Part 6 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.
A product page reads the same description thousands of times. Most requests ask for a value we just fetched from the database.
We could keep a copy nearby. A later request checks that copy first and avoids repeating the database read.
That sounds simple until the description changes, the copy fills up, or many requests discover it is missing at once. Let’s build the read path first, then follow those changes through the design.
On this page
- Choose freshness and write behavior
- Read-through is a different responsibility boundary
- Why recent use can predict future use
- Build the LRU data structure
- A cache tier can be replicated or sharded
Choose freshness and write behavior
Start with cache-aside
The application looks for the key in its cache. If the value is there and usable, it returns it—a hit. If it isn’t there, a miss causes the application to read storage, cache the result, and return it.
The application manages this process, so the pattern is called cache-aside.
The key must include everything that changes the response. Product ID alone is insufficient if two customers should receive different personalized values.
Decide what a write does
Now an administrator edits the description. The database has the new text, but our fast copy still contains the old one.
We need to choose how the write and cache interact:
| Strategy | Write path | Main concern |
|---|---|---|
| Cache-aside with invalidation | Update database, then remove cached copy | Failure or a racing reader can leave stale data |
| Write-through | Write through a layer that updates backing storage | Define when success is returned and how partial failure is handled |
| Write-behind | Accept into a buffering layer, persist later | Data can be lost unless pending writes are durably protected |
For cache-aside, updating storage and then removing the cached entry is common. The next reader reloads it. But those are two separate operations, and calling both successfully doesn’t make them one atomic action.
The subtle invalidation race
Even without an outright failed operation, this ordering can leave an old value behind:
- A reader misses and reads the old database value.
- A writer saves the new value and invalidates the cache.
- The reader fills the cache with the old value it already read.
The writer did invalidate the entry. The timing still allowed a stale refill.
Versioned entries, coordinated updates, and bounded expiration are possible tools. Choose them according to the freshness promise. A short expiration can limit some stale cases; it doesn’t make every read immediately current.
That distinction affects product behavior. A browsing page can sometimes tolerate a briefly old price. Checkout should revalidate the authoritative price before accepting the purchase.
Expiration and eviction are different
A cache can stop returning an entry for different reasons:
- Its TTL, or time to live, expires.
- Invalidation removes or replaces it because the value changed.
- Eviction removes it to make space.
Those decisions are related but separate. A recently accessed entry can be expired, and a still-valid entry can be evicted under memory pressure.
Choose a cache location
“Nearby” also needs a definition:
| Location | Benefit | Cost |
|---|---|---|
| Inside each application | Avoids a network lookup | Copies diverge and disappear on restart |
| Shared cache service | Instances reuse entries | Adds a network dependency |
| CDN edge | Serves reusable HTTP responses near users | Cache keys, privacy, and invalidation need care |
Local caches avoid a network hop but create independent copies on each instance. A shared cache lets instances reuse entries but adds a dependency. CDN caches place suitable HTTP responses near users.
Estimate the load reduction
With 10^4 reads per second and a 90% hit rate:
database reads ≈ total reads × miss fraction
= 10^4 × 10^-1
= 10^3 reads/second
The estimate excludes writes and refreshes. If the cache starts empty, nearly all 10^4 reads may reach storage instead.
Many requests can also miss the same key together and all attempt to load it. This is a cache stampede. Combining concurrent refreshes for one key can reduce duplicated work. Staggered expiration helps avoid many keys expiring together.
Read-through is a different responsibility boundary
Our application currently contains the miss-handling code. We could instead give a cache abstraction the responsibility for loading absent values.
The caller asks it for a key. The abstraction either returns a reusable copy or fetches the missing value. That is read-through:
| Pattern | Who fetches from storage on a miss? | What the caller does |
|---|---|---|
| Cache-aside | Application code | Check cache, fetch database, fill cache |
| Read-through | Cache service or loading abstraction | Ask the loading layer for the key |
Drawing a cache between an application and a database doesn’t implement the loading behavior. Some layer must know how to perform it. Microsoft’s cache-aside discussion explains this boundary.
Read and write policies are separate choices. A read-through loader might use synchronous write-through or durable write-behind. Specify when it acknowledges success and how partial failures behave instead of relying on the pattern names alone.
Why recent use can predict future use
Suppose the cache is full. We need to choose an entry to remove.
A customer has just opened an album and may refresh it or view another nearby image. Recently used entries can be useful again soon. This tendency is temporal locality.
LRU—least recently used—uses that tendency to choose a victim. It removes the entry not accessed for the longest time. Other policies make different guesses:
| Policy | What it removes | Limitation |
|---|---|---|
| FIFO: first in, first out | Oldest inserted entry | Ignores later reuse |
| LRU: least recently used | Entry unused for longest | A one-time scan can push useful entries out |
| LFU: least frequently used | Entry with low access frequency | Old popularity needs aging or it can dominate |
| Random | A randomly chosen entry | Simple but ignores access history |
A one-time scan can make LRU discard useful entries, and old popularity can mislead LFU without aging. The policy is a workload choice, not a universal ranking of algorithms.
Build the LRU data structure
We need to retrieve a key quickly and update its place in a recency order.
A plain list can hold the order, but locating a key takes a scan. A hash map can locate a key quickly, but we still need a way to change that key’s position without sorting everything.
Combine the two:
- A hash map points from key to list node.
- A doubly linked list keeps most recent near the front and least recent near the back.
- Nodes contain key, value, and neighbor links.
- Dummy head and tail nodes make boundary operations uniform.
Trace the operations
For capacity two, list the most recent entry first:
| Operation | Return | Recency order | Evicted |
|---|---|---|---|
put(A, 1) | — | A | — |
put(B, 2) | — | B, A | — |
get(A) | 1 | A, B | — |
put(C, 3) | — | C, A | B |
put(A, 9) | — | A, C | — |
get(B) | missing | A, C | — |
Reading A moves it to the front. Adding C then removes B, which has gone longer without an access. Updating A changes its value and recency without adding another entry.
With three entries, the same rule holds: after reading A, B, C, then A again, B is the least recent and would be evicted for a new D. The policy depends on use, not merely insertion time.
Implementation to study
Here is a single-threaded cache bounded by entry count. None means a miss, so this version doesn’t distinguish a miss from a stored None value:
class Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
if capacity < 0:
raise ValueError("capacity must be nonnegative")
self.capacity = capacity
self.nodes = {}
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _add_front(self, node):
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key):
node = self.nodes.get(key)
if node is None:
return None
self._remove(node)
self._add_front(node)
return node.value
def put(self, key, value):
if self.capacity == 0:
return
node = self.nodes.get(key)
if node is not None:
node.value = value
self._remove(node)
else:
node = Node(key, value)
self.nodes[key] = node
self._add_front(node)
if len(self.nodes) > self.capacity:
oldest = self.tail.prev
self._remove(oldest)
del self.nodes[oldest.key]
The map gives expected O(1) lookup work. Unlinking and adding a known node takes O(1) pointer changes. Memory is O(capacity).
Sorting timestamps on every access would do more work than needed. One access changes one entry’s position, so we can move that entry directly.
Check the implementation’s invariants
The two structures must keep agreeing. After each operation:
- Each cached key has exactly one map entry.
- Each map entry points to exactly one live list node.
- Map keys and list keys match.
- The first real node is most recent; the last is least recent.
- The real node count is within capacity.
These rules are invariants. They explain the failures behind common implementation bugs:
| Bug | Result |
|---|---|
| Remove a node from the list but keep it in the map | A later lookup can return an evicted value or manipulate stale pointers |
| Remove it from the map but leave it in the list | The next eviction can target an entry that is no longer accounted for |
| Insert a second node when updating an existing key | Duplicate list entries and incorrect size |
| Treat a miss as an access to a real node | The recency list can be corrupted |
| Forget capacity zero | A cache configured to retain nothing may still keep entries |
Sentinel nodes are bookkeeping, not cached entries. They let a one-element cache use the same unlinking steps as a larger one.
Why a cache hit is still a write to this data structure
get(A) returns a value and mutates recency. Two threads unlinking and relinking nodes concurrently can corrupt the list without coordination.
One lock around a complete get or put is a straightforward learning implementation. Production designs may partition locks, use local policies, or approximate eviction to avoid maintaining expensive global recency. They are changing the implementation trade-off, not the meaning of LRU.
Tiny exercises that expose boundary bugs
Try predicting the result before following the pointers:
- At capacity zero,
put(A, 1)must leave a later read of A missing. - At capacity one, inserting A then B must leave only B.
- Repeatedly updating A must not create duplicate A nodes.
- Missing B must not change existing entries’ recency.
- Reading A before adding C to a full A/B cache must make B the victim.
What production adds
The small implementation deliberately leaves several jobs outside its boundary:
- Byte limits, because equally many entries can occupy different amounts of RAM.
- Expiration, because recent entries may still be too old.
- Synchronization and failure handling.
- Metrics for misses, evictions, memory, and origin pressure.
Production products may also use approximate policies. Redis documents its approximate LRU behavior; don’t assume it runs the exact list we just wrote.
A cache tier can be replicated or sharded
A larger working set raises a different question from “which entry should leave?” It may no longer fit on one node at all.
- Sharding assigns different subsets of keys to different nodes.
- Replication keeps extra copies of a subset.
- Combining them can hold a larger working set and preserve copies after a node fails.
Replication still introduces lag and routing choices. A missing cache must not send unlimited work to storage. The capacity chapter sizes a working set and tests the cold-cache path.
A photo’s immutable dimensions and a last concert ticket shouldn’t share freshness rules just because both are represented as keys and values. We began with repeated reads; deciding which copies may be reused safely is what makes the cache a useful part of the application.
Previous: Route and Deliver Requests: Load Balancers, DNS, and CDNs. Next: Replication and Consistency: Leaders, Quorums, and CAP.