Course contents

06. Caching Lesson 2 of 8

Cache Aside

Put a cache in front of a database with the cache-aside pattern: see the hit ratio emerge, the TTL trade-off, and what happens when the cache fails.

14 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Cache aside: the application reads the cache, and on a miss reads the database and stores the result.
  • Skewed popularity lets a small cache absorb most reads; the misses still set the tail latency.
  • Cached data goes stale: delete keys on write and use a TTL as a backstop.
  • Shorter TTLs mean fresher data, more misses and more database load.
  • A cache that carries load is capacity: an empty or failed cache can overload the database.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Cache aside (also called lazy loading) is the most common way to use a cache such as Redis or Memcached in front of a database. The application owns the logic: it looks for a value in the cache; on a hit it uses it; on a miss it reads the database, returns the value and writes it into the cache so the next read is a hit. The cache itself knows nothing about the database.

Why it exists

Many workloads read far more than they write, and they read the same popular items again and again: product pages, user profiles, configuration. Serving each of those reads from the database costs a connection, CPU and disk work every time. An in-memory cache answers in well under a millisecond and is cheap to scale, so taking repeated reads off the database lowers latency and protects its capacity for the work only it can do.

How it works

Read path.

  1. Compute the cache key (e.g. product:42).
  2. GET it from the cache. If found, return it.
  3. Otherwise query the database, SET the key with a TTL, and return the value.

Write path. Write to the database, then delete the cache key so the next read reloads the fresh value. Deleting is safer than updating the cache: two concurrent writers updating both stores can leave them in different orders, while a delete just forces a reload.

Hit ratio. The fraction of reads served by the cache depends on how skewed the access pattern is, how much fits in the cache and how long entries live. With Zipf-like popularity, a cache holding 10% of the keys can serve well over half the reads, because the hottest keys stay resident and the least recently used ones are evicted (LRU).

Expiry. A TTL makes every entry expire after a fixed time, which bounds how stale it can get even if an invalidation is missed. Each expiry turns the next read into a miss, so the TTL is a direct trade between freshness and database load.

When to use it

  • Read-heavy data with popular items, where slightly stale values are acceptable for seconds or minutes.
  • When you want the cache to be optional: if it fails, the application can still read the database.
  • When only some data is worth caching: cache aside caches exactly what is read.

When not to

  • Write-heavy data, or data read once (logs, events): you pay for cache writes that are never read.
  • Data that must always be current (balances, stock reservations) unless you can invalidate reliably and tolerate the race windows.
  • When the database comfortably handles the load; a cache adds a component and a consistency problem.

Trade-offs

Choice You gain You pay
Short TTL Fresher data Lower hit ratio, more database load
Long TTL High hit ratio Staler data if an invalidation is missed
Invalidate on write Fresh reads after writes Code on every write path; race windows remain
Bigger cache More keys stay resident Memory cost; no help if the TTL is what limits hits
Caching computed results Saves expensive work Harder to know when to invalidate

Alternatives

  • Read-through: the cache loads missing values from the database itself; the application only talks to the cache.
  • Write-through: writes go through the cache to the database, keeping the cache warm and current, at the cost of slower writes and caching data that may never be read.
  • Write-behind: writes go to the cache and are flushed to the database later; fast, but risks losing writes.
  • Read replicas or a materialised view: scale reads without a separate consistency mechanism.
  • HTTP/CDN caching: cache whole responses closer to users.

Failure modes

  • Stale reads: a write that fails to invalidate, or a race where a slow reader puts an old value back after a writer deleted it, serves outdated data until the TTL expires.
  • Cache stampede (thundering herd): when a hot key expires, many concurrent requests miss at once and all query the database for the same value. Mitigate with request coalescing (one request rebuilds, others wait or get the old value), early probabilistic refresh, and TTL jitter so many keys do not expire together.
  • Cold cache: after a restart, deploy or failover the cache is empty and the database briefly sees nearly all reads. If it was sized only for misses, it saturates.
  • Cache outage: the fallback to the database is correct but sends the full read load there. Size the database for it, shed load, or limit concurrency to the database while the cache recovers.
  • Hot keys: one key read so often that a single cache node saturates; replicate it or keep a small local in-process cache.

In production

Treat the cache as part of capacity planning: know what the database must handle if the hit ratio drops. Set a TTL on every key, add random jitter, and delete keys on writes. Protect hot keys against stampedes. Monitor hit ratio, evictions, cache latency and database load together; a falling hit ratio is an early warning. Warm critical keys after deploys if a cold start is dangerous.

Common misconceptions

  • "A cache makes the database unnecessary for reads." Every miss, expiry and cache outage still reads the database.
  • "A bigger cache always raises the hit ratio." Not if entries expire before they are evicted; then the TTL is the limit.
  • "Updating the cache on write is the same as deleting the key." Updates can race and leave stale values; deletes force a fresh read.
  • "The fallback to the database makes cache failures harmless." Only if the database can carry the full load.

