SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Data Archiving and TTL

Move old data to cheaper storage, or let it expire automatically, so the main database stays small.

โฑ 11 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Data archiving moves old data you rarely need out of your main database into cheaper storage. TTL (time to live) makes data expire and disappear by itself after a set time.

  • The main database should hold the hot data people use now. Old data makes tables, indexes, backups and queries bigger and slower.
  • Archive = keep it, but somewhere cheap. TTL or delete = remove it once you no longer need it or are no longer allowed to keep it.
  • Removing a huge amount of data row by row is expensive. Smart systems drop whole time partitions instead.

02Concept: What is it?

Most data is useful for a short time. Last week's orders are read all the time. Orders from five years ago are read almost never. If you keep everything in the main database, it grows without limit, and everything about it gets slower and costs more.

There are three common answers. Archive the old data to cheaper storage (for example files in object storage). Expire it automatically with a TTL when a rule says it is no longer needed. Or delete it in a planned job. Many systems combine them: keep 90 days in the database, archive up to 7 years, then delete.

TTL is a setting on a row, key or document that says when it expires. Redis, DynamoDB, Cassandra, MongoDB and most time-series databases have a version of it. Expiry is usually done in the background, so data can stay a little longer than its TTL before it is physically gone.

The life of a piece of data
๐Ÿ”ฅMain databasehot, recent
โ†’โ†“after 90 days
๐Ÿ“ฆArchivecheap, rarely read
โ†’โ†“after 7 years
๐Ÿ—‘๏ธDeletedrule says it must go
Data moves from fast and expensive to slow and cheap, and finally leaves.
๐Ÿง Smaller hot data is faster data
Backups, index rebuilds, replication and queries all get faster when the main database only holds what is used. Cost falls too, because cheap storage costs a fraction of database disks.

03Real-Life Example

๐ŸตThe Office Filing Cabinet
An office keeps this year's invoices in a drawer next to the desk, because people ask for them every day. Older years go to boxes in the basement. They are still there, but fetching one takes a walk. After seven years the law lets the office throw them away, and a shredding company does it on a schedule. If the office kept every invoice on the desk forever, the desk would be buried and nobody could find anything.
The office
Data archiving and TTL
The drawer next to the desk
The main database (hot data)
Boxes in the basement
The archive (cheap, slower)
Moving last year's box downstairs
An archive job
Throwing away after 7 years
Deletion by retention rule
A shredder that runs by itself
TTL expiry
Taking out one page at a time
Row-by-row DELETE (slow, locks)
Throwing out a whole box at once
Dropping a whole partition (fast)
Two ways to remove a year of old rows
Row-by-row DELETE
Work and lockingmillions of deletes
๐ŸŒSlow, heavy log
Drop the old partition
Work and lockinga metadata change
โšกAlmost instant

04Why Do We Need It?

โšกFaster queries
Smaller tables and indexes mean less to scan and more of the working set fits in memory.
๐Ÿ’พFaster backups
Less data to copy, restore and replicate.
๐Ÿ’ฐLower cost
Cold storage costs far less per gigabyte than database disks.
๐Ÿ”’Privacy and law
Some rules require you to delete data after a set time. Others require you to keep it.
๐ŸงนLess clutter
Expired sessions, tokens, logs and caches should not live forever.
๐Ÿ“ˆPredictable growth
A retention rule turns endless growth into a steady size you can plan for.
Decide on purpose how long each kind of data lives, and automate it. Otherwise it lives forever and everything gets heavier.

05Where Do We Use It?

๐Ÿ”‘Sessions and caches
Redis keys with an EXPIRE time are removed on their own. See Key-Value Databases.
๐Ÿ“ˆMetrics and logs
Time-series databases have retention policies that drop old data, often keeping coarser summaries.
๐ŸงพOrders and transactions
Recent orders stay in the database. Older ones move to an archive for audits.
๐Ÿ“จEvents and messages
Brokers keep messages for a retention period, then delete them.
๐Ÿ—‚๏ธData lakes
Archived rows are often written as files (Parquet or CSV) into object storage.
๐Ÿ•ต๏ธPersonal data
Privacy rules may demand deleting a user's data after an account closes.

06Types / Parts / How It Works

Ways to get rid of old data

