DesignTheSystem/dev
System Design (HLD) 7 min read

Caching reads: cache-aside and hit rate

Put a cache in front of a database and work out how much load it really takes off.

Why reads hurt first

Most products read far more than they write: a link is created once and opened thousands of times. Every read that reaches the database uses a connection and disk time, so the database is usually the first thing to fall over.

A cache keeps recent answers in memory. Memory answers in about a millisecond; a database query takes 5 to 50.

Cache-aside, step by step

The server asks the cache first. On a hit it returns straight away. On a miss it reads the database, stores the answer in the cache with an expiry (TTL), then returns it.

Writes go to the database, then delete the cached copy, so the next read fetches the new value.

read(key):
  value = cache.get(key)
  if value: return value          // hit: ~1 ms
  value = db.query(key)           // miss: ~20 ms
  cache.set(key, value, ttl=300)  // keep it for 5 minutes
  return value

The number that matters: hit rate

The database only sees the misses. At 10,000 reads a second and a 90% hit rate, the database gets 1,000 a second. At 99%, it gets 100: ten times calmer for nine extra points.

Hit rate depends on cache size and how skewed the traffic is. If 20% of items get 80% of reads, a cache holding that 20% catches most traffic. The simulator works the same way: the cache's hit rate comes from how much of the data fits in its memory.

Key takeaways

  • The database only sees cache misses: reads × (1 − hit rate).
  • Cache-aside: read the cache, fall back to the database, then fill the cache.
  • On a write, update the database and delete the cached copy.

Try it in the simulator: Watch a cache take the load

Put this concept into practice on Design Pastebin Text Sharing:

  1. Connect Client → Load balancer → API servers → PostgreSQL and run it. Note the database's load and the p99.
  2. Add a Redis cache and connect the API servers to it as well as to PostgreSQL. Reads now try the cache first (cache-aside). Run again.
  3. Select the cache and raise its memory per node, running after each step.

What to watch: With the cache, p99 falls back under the 60 ms target. As the cache gets more memory it holds more of the popular data, so fewer reads miss and the database's load keeps dropping.

Check your understanding

Answer these questions interactively to test what you learned and track progress on your skill map:

  1. 20,000 reads a second hit a cache with a 95% hit rate. How many reach the database?
  2. With cache-aside, what should a write do to the cached copy?

Continue learning