İçeriğe geç
wedevit

November 16, 2026 · 9 min read · software

İlhan Buğra Aslan

The database grows every month and nothing is ever deleted: how to build a data retention and archiving policy


A data retention policy fits on one page: for each class of data, how long it stays in the live database, where it goes next, how long it is kept in total, how it is deleted, and who owns that decision. Until that page exists, database growth is not a decision anyone made. Nobody dares delete anything, because nobody has written down what may be deleted. Two things set the numbers. The floor comes from regulation, and in Turkey article 82 of the Turkish Commercial Code requires ten years for commercial books, financial statements and business correspondence, counted from the end of the calendar year in which the last entry was made (TCC article 82). The ceiling comes from operations: when did anyone last actually open this record? Everything between those two lines is a choice, and every extra month has a price.

Measure what is actually growing

The conversation usually starts with "the database is bloated, let's delete something" and stops there, because nobody has numbers per table. Start with a ten-line list: the ten largest tables, data and index size for each, and monthly growth over the last six months. Most teams that produce this list land in the same place. The volume is not in customer records. It is in machine data.

The usual suspects are predictable: application event logs, audit trail tables, webhook delivery attempts, notification and email send records, raw files kept from imports, and rows that were soft deleted but never actually removed. Almost none of it is read inside the product. The problem is not that you keep it. The problem is that you keep it in the live database.

Look at index sizes separately. On log-shaped tables, indexes grow faster than the data itself, because over the years every new field got an index and none were ever dropped. Behind a slow query complaint there is sometimes no bad plan at all, just an index set that no longer fits in the server's memory.

The retention schedule fits on one page

The body of the policy is a table with six columns: data class, time in the live database, next destination, total retention, deletion method, owner. Do not leave the owner column empty. A row with no owner turns into "let's not touch that for now" within six months.

Separating classes is the whole point. Orders and invoices have to stay accessible for the period the law sets. Thirty to ninety days of application event logs is enough for most teams. The audit trail lives longer, because its value is answering questions about the past. Webhook delivery attempts and temporary processing records are measured in weeks. On the tax side, article 253 of the Tax Procedure Law sets five years counted from the calendar year following the one the records belong to, so two different rules give two different periods and the longer one governs.

The most common mistake is announcing a single period for the whole database. "We keep everything for ten years" applies the longest obligation to the cheapest data, and nobody argues with it because it looks like the safe side. For records that contain personal data, settle the period with your legal counsel; that part is not an engineering decision.

Deleting rows does not free disk space

The first surprise after the policy is written: you delete millions of rows and disk usage barely moves. The PostgreSQL documentation is explicit about why. Standard VACUUM removes dead row versions and marks the space available for reuse, but it does not return that space to the operating system, except when pages at the very end of a table become entirely free (PostgreSQL 18, routine vacuuming). Getting the space back means VACUUM FULL, which rewrites the table, takes an ACCESS EXCLUSIVE lock for the duration, and needs extra disk space for the new copy. In other words, the moment you need it most, when the disk is already full, is the moment you cannot run it.

MySQL arrives at a similar place with different names. For InnoDB tables, OPTIMIZE TABLE maps to ALTER TABLE ... FORCE, which rebuilds the table and frees unused space in the clustered index; it uses online DDL, so the exclusive lock is taken only briefly during the prepare and commit phases (MySQL 8.4 reference). An intermediate table is created, so again you need free space to free space.

The practical conclusion: removing two hundred million rows with a single DELETE is the worst available option on a live system. The long transaction delays replication, inflates the write-ahead log, and blocks writers. Chunked deletes with a pause between batches work, in tens of thousands of rows per round. Better still, if you design deletable data to be deletable from day one, you skip most of this work entirely.

Partitioning: detach instead of delete

For tables that grow with time, the right tool is partitioning. In the words of the PostgreSQL documentation, dropping an individual partition with DROP TABLE or running ALTER TABLE DETACH PARTITION is far faster than a bulk operation, and these commands entirely avoid the VACUUM overhead caused by a bulk DELETE (PostgreSQL 18, partitioning). The same page covers partition pruning, which is the side benefit of a retention design: the planner proves that a partition cannot contain matching rows and excludes it from the plan. Queries get faster even before any data goes away.

The setup is simple enough. Partition the event table by month, create next month's partition ahead of time, and when a partition passes its retention age, detach it and either write it to the archive and drop it, or just drop it. Deletion stops being a row operation and becomes a metadata operation.