MethodHow it worksGood and bad
Row-by-row DELETEA job deletes rows older than the limitEasy to write. Heavy: locks, big logs, empty space left behind, and slow on huge tables.
Drop a time partitionThe table is split by day or month, and a whole old partition is dropped or detachedFast and light. Needs the table to be partitioned by time from the start. See Partitioning.
TTL / expiryEach row, key or document carries an expiry time and the database removes itNo job to write. Removal happens in the background, so it is not instant.
Archive then deleteCopy old rows to cheap storage (such as object storage), check them, then remove themKeeps the data for audits. Costs a copy step, and the archive must be searchable and restorable.
Soft deleteMark the row as deleted but keep itEasy to undo. The data is still there, so the table does not shrink and privacy rules may not be met.

TTL in common systems (behaviour in general terms)

How TTL expiry usually works
โœ๏ธWrite with TTLexpire in 1 hour
โ†’โ†“time passes
๐Ÿ™ˆExpiredreads no longer see it
โ†’โ†“background cleanup
๐ŸงฝRemovedspace is freed
A key is hidden from reads as soon as it expires, and physically removed a little later.

Where the archive lives

  • An archive table or database: still SQL, simple to query, but still costs database storage.
  • Files in object storage: very cheap (often Parquet or CSV). Queried with an analytics engine. See Object Storage.
  • A cold storage class: the cheapest, with slow or delayed retrieval and a fee to read. See Storage Tiers (Hot, Warm, Cold).
VisualizerA table that grows: keep everything, delete, drop partitions or archiveChange how many rows arrive each day and how long you keep them. Compare the size of the table, the query time and the nightly cleanup work for each strategy.
How is old data removed?

Every night a job deletes rows older than the retention. Deleting row by row is real work: it writes the log, holds locks and leaves empty space behind.

Rows in the main table over one year (grey = if you kept everything, cyan = with this strategy). Rows are in millions.
day 1day 183day 365
Rows in table
450 M
at day 365
Typical query
1355 ms
5480 ms if kept
Cleanup per night
2.5 min
row-by-row delete, with locks and log
In cheap storage
0 M
still available
The table stays at 450 M rows, but each night's DELETE of 5 M rows takes about 2.5 minutes and holds locks. Delete in small batches and off peak hours, or switch to dropping partitions.

A simplified model with exact arithmetic (no random numbers). The query time (5 ms plus 3 ms per million rows), the delete speed (2 M rows a minute), the 1 second partition drop and the copy speed are made-up numbers for teaching, not measurements. Real databases behave differently, and a good index keeps many queries fast on a big table.

07How to Use It / Steps / Implementation

Putting a retention policy in place

  1. 1
    Classify the data
    For each kind of data, ask how long it is used, how long it must be kept by law, and when it must be deleted.
  2. 2
    Write the retention rule down
    For example: 90 days hot, 7 years archived, then deleted. A rule nobody wrote down is a rule nobody follows.
  3. 3
    Plan for removal from the start
    For time-based tables, partition by time, so old data can be dropped as a whole partition.
  4. 4
    Use TTL where it fits
    For sessions, caches, tokens and events, set an expiry when you write the data, not later in a cleanup job.
  5. 5
    Archive safely
    Copy, verify (count rows, check a sample), then remove. Keep the archive in a format you can still read in years.
  6. 6
    Delete in small batches
    If you must delete row by row, do it in small batches, off peak, and watch the load on the database and replicas.
  7. 7
    Handle references and holds
    Check foreign keys and related data. Respect legal holds that stop deletion.
  8. 8
    Test the way back
    Pick an archived record and restore it. An archive you cannot search or restore is not an archive.
๐Ÿ’กDrop, do not delete
Removing a month of rows by dropping a partition takes a moment, whatever the size. Deleting the same rows one by one can run for hours and slow everyone else down.
โš ๏ธBackups also hold the data
A deleted row can still live in old backups. If a rule says data must be gone, include the backup retention period in your plan.

08Key Terms to Know

TermMeaning in easy words
RetentionHow long a kind of data is kept
TTL (time to live)A per-row, per-key or per-document expiry time after which the data is removed
ArchiveCheaper storage for data that is kept but rarely read
Hot dataRecent data that is read and written often
Cold dataOld data that is rarely read
Partition dropRemoving a whole partition, which is a quick metadata change
Soft deleteMarking a row as deleted without removing it
Hard deletePhysically removing the data
Legal holdAn order that stops deletion of certain data
Lazy expiryRemoving expired data when it is next read, or in the background, not at the exact moment it expires
Compaction / vacuumCleanup that frees space left behind by deletes

09Pros, Cons and Trade-offs

