← Building blocks

Expire data automatically

Storage & data modellingfundamental

Sessions, links and tokens must disappear after a while without a cleanup job.

Say it like this

Links and sessions carry an expires_at, the store deletes them on a TTL in the background, and every read still checks the timestamp so a late sweep never serves an expired record.

Basic solution

Store an expires_at and set a TTL on the row or key; check on read (lazy) and sweep in the background (active).

Redis EXPIREDynamoDB TTLCassandra TTLcron sweeper

Lazy check on read, active sweep in the background

Every read compares expires_at and refuses expired rows immediately. A sweeper deletes them in batches later; the cache TTL is capped to the remaining lifetime so it cannot outlive the row.

How it works

  1. When a record is written, the service computes expires_at = now + lifetime and stores it as a column on the row, or it sets a TTL directly on the key (SET key value EX 3600 in Redis), which tells the store to delete the key after 3,600 seconds.
  2. When a record is read, the service compares expires_at with the server clock. If the time has passed, it treats the record as missing (returns 404 or 410 to the client) and may delete the row on the spot. This is lazy expiry: the check costs one comparison on a row already fetched.
  3. In the background, either the store itself or a sweeper job finds rows whose expires_at is in the past and deletes them in batches. This is active expiry: it reclaims the disk space that lazy expiry alone would leave behind.
  4. Any cache holding the record is written with a TTL no longer than the time remaining until expires_at, so the cache entry cannot survive the row it copies.
  5. Keys or ids freed by expiry are returned to the pool for reuse only after the sweeper has deleted the row, never from the lazy path, so a stale reference can never resolve to someone else's record.

Why both lazy and active

  • Lazy expiry alone leaves dead rows on disk forever if nobody reads them.
  • Active expiry alone has a delay between the deadline and the sweep, so a read in that window would serve stale data.

Worked example

URL shortener with expiring links

  • 100M links per month, 30% created with a 30-day expiry. That is 30M rows a month that must stop redirecting and free their aliases.
  • Lazy path: on GET /{alias}, the redirect service compares expires_at with now. The check is one integer comparison on a row it already fetched, so it costs nothing.
  • Active path: a sweeper runs every 10 minutes, DELETE ... WHERE expires_at < now LIMIT 10,000, looping until no rows match. 30M rows per month is about 700 per minute, so each run deletes roughly 7,000 rows in a few hundred milliseconds.
  • Cache: the Redis entry is written with EX = seconds until expires_at, capped at 300. A link expiring in 90 seconds gets a 90-second cache TTL, so the cache and the row expire together.
  • Key reuse: aliases of expired rows return to the key pool only after the sweeper has deleted the row, so a user who bookmarked an old link gets 410 Gone rather than someone else's destination.

Rate limiter counters

  • A fixed-window counter per user lives in Redis with EXPIRE = 2 × window. Idle users cost nothing because their keys vanish; 10M users × 60 bytes is 600 MB only while they are active.

Variants and when each wins

Store-native TTL (Redis EXPIRE, DynamoDB TTL, Cassandra TTL)

  • The store deletes expired items itself with no application code. It wins for simplicity, but deletion is best-effort: DynamoDB can lag by a few days and Cassandra leaves tombstones that cost every read until compaction.

Lazy expiry only

  • The service checks on read and never sweeps. It wins for data that is always read before its expiry matters, such as sessions, but storage grows without bound.

Sweeper job

  • A scheduled job deletes expired rows in batches, using an index on expires_at to find them. It wins when you need control over timing and load, at the cost of one more job to run and monitor.

Partition by time and drop

  • Rows are stored in daily or hourly partitions and whole partitions are dropped when they age out. It wins for logs and events with a uniform retention, because dropping is instant and leaves no tombstones.

Pick store-native TTL plus a read-time check by default; add a sweeper when the store's TTL is too slow or absent; use partition drops for logs and events with a fixed retention.

Failure modes

Expired record still served

  • A link keeps redirecting for hours after its deadline. It happens because the service relied on the store's TTL, which is best-effort and delayed. Always compare expires_at on read; the TTL is for reclaiming space, not for correctness.

Cache outlives the row

  • The row is gone but the cache still answers. It happens because the cache TTL was a fixed five minutes regardless of how long the record had left. Set the cache TTL to the smaller of the default and the seconds until expires_at, and evict the cache key on explicit delete.

Sweeper takes locks or floods replication

  • Latency spikes every ten minutes when the sweeper runs. It happens because one DELETE removes millions of rows in a single transaction, holding locks and generating a flood of replication log. Delete in small batches with LIMIT, sleep briefly between batches, and index expires_at so each batch is a range scan rather than a table scan.

Tombstone build-up

  • Reads on Cassandra or another LSM store slow down over weeks. It happens because each expired row becomes a tombstone that every read must skip until compaction removes it. Store such data in time-partitioned tables that are dropped whole, or tune gc_grace and compaction.

Key reused too early

  • An old bookmark lands on a stranger's link. It happens because the alias was returned to the pool on the lazy path, before the row was actually deleted. Reclaim keys only from the sweeper, after a grace period.

Interviewer follow-ups

Answer out loud before you open each one.

If the store already deletes expired rows, why check expires_at on every read?

Store TTLs are best-effort and can lag minutes to hours, and a replica or cache may still hold the row. The read-time check is one comparison and is the only thing that makes expiry exact from the user’s point of view.

How do you sweep a table with a billion rows without hurting production?

Index expires_at, delete in batches of a few thousand with LIMIT, sleep briefly between batches, and run from a replica-aware job that pauses when replication lag grows. If the lifetime is uniform, partition by time and drop partitions instead.

What happens to a cached copy when the row expires?

Nothing, unless you planned for it. Set the cache TTL to the remaining lifetime at write time, and on explicit deletes evict the cache key as part of the delete path.

When would you not use a TTL at all?

When the data has legal or audit value (orders, payments), when deletion must be acknowledged to the user, or when the lifetime depends on business rules rather than a timestamp. Those cases want an explicit archival job, not a silent expiry.

Connections

Pairs with
Invalidate the cache when data changes · Run work later or on a schedule · Delete without losing history · Limit requests per client
Pulls against
Recover from bad data, not just dead disks
Used in
URL Shortener (TinyURL / bit.ly) · Distributed Rate Limiter

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRedirect service, Sweeper jobCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheRedisMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon AuroraURL storeAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB