← Lessons

quiz vs the machine

Silver1100

Databases

Time to Live and Expiry

A time to live lets the database delete data automatically after a set lifetime instead of relying on cleanup jobs.

4 min read · intro · beat Silver to climb

Data That Should Not Live Forever

Some data is only useful for a while. A session token, a cached result, or a one time code becomes useless after a period. A time to live, or TTL, tells the database how long an item should live, after which it is expired and removed automatically.

How TTL Works

  • You set a TTL when writing an item, either as a duration or an absolute expiry time.
  • Once the item passes its expiry, reads treat it as gone even before it is physically deleted.
  • A background process reclaims the space later, so deletion is lazy rather than instant.

Why It Helps

  • It removes the need for a separate cleanup job to find and delete old data.
  • It keeps caches and session stores from growing without bound.
  • It expresses the intent that the data is temporary right where it is written.

Things to Watch

Expiry is usually approximate, so an item may linger briefly past its TTL before the cleanup pass removes it. Never rely on TTL for precise timing or for security critical immediate deletion.

Key idea

A time to live marks data as temporary so the database expires and removes it automatically, though cleanup is lazy and expiry timing is only approximate.

Check yourself

Answer to earn rating on the learn ladder.

1. What happens when an item passes its TTL?

2. Why should you not rely on TTL for security critical immediate deletion?