Skip to content

Lesson 5 of 38Building blocks

Caching

Choose where to cache, pick a read and write pattern, handle eviction and invalidation, and avoid cache stampedes.

18 min read0/4 questions

When an interviewer says "the database is at 90% CPU and most traffic is reads", the first answer they hope to hear is add a cache. A cache keeps a copy of data in a faster place (usually memory) so you skip the slow work next time. Done well, it cuts latency from tens of milliseconds to one and takes 90% or more of the load off your database. Done badly, it serves wrong data to users.

Where caches live

Caches exist at every layer between the user and the disk. A request that is answered high up never touches the layers below.

Cache layers, from the user down
  1. Browser cacheCache-Control, ETag. 0 ms, per user
  2. CDN edgeStatic files, public pages. ~5 ms, shared by a city
  3. In-process cacheA dict or LRU inside the app. under 1 µs, per server
  4. Distributed cacheRedis or Memcached. ~1 ms, shared by all servers
  5. Database buffer poolPostgres shared_buffers. Hot pages in RAM
  6. DiskSSD. The source of truth

The DNS, CDNs, and Client Caching lesson covered these two: HTTP headers decide what browsers and CDNs keep.

1/4

Read and write patterns

The question that defines a caching strategy is: who puts data in the cache, and when does the database get written? There are four classic answers. Step through each.

Cache-aside (lazy loading) is the default. The app checks the cache, and on a miss loads from the database and fills the cache itself. Writes go to the database and delete the cached key.

Cache-aside
App serverApp serverRedisRedisDatabaseDatabaseGET / SETSELECT

GET user:42 from Redis. Miss: the key is not there.

1/4

Pros: only data that is actually read gets cached, and if Redis dies the app still works (just slower). Cons: the first read of every key is slow, and there is a window where cache and database can disagree.

Quick check
You count video views. There are 50,000 increments per second on popular videos, and losing a few seconds of counts in a crash is acceptable. Which write pattern fits?
Need a nudge? A hint rules out a wrong answer.

Eviction: what to throw out

Memory is limited, so a full cache must evict something to make room. The policy decides what.

  • LRU (least recently used): evict the key that has gone longest without being read. The default almost everywhere, because recently used data tends to be used again.
  • LFU (least frequently used): evict the key with the fewest reads. Better when a few keys are popular for a long time and a one-off scan should not flush them.
  • TTL (time to live): every key expires after a set time, whether or not the cache is full. This is less an eviction policy than a freshness guarantee, and you almost always set one.

Redis lets you choose with maxmemory-policy, e.g. allkeys-lru or allkeys-lfu. Run this tiny LRU with capacity 3 and watch the order.

Pythonlru.py
from collections import OrderedDict cache = OrderedDict()CAPACITY = 3 def get(key): if key in cache: cache.move_to_end(key) # mark as most recently used return f"hit {key}" cache[key] = f"value of {key}" # pretend we loaded it from the DB if len(cache) > CAPACITY: evicted, _ = cache.popitem(last=False) # oldest is at the front return f"miss {key} (evicted {evicted})" return f"miss {key}" for key in ["a", "b", "c", "a", "d", "b", "a"]: print(get(key), " cache:", list(cache))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
An LRU cache with capacity 2 sees: put x, put y, get x, put z. Which key is evicted?
Need a nudge? A hint rules out a wrong answer.

Hit rate math

The hit rate is the fraction of reads the cache answers. It controls both latency and how much load reaches the database.

Pythonhit_rate.py
CACHE_MS = 1 # Redis round tripDB_MS = 20 # database query def avg_latency(hit_rate): return hit_rate * CACHE_MS + (1 - hit_rate) * (CACHE_MS + DB_MS) for hit_rate in [0.0, 0.5, 0.9, 0.99]: db_qps = 10_000 * (1 - hit_rate) print(f"hit rate {hit_rate:>4.0%} avg {avg_latency(hit_rate):5.1f} ms DB load {db_qps:>6,.0f} QPS")
Output
Press Run (⌘ Enter) to see what happens.