โœ… Pros
  • Smaller, faster tables and indexes
  • Faster backups and restores
  • Lower storage cost
  • Helps meet privacy and retention rules
  • Steady, predictable growth
โš ๏ธ Cons
  • Needs rules, owners and testing
  • Archived data is slower to reach
  • Mass deletes can hurt the live database
  • Deleted data may live on in backups
  • A wrong rule can destroy data you still needed

Trade-offs

ChoiceWe gainWe lose
Short retention in the databaseSmall, fast, cheapOld data is slower or harder to reach
Long retention in the databaseEverything is one query awayBigger tables, slower, costlier
Partition by timeInstant removal of old dataPlanning up front, and queries across partitions need care
Row-by-row DELETEWorks on any tableHeavy load and locks, slow on big tables
TTLNo cleanup job, automaticNot instant, and a wrong TTL silently drops data
Soft deleteEasy undo, an audit trailThe table keeps growing, and privacy rules may not be met

10Common Problems and Mistakes

Common mistakes

  1. No retention rule at all. The table grows forever, and the first sign is a slow, expensive database.
  2. One giant DELETE. It locks rows, floods the log, delays replicas and may run for hours.
  3. Deleting before verifying the archive. The copy failed and the original is gone.
  4. Forgetting related data. Child rows, files and search indexes keep pointing to data that is gone.
  5. Ignoring legal holds. Deleting data that must be kept is as bad as keeping data that must go.
  6. Trusting TTL to be exact. Expiry can lag. Do not rely on it for security-critical timing.
  7. Forgetting backups. A "deleted" record can come back from a restore.

Things to watch

๐ŸŒŠDelete storms
Many keys with the same TTL expire at once and cause a burst of cleanup work. Spread the expiry times.
๐Ÿ•ณ๏ธEmpty space
A delete frees rows, not always disk space. Plan compaction or vacuum.
๐Ÿ”Findability
Archived data needs an index or catalog, or nobody can find a record.
๐Ÿ“Schema drift
Old archived files have the old columns. Keep a note of how to read each version.

11Real-World Examples

๐ŸงพOrders
Recent orders stay in the live database for support. Older ones are exported to files in object storage for audits.
๐Ÿ“ŠMonitoring
Raw metrics are kept for days. Coarse summaries are kept for months or years, and the rest is dropped.
๐Ÿ”‘Sessions
A login session is stored with a TTL, so abandoned sessions disappear with no cleanup code.
๐Ÿ“จMessage brokers
Events are kept for a set period so consumers can catch up, then removed.
๐Ÿ‘คAccount deletion
A privacy request starts a job that removes or anonymises a user's data across systems within a deadline.
๐Ÿ“œLogs
Recent logs are searchable. Older logs are compressed to cheap storage, then deleted.
๐Ÿ“Note
TTL behaviour, limits and costs differ by product and version. Check the documentation of the system you use.
Mini case: an orders table
๐Ÿ—„๏ธOrders tablelast 90 days
โ†’โ†“monthly job
๐Ÿ—ƒ๏ธParquet filesobject storage, 7 years
โ†’โ†“after 7 years
๐Ÿ—‘๏ธDeleted
Hot Archive Gone
Retention rules turn a table that grows forever into a steady size.

12Related Topics to Read Next

Partitioningโ†’

Splitting by time makes dropping old data instant.

Storage Tiers (Hot, Warm, Cold)โ†’

Where archived data should live, and what it costs.

Object Storageโ†’

The usual cheap home for archived files.

Time Series Databasesโ†’

Built-in retention and downsampling.

Key-Value Databasesโ†’

TTL per key is a core feature.

Cache Eviction Policiesโ†’

Another way of deciding what to throw away.

Indexingโ†’

Smaller tables mean smaller indexes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: archive = move old data to cheap storage. TTL = data expires by itself.
  • โœ”Why: smaller, faster, cheaper, and rules about how long you may keep data.
  • โœ”Best removal: partition by time and drop old partitions. Avoid giant DELETEs.
  • โœ”TTL: good for sessions, caches and events. Removal is background, not instant.
  • โœ”Archive safely: copy, verify, then remove. Keep it findable and restorable.
  • โœ”Watch: backups, replicas, search indexes and legal holds also hold the data.
  • โœ”Plan: write the retention rule down for every kind of data.
  • โœ”One line: โ€œKeep the hot data close, the old data cheap, and let the expired data go on a schedule.โ€
โ† Previous
Point-in-Time Recovery
Next โ†’
Block Storage