Interview angle

Expect to justify the cache with numbers (read/write ratio, hit ratio, database capacity) and to describe the read and write paths precisely. Interviewers then probe invalidation and staleness, TTL choice, stampede protection, what happens when the cache cluster fails or restarts, and hot keys. Saying "the database must survive a cold cache, or we shed load until it warms" shows you think of the cache as capacity, not decoration.

Model assumptions

The simulation is a simplified model, not a benchmark. Users read 10,000 products with Zipf(1) popularity; only reads are modelled. The Product API has 32 workers and holds one while it waits for the cache and the database. The database has 8 connections and a 30 ms mean read (lognormal, cv 0.4), about 260 reads per second; waiting more than 250 ms for a connection fails the query. The cache is an LRU of 1,000 keys answering in about 1 ms; it is filled after each database read. A failed cache is treated as a miss. A crashed cache restarts empty, as an in-memory cache usually does. The hit-ratio tile counts every lookup since the simulation started, including warm-up. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every read goes to the database

    Users read product pages at about 150 requests per second. The Product API does a little work and reads the product from the database every time.

    The database has 8 connections and needs about 30 ms per read, so it can serve roughly 260 reads per second. At 150 it is a bit over half busy.

    Scene: Users call the Product API, which reads every product from the database. The database is a bit over half busy and every request succeeds.

    Key idea: Without a cache, the database does the full read work for every request, including the thousandth read of the same row.

  2. 2. Read traffic outgrows the database

    Traffic doubles to 300 requests per second. The database cannot keep up: all 8 connections are busy and reads queue for them. The API’s workers sit waiting on those reads, its own queue fills, and new requests are rejected (503).

    Most of those reads are for the same few popular products. The database is doing identical work over and over.

    Scene: At 300 requests per second the database is saturated: reads wait for connections, the API fills up with waiting requests, latency climbs above 500 ms and some requests are rejected.

    Key idea: Read-heavy traffic with popular items is the classic case for a cache.

  3. 3. Check the cache first

    We add an in-memory cache and change the API: look in the cache first. On a hit, answer from the cache in about a millisecond. On a miss, read the database, return the value and put it into the cache for next time.

    The application manages the cache itself; the cache never talks to the database. That is the cache-aside pattern. The database now only sees misses, so the rejections stop and typical latency drops.

    Scene: The Product API asks the cache first and reads the database only on a miss, then stores the value in the cache. Most requests are hits; the database is far less busy and nothing fails.

    Key idea: Cache aside: read the cache; on a miss read the database and fill the cache yourself.

  4. 4. Why a small cache works

    The cache holds only 1,000 of the 10,000 products, yet about two thirds of reads are hits. Popularity is skewed: the few products everyone looks at stay in the cache, and the least recently used ones are evicted to make room.

    The misses still reach the database, and they are the slow requests. That is why P95 stays near the database time even though the median is now a few milliseconds.

    Scene: About two thirds of reads hit the cache. The remaining misses go to the database, which is lightly loaded; median latency is low while P95 reflects the database reads.

    Key idea: Hit ratio depends on how skewed the access pattern is, not only on cache size. Misses set your tail latency.

  5. 5. Stale data and expiry

    When a product’s price changes in the database, the cache still holds the old value. Cache aside does nothing about that on its own. Common fixes: delete the key when you write, and give every entry a time to live (TTL) so stale data cannot live forever.

    We set a TTL of 2 seconds (short, to make it visible). Expired entries count as misses, so the hit ratio drops and the database works harder. Shorter TTL means fresher data and more load.

    Scene: Cache entries now expire after 2 seconds. The hit ratio drops and more reads reach the database.

    Key idea: TTL bounds staleness at the cost of hit ratio. Invalidate on write when freshness matters.

  6. 6. The cache goes down

    One second in, the cache crashes. The API does the right thing for cache aside: it treats the failure as a miss and reads the database.

    But the database was sized for misses only. It suddenly gets all 300 reads per second, saturates and starts failing requests. The same thundering herd happens on a smaller scale when a hot key expires and many requests miss at once: a cache stampede.

    Scene: The cache goes offline. Every read falls through to the database, which saturates; the API fills up with requests waiting on it and some are rejected.

    Key idea: A cache that carries load is part of your capacity. When it empties, the database takes the full hit.

  7. 7. Running cache aside safely

    The cache is back. In production: invalidate on write (delete, don’t update, the key), use a TTL with a little random jitter so keys do not expire together, let only one request rebuild a missing hot key (request coalescing), and keep the database able to survive a cold cache.

    Watch the hit ratio and the database load together. A falling hit ratio is an early warning of database trouble.

    Scene: The cache is back online in front of the database with a 2 second TTL. Most reads are cache hits again and nothing fails.

    Key idea: Cache aside is simple and resilient to cache failure, but staleness, stampedes and cold starts are yours to handle.