Going from 90% to 99% looks small but cuts database load 10x (1,000 QPS to 100). That is why teams obsess over the last few percent.

Predict the outputPython

Hit rate 90%, a hit costs 1 ms, a miss costs 21 ms. Average latency?

print(round(0.9 * 1 + 0.1 * 21, 1))
Need a nudge? Hints walk you through it.

Invalidation, stampedes, and thundering herds

There is an old joke that the two hard problems in computer science are naming things and cache invalidation. When the data changes, the cached copy is wrong until something fixes it. Your options:

  • TTL only: accept data up to N seconds stale. Simple, and fine for most read-heavy content.
  • Delete on write: after updating the database, DEL user:42. The next read reloads it. Prefer deleting over updating the cached value, because two concurrent updates can write cache values in the wrong order.
  • Event-driven: the database change stream (CDC) publishes updates and a consumer invalidates keys. Used at large scale.

A cache stampede happens when a hot key expires and thousands of requests miss at the same instant, all run the same expensive query, and the database falls over. The broader version, many keys expiring together or a cold cache after a restart, is called a thundering herd. Fixes:

  1. Request coalescing (single flight): only one request rebuilds the key, usually by taking a short lock (SET lock:key 1 NX EX 5); the others wait briefly or serve the stale value.
  2. TTL jitter: add randomness (300 s ± 30 s) so keys written together do not expire together.
  3. Early refresh / stale-while-revalidate: refresh a hot key in the background shortly before it expires.
  4. Warm the cache before sending traffic to a new cluster.
Quick check
Every hour on the hour your database spikes to 100% CPU for a few seconds. All product pages were cached at deploy time with a TTL of exactly 3,600 seconds. What is the simplest fix?
Need a nudge? A hint rules out a wrong answer.

Redis vs Memcached

Redis (or Valkey)Memcached
Data typesStrings, hashes, lists, sets, sorted sets, streamsStrings only
PersistenceOptional (snapshots, append-only file)None
Replication and failoverYes (replicas, Sentinel, Redis Cluster)No, client-side sharding
ThreadsMostly single-threaded command executionMulti-threaded
Extra usesLeaderboards, rate limiters, queues, pub/sub, locksPure cache

Redis is the default choice today because one tool covers caching plus several other jobs you will meet in this unit. Memcached is still a fine, simple, very fast pure cache. (Valkey is the open-source fork of Redis that many cloud providers now run.)

ChallengeMedium

LRU cache

Build the cache that sits in front of a slow database. It holds at most capacity entries. When it is full and a new key arrives, it evicts the least recently used key: the one that has gone longest without a get or a put.

  • get(key) returns the value, or -1 if the key is missing. A successful get counts as a use.
  • put(key, value) inserts or updates the key and counts as a use. If that pushes the size past capacity, evict the least recently used key.

Both operations must be O(1).

cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
cache.get(1)      # 10   (1 is now the most recent)
cache.put(3, 30)  # evicts 2
cache.get(2)      # -1
class LRUCache: def __init__(self, capacity: int) -> None: # Hint: collections.OrderedDict remembers insertion order. pass def get(self, key: int) -> int: pass def put(self, key: int, value: int) -> None: pass
Key terms
cache-aside
The app reads the cache, loads from the DB on a miss, and fills the cache itself. Writes delete the key.
write-through vs write-back
Write-through writes cache and DB together; write-back writes the cache now and the DB later, risking loss.
LRU
Evict the least recently used key. The default eviction policy.
hit rate
The share of reads the cache answers. It sets latency and how much load reaches the database.
cache stampede
Many requests miss the same hot key at once and overload the DB. Fixed with locks, jitter, or early refresh.
invalidation
Removing or updating cached data when the source changes, by TTL, delete-on-write, or events.