Try
↑ ↓ move↵ openesc close

Interview prep / Caching

Junior · Caching · System design interview question

You are caching a user's profile page. How do you pick a time-to-live, and what goes wrong if it is too short or too long?

Sketch your own answer first, then compare it with the one below.

A strong answer

The TTL is the longest time you are willing to show out-of-date data, so start from the product, not from the cache. Ask what harm a change that appears 30 seconds late would cause. For a display name, none. For a permission change, possibly a lot.

Too short and the cache stops helping. If a key is requested at random about once a minute and the TTL is 60 seconds, the hit fraction is about r × T / (1 + r × T) = 1 / 2, so half of the requests miss. A 10-minute TTL for the same key gives 10 / 11, about 91 percent.

Too long and users see stale or deleted data. Dead entries also hold memory until they expire.

The usual pattern pairs a moderate TTL with explicit invalidation on write. The invalidation keeps data fresh in the normal case, and the TTL is the backstop for the invalidations that get lost. Add a little random jitter to each TTL so a batch of keys written together does not all expire together.

Different data deserves different lifetimes. A profile picture can live for hours, an account balance for seconds or not at all.

Sources

  • Roy T. Fielding, Mark Nottingham, Julian Reschke (2022). HTTP Caching.

Learn it by running it

The caching and eviction lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms