Scrivio Interview library
ConceptFoundations7 min read · updated 13 November 2026

Every cached value needs a lifetime. A TTL that is too short wastes the cache, one that is too long serves stale data, and identical TTLs can make many entries expire at the same moment.

How do you choose a TTL for a cached value, and what are absolute expiry, sliding expiry, TTL jitter and a TTL used as a safety net?

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

We choose a TTL from how long stale data is acceptable and how often the source changes: seconds for prices or stock, minutes for product details, hours for reference data. Absolute expiry counts from the write and bounds the age of a value, sliding expiry counts from the last access and keeps popular entries alive. Jitter randomizes TTLs so entries written together do not expire together, and a maximum TTL kept even with event-based invalidation is the safety net that bounds any missed invalidation.

Why this question is asked

Every cache entry needs a lifetime, and the number we pick decides both how useful the cache is and how wrong it can be. Interviewers ask this because many production incidents come from TTLs that were set once by guessing: data stale for an hour, or a wave of misses at the top of the hour. In this answer, we will recap what a TTL does, choose one from the data's needs, compare absolute and sliding expiry, add jitter, see why a TTL stays useful even with invalidation, and look at not-found results and how to review TTLs over time.

1A Quick Recap of TTLs

A TTL, time to live, is how long a cache keeps an entry before treating it as gone. In Redis we set it with SET key value EX 600, and the key disappears 600 seconds later. In Caffeine, the in-process Java cache, we set it with expireAfterWrite or a custom Expiry.

The TTL pulls in two directions. Too short, and the cache keeps reloading values that had not changed, so the hit ratio drops and the database does the work the cache was meant to save. Too long, and users see data that changed at the source a while ago. There is no universal right value; there is a right value for each kind of data.

2Choosing the Number

Start with two questions about the data. How long may a reader see an old value before it hurts? And how often does the value really change? The TTL should be no longer than the first answer, and there is little point making it much shorter than the second.

A price or stock level shown on a busy page may be acceptable for 10 to 30 seconds, but not for an hour. Product descriptions change a few times a month, so 10 to 30 minutes is fine. Country lists, currency codes and feature catalogues change rarely, so hours or a day is fine. If the application also deletes the entry whenever the data changes, the TTL is no longer the main freshness mechanism; it becomes the upper bound on staleness when an invalidation is missed.

Typical starting TTLs
DataChangesStarting TTL
Price, stock on a listingMany times a day10 to 30 seconds
Product detailsA few times a month10 to 30 minutes
Reference dataRarelyHours, up to a day
Not-found resultWhen the item is created30 to 60 seconds
Anything with invalidationOn every writeMax TTL as a safety net
Starting points to measure against, not fixed rules.

3Absolute and Sliding Expiry

Absolute expiry counts from when the entry was written. A value written at 10:00 with a 10-minute TTL is gone at 10:10 no matter how often it was read. Sliding expiry counts from the last access: every read pushes the expiry forward, so an entry only disappears after it has been idle for the whole TTL.

Java
Cache<String, Product> products = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(10)) // absolute: never older than 10 minutes
.maximumSize(50_000)
.build();
Cache<String, Session> sessions = Caffeine.newBuilder()
.expireAfterAccess(Duration.ofMinutes(30)) // sliding: gone after 30 idle minutes
.build();
// Redis: GETEX reads and resets the TTL, which gives sliding expiry
// GETEX session:ab12 EX 1800 -> "{...}" and the key now lives 1800 s more

The difference matters for data that changes at the source. With sliding expiry, a product read every few seconds never expires, so a change that was not invalidated would be served forever. That is why sliding expiry suits sessions and other data the cache itself owns, where idle time is the right measure, and absolute expiry suits copies of data that lives elsewhere, where the age of the copy is what we want to bound.

4Adding Jitter

Suppose a job warms 100,000 entries at 09:00, all with a 10-minute TTL. At 09:10 they all expire together, and the next requests for all of them miss at the same moment and go to the database. Then they are all reloaded around 09:10 and expire together again at 09:20. The cache has turned a smooth load into a wave every ten minutes.

Jitter breaks the wave by adding a small random amount to each TTL, for example 10 minutes plus or minus 10 percent.

Java
long base = 600; // seconds
long ttl = base + ThreadLocalRandom.current().nextLong(-60, 61); // 540 to 600 to 660
redis.opsForValue().set(key, json, Duration.ofSeconds(ttl)); // one SET ... EX command

Now the 100,000 entries expire over two minutes instead of one second, and the reloads spread out with them. After a few cycles the expiry times are completely spread. Ten percent is a common choice; more spreads further but makes the effective TTL less predictable.

5A TTL as a Safety Net

Teams that delete cache entries on every write sometimes ask why they still need a TTL. The answer is that invalidation can fail: a message is lost, a code path writes the database directly, a bug writes the wrong value, or a consumer falls behind. Without a TTL, a wrong value stays until someone notices. With a maximum TTL, say one hour, any mistake heals itself within an hour.

The TTL also reclaims memory. Keys nobody reads anymore expire instead of waiting to be evicted, and the eviction policy is left to handle real pressure. So the rule is simple: every cache entry has a TTL, even when something else is responsible for freshness.

6Not-Found Results and Reviewing TTLs

When a lookup finds nothing, caching that answer stops repeated requests for the same missing id from reaching the database. But a missing item can be created at any moment, so a not-found result gets a much shorter TTL, 30 to 60 seconds, than a found one, and the create path should delete it.

Finally, TTLs are not set once. Each cache should report its hit ratio, and where possible how often it served a value that differed from the source. If the hit ratio is low and staleness is never a complaint, the TTL may be too short; if users report old data, it is too long or invalidation is missing. Reviewing these numbers a few weeks after launch is where the guesses become decisions.

7Follow-up questions

When is a TTL of zero, meaning no caching, the right answer?

When a stale value is never acceptable, such as a balance checked before a payment or stock reserved at checkout; when values are rarely read twice, so the hit ratio would be near zero and the cache only adds memory and a network hop; and when loading is already cheap, such as a primary key lookup on a small, well-indexed table. In those cases the cache adds risk or cost and saves little.

Does Redis remove a key at the exact moment its TTL ends?

Not physically. A read of an expired key always returns nothing, so from the client's view it is gone on time. The memory is reclaimed either when the key is touched, or by a background cycle that samples keys with TTLs and deletes expired ones. Under heavy load expired keys can linger briefly, but they never come back.

Should all entries in one cache have the same TTL?

Not necessarily. Entries of different value or volatility can get different TTLs, and Caffeine's Expiry interface or a per-key SET ... EX in Redis allows that. Hot items that change often may get shorter TTLs than cold reference items in the same cache.

8Conclusion

In this answer, we saw that a TTL comes from how long staleness is acceptable and how often the source changes, from seconds for prices to hours for reference data. Absolute expiry bounds the age of a copy and suits data owned elsewhere, while sliding expiry keeps busy entries alive and suits sessions. Jitter spreads expiry so entries written together do not expire together, a maximum TTL stays as a safety net even with invalidation, not-found results get short TTLs, and TTLs are reviewed with hit ratio and staleness metrics.

What to say in the interviewAbout 80 seconds aloud

Open with

I pick a TTL from two things: how long a reader can tolerate a stale value, and how often the value changes. Prices and stock get seconds, product details minutes, reference data hours.

Then, if they want more

If writes delete the entry, the TTL is just the upper bound on staleness when an invalidation is missed. Absolute expiry counts from the write, so a copy is never older than the TTL; that is right for data that lives in a database.

Sliding expiry counts from the last read, so popular entries never expire; that suits sessions, but for source data it means a missed change could be served forever.

Jitter means randomizing each TTL a little, say ten minutes plus or minus ten percent, so a batch of entries written together does not expire together and send a wave of misses to the database.

And even with event-based invalidation I always keep a maximum TTL, because invalidation can be lost or buggy, and the TTL makes the cache heal itself and frees memory from keys nobody reads. Not-found results get a much shorter TTL, like 30 seconds.

Then I look at hit ratio and staleness after launch and adjust, because the first TTL is always a guess.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you choose a TTL for a cached value, and what are absolute expiry, sliding...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/55c1bd9a60/