Caching
A cache stores a reusable answer closer to the caller or cheaper than the source.
What, why, when and how
What is it?
Caching stores a reusable copy of a computed result or source value close to its readers.
Why is it needed?
Repeated expensive reads consume database capacity and add latency even when the underlying result has not changed.
When should I use it?
Use a cache when requests reuse keys, the result has a defined freshness tolerance, and origin capacity or latency is a measured problem.
When should I choose something else?
Avoid relying on a stale cache to grant exclusive ownership or enforce a strict balance. Low reuse and constantly changing keys can make cache maintenance cost more than it saves.
How do I use it?
Choose the key and tenant scope, define TTL and invalidation, bound memory, coalesce concurrent fills, and plan how misses behave during a cache outage.
Can you show a concrete example?
With two slots and accesses A, B, A, C, FIFO evicts A while LRU evicts B. Separately, a delayed read of source version 7 can refill a cache after version 8 invalidation, so eviction policy does not solve freshness.
Read the diagram
Capacity 2; accesses: A, B, A, C; FIFO removes A; remaining keys: B, C; LRU removes B; remaining keys: A, C
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
A cache stores a reusable answer closer to the caller or cheaper than the source. Its central design question is how wrong that answer is allowed to be. Public article metadata may tolerate a minute of staleness; the final inventory decision may not. State the freshness contract before selecting TTLs, invalidation mechanisms, or a cache product.
Learning goals
Cache-aside; write-through; invalidation; TTL; staleness contracts; stampedes; jitter; request coalescing; negative caching; hot keys; outage protection.
Predict eviction before choosing a policy
Use a two-entry cache and request A, B, A, C, with every object the same size. FIFO remembers insertion order: the second A read does not change it, so inserting C evicts A and leaves B,C. LRU remembers use: the second A makes B least recently used, so inserting C leaves A,C. LFU counts use: A has two reads and B one, so a simple count-based policy evicts B; define tie-breaking and aging because long-ago popularity can otherwise dominate forever. Real products often approximate these policies to avoid expensive exact bookkeeping.
TTL answers a different question. If A expires after 30 seconds, it can disappear even when it remains the most popular object. Memory pressure can evict B before its TTL. A TTL constrains cache residence under the declared access semantics; it is not a guarantee that a copied value was fresh when inserted. Variable-size objects also invalidate a simplistic “two entries” capacity model: track bytes and oversized entries.
Choose placement by avoided work. A browser cache avoids a network trip but needs private-response rules; a CDN shares eligible responses near users; an in-process cache avoids a remote cache call but creates one copy and invalidation target per process; an external cache is shared but adds network and service dependencies. One endpoint can use several layers only with consistent scope and freshness rules.
Read-through moves miss loading into a cache abstraction; cache-aside leaves it in the application. Write-through requires a defined protocol linking durable writes and cached representations. Write-behind acknowledges before later persistence; if the only acknowledged copy is volatile, a cache loss loses that write. Calling both stores “updated” does not make their writes atomic.
R: source read -> version 7
W: source commit -> version 8; invalidate
R: late cache fill -> version 7
next read: stale, despite successful invalidationRead the diagram
Access trace, capacity 2: A,B,A,C; FIFO: evict A -> remaining B,C; LRU: evict B -> remaining A,C; LFU in this fixture: evict B -> A,C; TTL expiry and pressure eviction are different; Late source-v7 fill after v8 invalidation is stale
Protect this interleaving with a freshness contract: version-aware fills need retained knowledge of version 8; an ordinary delete erases that knowledge. Otherwise accept a bounded stale interval, coordinate the paths, or bypass the cache for correctness-sensitive decisions. Coalesce simultaneous misses, jitter expirations and cap origin concurrency. These protect load, while the authoritative reservation still protects inventory.
Show answer and explanation
Answer: At 20,000 reads/s and 95% hits, normal misses are 1,000/s. Complete cache loss exposes 20,000/s, a twentyfold increase. If the store is safe at 2,000/s, admit only a bounded fraction and degrade permitted reads; adding API workers alone increases the danger.
Step-by-step reasoning
1. Trace cache-aside explicitly
On a hit, return the cached value if its scope and freshness satisfy the request. On a miss, read the authoritative store and populate the cache with a bounded lifetime. Include tenant, authorization-sensitive scope, and representation version in the key when needed. Cache “not found” carefully and briefly so newly created data does not remain invisible for too long.
2. Handle concurrent fills
If 10,000 clients miss the same key at once, a cache can amplify load rather than reduce it. Coalesce fills for that key, use jittered expirations, and limit total origin concurrency. A lock used only to prevent a stampede is not a business correctness lock. It needs a safe timeout and failure behavior rather than indefinite waiting.
3. Explain invalidation races
Deleting a key after a write is not enough in every interleaving. Reader A can fetch old database state, writer B can commit and invalidate, then A can refill the cache with the old value. Versioned entries, coordinated invalidation, or a short bounded TTL can address different freshness contracts. Choose a mechanism proportional to the consequence of stale data.
4. Design the outage path
If the cache disappears, unrestricted fallback can overload the database. Apply admission control, cap concurrent misses, shed optional work, and serve explicitly permitted stale values where useful. A high hit rate is not sufficient evidence of health; a few expensive misses or one hot key may dominate origin load and tail latency.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
Illustrative load calculation
Read traffic = 20,000 requests/s
Hit ratio = 95%
Expected misses = 1,000 requests/s
If cache fails: potential origin load = 20,000 requests/s
Origin protection must be sized for its safe capacity.Worked example
A public article changes its title. A one-minute stale title is acceptable, so use cache-aside with jittered TTL and a best-effort invalidation event. A checkout availability display can also be cached, but the purchase operation must revalidate inventory at its owner. This separation makes the interface responsive without letting a cached “in stock” value authorize an oversell.
Failure walkthrough
During a synchronized TTL expiry, all web workers try to rebuild a popular homepage. Add one in-flight refresh per key and a global fill budget. If stale-while-revalidate is allowed, return the old page during a bounded refresh window. If freshness is mandatory, reject or wait within a deadline rather than silently serve stale data. Monitor miss concurrency, eviction rate, fill latency, and stale age.
Read the diagram
Reader fetches old version → Writer commits new version → Writer invalidates cache → Old reader attempts refill → Version check or TTL bounds stale data
Decisions and trade-offs
| Strategy | Benefit | Risk |
|---|---|---|
| Cache-aside | Simple and demand-driven | Miss latency and stale fills |
| Write-through | Cache updated on write path | Write latency and dual-system failures |
| Short TTL | Bounds ordinary stale lifetime | More misses; not an atomicity guarantee |
Check your understanding
A key expires during a database slowdown. Which matters more: adding cache clients or bounding cache-miss work?
Show answer and explanation
Answer: Bound miss work and coalesce refreshes. More clients do not increase database capacity. A protected origin can recover; an unlimited retry and refill wave can keep it saturated.
Transfer to a new scenario
Cache public article metadata while keeping the final inventory decision authoritative.
A cache miss wave reaches an already saturated database. Which protection actually bounds load?
Continue the connection
Study Scaling Reads and explain which guarantee from this lesson carries into that topic.
Define freshness before choosing a policy
For each value, state who owns the truth, how stale the value may be, and whether stale data can cause harm. A product description may tolerate a minute of delay. A seat reservation must still perform its conflict check at the authoritative store. Caching a displayed availability count does not make that count safe for purchase decisions.
Use a key that includes every dimension affecting the response: tenant, entity, relevant query parameters and possibly schema version. Caching an authenticated response under only a URL can leak one user’s data to another. Large values and high-cardinality query combinations can exhaust memory even with a good hit rate.
Compare read and write policies
| Policy | Flow | Principal risk |
|---|---|---|
| Cache-aside | Application reads cache, then store on a miss | Stale refill races and stampedes |
| Read-through | Cache loader fetches a miss | Loader becomes a critical dependency |
| Write-through | Write path updates durable state and cache under a defined protocol | Dual-write failure still needs handling |
| Write-behind | Cache acknowledges before durable persistence | Lost acknowledged data if the buffer fails |
| Invalidate after write | Commit source, then delete cached value | Invalidation can be delayed or lost |
A policy name is not a consistency proof. “Write-through” across two independent systems still needs an order, retry behavior and recovery story. If acknowledged data must survive a cache loss, an ordinary volatile cache cannot be the only committed copy.
Walk through the stale-refill race
Reader R misses the cache and reads database version 7. Before R fills the cache, writer W commits version 8 and invalidates the key. R then inserts version 7. The invalidation succeeded, yet stale data returned. A short TTL limits the stale interval but does not prevent the race.
Read the diagram
Miss; Read old version 7; Commit new version 8; Invalidate cache entry; Late refill stores version 7; Next read can see stale value
Possible remedies include version-aware cache writes with a retained invalidation version, a coherent loader/write protocol, or bypassing the cache for operations requiring current state. A delayed second delete reduces some races but is not a universal proof under arbitrary delays. State which residual staleness your choice permits.
Prevent a cache outage becoming a database outage
With 100,000 reads/s and a 99% hit rate, the database normally sees around 1,000 reads/s. Losing the cache can multiply that load by 100. Adding application replicas makes the failure worse if every instance immediately falls back to the database.
Coalesce concurrent misses for the same key, cap origin concurrency, apply per-tenant admission and use stale-while-revalidate only where the freshness contract permits it. Add TTL jitter so a bulk-loaded set does not expire simultaneously. Negative caching can protect nonexistent keys, but its TTL must not hide newly created records for too long.
Separate eviction from expiry
Expiry implements a lifetime rule. Eviction makes room under memory pressure, potentially before a TTL expires. LRU favors recency; LFU favors repeated use; approximate policies reduce bookkeeping cost. Measure bytes as well as entry count. A few huge values can evict many useful small ones.
A hot key may need replication or local caching; adding hash partitions will not distribute one key’s requests. Local caches reduce network traffic but multiply invalidation targets. Track hit rate by traffic class and value size, origin requests, fill latency, evictions, stale responses and refresh failures.
Exercise: choose a safe fallback
A recommendation cache is unavailable while an inventory cache is stale. Both normally reduce database load. Should the services use the same fallback?
Show answer and explanation
Answer: No. Recommendations may use a bounded stale result or a simpler fallback. Inventory purchase must still validate authoritative availability and may reject or queue under overload. Apply separate budgets so a recommendation cache outage cannot consume every database connection needed for checkout.