2/37
Part 1 of 6 · Two limitsLearn and do

A cache can't keep everything: it runs out of room, and copies go stale

A cache keeps copies of answers that are slow to get: a database row, a page from another service, the result of an expensive function. When the same request comes again, the cache answers it, and the slow part is skipped.

A hit gives back what was stored. A miss is allowed: the caller goes to the real source.

What a cache can't promise is to keep everything, for two reasons, and every cache question in an interview is about one or both:

  • Memory is finite. When the cache is full and a new key arrives, an entry has to go. The rule that picks it is the eviction policy. LRU, least recently used, evicts the entry nobody has used for the longest time.
  • Copies go stale. The real data changes, so an entry stops being valid after a while. A time to live (TTL) is how long an entry may be served after it was written. After that it has expired, and a read must treat it as a miss.

Try the first limit before the figures show both:

Predict

Capacity 3 holds a, b and c, used in that order. put("d", 4) arrives, and the cache evicts the least recently used entry. Which key goes?

Pick an answer above to see the rest