It is not worth doing for every table. The same documentation notes that these benefits are normally worthwhile only when a table would otherwise be very large, with a rule of thumb that the table size should exceed the physical memory of the database server. Three caveats matter. Pruning only works if your queries carry the partition key. Unique constraints must include that key. And converting an existing huge table is not a one-shot job; it needs a zero-downtime plan.

A backup is not an archive

Two jobs get conflated constantly. A backup exists to return to a recent state; its retention is short and its real measure is a tested restore. An archive exists so old data can still be read; its retention is long and its real measure is whether anyone can open it years later.

"We keep backups for ten years" is therefore not an archiving policy. Restoring a six-year-old dump requires that day's schema, that day's application version, and usually that day's libraries. The data exists in theory and nobody can read it in practice. Write the archive in a form that stands on its own: a columnar file format that carries field names and types alongside the values, or a separate archive schema with its own documented structure. Once that line is drawn, the 3-2-1 backup rule governs the backup side and the retention schedule governs the archive side, and neither pretends to be the other.

Cold storage is cheap, retrieval is not

Moving data to object storage is cheap, and the cheapness comes with rules. In the AWS S3 Glacier classes, the minimum storage duration is 90 days for Instant Retrieval and Flexible Retrieval and 180 days for Deep Archive; delete, overwrite or transition an object before that and you are still charged for the remaining days (S3 Glacier storage classes). Moving data there as an experiment and changing your mind two months later means paying for six.

Retrieval times split the classes apart. In Flexible Retrieval, expedited requests typically restore an object in 1 to 5 minutes, standard in 3 to 5 hours, and bulk in 5 to 12 hours, with bulk retrievals free. In Deep Archive, standard restores typically complete within 12 hours and bulk within 48. Pick the class by answering one question rather than by comparing per-GB prices: when somebody asks for this data, how long can they wait?

Small objects are a separate trap. Glacier Flexible Retrieval and Deep Archive require 40 KB of extra metadata per object, 8 KB of which is billed at the S3 Standard rate, and Glacier Instant Retrieval has a 128 KB minimum object size. Archiving millions of tiny records one by one costs noticeably more than packing them into monthly bundles. That detail is why some teams who moved to archive storage to cut their cloud bill never saw the savings they modelled.

Reading from the archive is a product decision

Before moving anything, answer this: what does a user see when they open an order from three years ago? There are three reasonable answers. The summary row stays live and the detail is fetched from the archive on demand. Or you set a visible cutoff and say plainly on screen what happened to older records. Or the request becomes a background job and the user gets a notification when the data is ready.

The wrong answer is no answer. A screen that shows "Something went wrong" gives back in support tickets whatever the archiving project saved in storage. Write the error and empty states for this case up front. Review report filters too: if a user can select "last 5 years", the report has to know where that data physically lives.

Deletion never happens in one place

Removing a row from the live table is where the work starts. The same data sits in read replicas, the search index, caches, the analytics warehouse, exported files, log lines, and whatever third-party services you send it to. Turn deletion into a written checklist per data class, covering every copy, or "we deleted it" becomes a sentence that is not true.

The relationship between soft delete and retention also needs to be explicit. A soft-deleted row still occupies the table, takes up space and slows down queries, so a separate job has to hard delete it once the recovery window closes. Give the policy a pause switch as well: when records are subject to a legal dispute, deletion stops, and who decided that and when gets recorded.

Put the policy in code, not in good intentions

Work scheduled as "we'll clean up once a year" does not happen. Turn the retention rules into a scheduled job, and run the first version in dry-run mode that only produces a report: how many rows from which class would have been deleted, how many GB would have been freed. Watch that report for a few weeks, and when the numbers match what you expected, switch on real deletion.

Three controls are enough. Alert when the job does not run. Stop and ask for human approval when the deleted row count jumps to several times the normal. Have every run write what it deleted and under which rule to the audit log, because the first question anyone asks is "where did this record go". Put disk usage and the growth rate of the largest tables on your monitoring dashboard too; that is the fastest way to notice a retention policy that quietly stopped working.

A two-week first step

Four pieces of work. Produce the size and monthly growth of your ten largest tables. Write the retention schedule per data class on one page and confirm the legal floor with your accountant and counsel. Convert the fastest-growing machine-data table to monthly partitions. Turn on the deletion job in dry-run mode and watch the numbers for two weeks.

Do not start building archive infrastructure before those four are done; for most teams the first two already solve the larger part of the problem. If you would rather go through your current tables together and work out what belongs where, an hour on a call is usually enough to get the plan straight.


Need help with this topic?

get in touch →← all posts