Skip to content

Redis / caching · 6 of 10

Negative caching

Step 1 · The pattern

Found once, served from the cache

Most reads are for popular products that are already in the cache, so they never reach the database. A few are for products not yet cached. Those go to the database once and are stored on the way back.

  • served
  • on its way

In short

Negative caching: how it works and how it breaks

A read-through cache checks the cache, and on a miss asks the database and stores the answer. That works for anything that exists. A lookup for something that does not exist is different: the database returns nothing, so nothing is stored, and the next lookup for the same id misses again. Every such request reaches the database, however healthy the cache is. This is often called cache penetration. The traffic comes from deleted products that are still linked, crawlers walking id ranges, or an attacker choosing ids on purpose. The hit ratio for real keys stays high, so the cache looks fine while the database is saturated. The repair is negative caching: store a short-lived marker that says not found, so repeats are answered by the cache. Keep its lifetime short, and remove the marker when the item is created.

What this simulation simplifies

  • With the fix on, every lookup for a missing id is answered by the cache. In reality the first lookup for each id still reaches the database once per marker lifetime.
  • The crawler here repeats a limited set of ids. A scan over ids that never repeat is not helped by cached markers alone.

How this comes up in interviews

"The cache is working and its hit ratio is high, but the database is still at 100%. Where would you look?"

Then they ask

  1. How long would you cache a not-found answer, and what breaks if it is too long?
  2. Negative caching does not help against a scan of millions of distinct ids. What does?
  3. Why should a database timeout not be cached as not found?

A strong answer covers

  • A hit ratio hides volume. Count misses per second and compare with what the database can serve.
  • Lookups for missing ids store nothing, so every repeat is a database query.
  • Cache a short-lived not-found marker, and delete it when the item is created.
  • For many distinct ids, a Bloom filter of existing ids rejects most of them without a query.
  • Rule out the other causes: writes, uncached query types, and keys expiring together.

Points to cover, not a script. Say them in your own words and tie them to a system you have worked on.

On one page: the track cheat sheet.

Last updated: Engineering write-up

Diagrams are our own simulations: the timings, rates and counts in them are illustrative, not measurements. Captions are original wording.