Module 4 · Caching and performanceLesson 38 of 885 minBeginner
Time to live (TTL)
A TTL is an expiry time on a cached value. It's the dial between fresher data and fewer trips to the database.
Set the TTL to "forever" and watch stale answers grow. Then lower it step by step and watch database reads rise as staleness falls.
A TTL (time to live) tells the cache how long to keep a value. After that, the entry is treated as missing and the next request fetches a fresh copy.
Picking a TTL
Think about two things:
- How stale can this be? That's your maximum TTL.
- How often is it read? The more reads, the more a longer TTL saves.
Rough examples:
| Data | Typical TTL |
|---|---|
| Stock price in a trading app | No cache, or under a second |
| Product page | 1 to 10 minutes |
| User profile | 5 to 60 minutes, plus delete on write |
| Country list, config | Hours to a day |
| Hashed static files (app.3f9a.js) | A year |
Jitter
If a thousand keys were cached at the same time with the same TTL, they all expire together and the database sees a thundering herd of misses. Adding a little randomness, say a TTL of 10 minutes plus or minus 1, spreads the expiries out.
TTL is a safety net
Even when you delete keys on write, a TTL guarantees that any value the code forgot to invalidate will eventually correct itself. Very few production caches should hold data with no TTL at all.
TTLs elsewhere
The same idea shows up all over system design: DNS records, HTTP Cache-Control: max-age, session lifetimes, distributed lock leases. In each case it's the same trade: freshness against work.