Part 2 · Blueprint 06
Distributed Caching & Stampede Prevention
15 min reading · Sources · Editorial review pending
A copied answer can be fast while violating a freshness or authorization promise.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: SQL vs. NoSQL vs. NewSQL Storage Engines, Indexes & Storage Engines: B-Trees vs. LSM Trees.
Sixty-second mental model
Problem: A copied answer can be fast while violating a freshness or authorization promise.
Use: Bound miss traffic and give refresh work explicit ownership.
Design boundary: Use a distributed cache to avoid repeated origin work while retaining an explicit freshness policy. Cache-aside, write-through and invalidation have different failure windows. A cache entry must include the authorization and representation dimensions needed by its consumers.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing distributed caching. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one lookup means and which component owns the authoritative record.
Think of a nearby pantry stocked from a central kitchen. Separate the requester from authoritative record, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Cache
- Stored data reused to avoid repeating a more expensive retrieval or computation. Analogy: Keeping frequently needed ingredients near the counter.
- Cache hit
- A lookup served from the cache under the applicable validity rule. Analogy: Finding the needed ingredient on the nearby shelf.
- Cache miss
- A cache lookup that cannot supply the requested usable entry. Analogy: Having to visit the main storeroom.
- Cache-aside
- A pattern where application code loads missing data and populates the cache. Analogy: The cook checks the shelf, then fetches and restocks an absent item.
- Hot key
- A key receiving a disproportionate share of traffic or contention. Analogy: One popular shelf that every customer reaches for.
Architecture and worked reasoning
Design boundary: Use a distributed cache to avoid repeated origin work while retaining an explicit freshness policy. Cache-aside, write-through and invalidation have different failure windows. A cache entry must include the authorization and representation dimensions needed by its consumers.
Responsibilities on the request path
Workload and limiting resource
Hypothetical workload: 5,000 reads/s with 80% hits leaves 5,000 × 0.2 = 1,000 origin reads/s normally. A cold cache sends all 5,000 reads/s unless admission or request coalescing intervenes. Ten simultaneous loaders each taking 200 ms occupy ten origin slots for one key, whereas one coalesced loader occupies one.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Commit authoritative data before publishing an invalidation obligation.
- Invalidate or version affected cache entries.
- Bound concurrent loaders on a cold key.
Observation and recovery path
- Read a tenant-scoped key.
- On a miss, obtain one permitted origin result.
- Populate with a TTL/version rule and preserve the response freshness contract.
Failure that changes the decision
Hypothetical scenario: A delayed old loader overwrites a newer cached version after invalidation. Use version-aware publication or a suitable invalidation protocol; TTL alone only bounds some stale periods.
Attempt this decision before reading the explanation
Can stale data be served during an origin outage for every resource?
No. A public product description may permit bounded staleness, while current access revocation or stock allocation may require fresh authority. Declare freshness per operation and keep the protected decision out of an independently stale cache.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
In short. Cache repeated reads only under an explicit freshness and identity contract. Bound refill work independently of the warm hit rate.
A time-to-live limits a cache entry's permitted reuse according to a particular timer policy. It does not prove that the data was current when inserted or that the underlying state has not changed. An application cache also needs to decide when the timer starts and which events invalidate an entry.
RFC 9111 defines HTTP cache freshness, validation and restrictions on reusing responses. That contract is more precise than a general claim that every cached result is reusable until an arbitrary local timer expires. Application-level object caches need their own explicit rules rather than assuming HTTP directives solve every state problem.
Cache keys are equally important. If a result depends on language, source revision, account, permissions or other inputs, omitting a relevant distinction can produce a fast wrong answer. Including identity in a key is useful isolation, but it does not replace an actual authorization check for the requested data.
A cache-aside read first asks whether a usable entry is present. On a miss, the application reads the source and may publish a reusable representation. The write path must explain whether it invalidates, refreshes or versions that representation. A reader and writer can interleave, so describe those steps as concurrent operations rather than a decorative straight line.
Versions can help prevent an older refill from overwriting a newer entry, but the version comparison must itself be enforced by the chosen mechanism. Simply attaching a version number to text does not make concurrent writes safe. Nor does invalidating a shared cache automatically invalidate copies held by other layers.
Redis is the shared in-memory copy; Postgres remains authoritative for Northwind’s prices. In cache-aside , the application looks in Redis, reads Postgres on a miss, and fills Redis. Write-through makes the write path update the cache as part of its success contract. That adds write-path dependency and still requires a defined response if the database write succeeds while the cache update fails. Write-behind acknowledges a cache write before durable storage catches up. Its crash and replay requirements make it a poor default for an authoritative checkout price.
Eviction answers a different question from expiration: which entry leaves when memory is full? Redis offers approximate least-recently-used (LRU) and least-frequently-used (LFU) policies. LRU suits recent reuse but a scan can displace frequently useful older entries. LFU can preserve repeatedly popular items but may adapt more slowly when the hot set changes. Redis’s eviction documentation explains its sampling and frequency approximation; measure keyspace hits, misses and evictions under the actual access pattern.
A hot key concentrates work on one key even when the total key count looks small. Adding shards spreads different keys; it does not divide requests for one key automatically. A small local copy can reduce network reads when the display contract permits it. That adds another invalidation boundary. A cache stampede is the refill wave when many readers simultaneously discover a missing or expired key. A fast Redis lookup cannot prevent those readers from overloading Postgres afterward.
Hypothetical scenario. Choose a read rate of 1,000 requests/s and a hit fraction of 0.9. Warm hits are 1,000 × 0.9 = 900/s; misses are 1,000 − 900 = 100/s. Under one-source-read-per-miss accounting, the source sees 100 reads/s before considering writes, refreshes or retries.
Choose exactly 2 ms for a hit and 40 ms for the entire miss path. The weighted mean is 0.9 × 2 + 0.1 × 40 = 1.8 + 4 = 5.8 ms. These are chosen path times, not observations. This calculation establishes neither a percentile nor behavior under contention; a small slow fraction can matter greatly to users whose requests consistently miss.
For a refill example, assume a popular entry expires and exactly eighty requests arrive during a 0.4-second refill window. Their average rate over that window is 80 ÷ 0.4 = 200 requests/s. Without coordination, every request may issue a duplicate source read. If one in-flight refill is shared within each of six independent application processes, up to six concurrent refills can still occur. Process-local coordination is not automatically global coordination.
For a separate age example, choose a value already 45 seconds old when inserted into an application cache. If a local timer permits another 60 seconds of reuse without validation, the value can approach 45 + 60 = 105 seconds old before that timer expires, under the stated clock and age assumptions. This is why a local timer duration and source-data age are different quantities.
Do not turn these examples into universal settings. Refill cost, popularity, expiration patterns and permissible age depend on the application. Capacity planning should include misses, refresh work, cold starts and coordination failures rather than budgeting only the 900 warm hits.
Toy math: launch-day price miss. Choose 1,000 simultaneous readers and a 60-second TTL. If they all observe one expired key before any fill completes, the uncoordinated plan issues 1,000 identical Postgres reads. Coalescing across the whole service reduces this wave to one active refresh plus waiting readers; coalescing separately in six processes permits six refreshes. The distinction is coordination scope, not Redis lookup speed.
Size the working set from distinct items touched during the reuse window. Assume 100,000 catalogue items, and that the hot 20% of items account for 80% of reads. The candidate hot set contains 100,000 × 0.20 = 20,000 items. At a chosen 2,000 bytes per cached representation, payload is 20,000 × 2,000 = 40,000,000 bytes, or 40 decimal MB. This is 20% of item count, not 20% of read volume. A hypothetical 50% allowance adds 20 MB for a 60 MB planning subtotal; measure actual keys, object overhead, fragmentation and buffers before setting the process limit.
Refresh policies can use early refresh, distributed expiration, coalesced work or bounded concurrency. Each has costs. Coordination can fail, a lease can expire before work finishes, or one slow refresher can delay many readers. The application needs a timeout and fallback that respects its correctness requirement.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Cache-aside | Keeps the application in control of loading and validity. | Misses and concurrent refreshes need bounded coordination. |
| Write-through boundary | Can make cache and source update order explicit. | The actual durability acknowledgment and failure recovery must still be specified. |
Recovery decision
Hypothetical scenario: A delayed old loader overwrites a newer cached version after invalidation. Use version-aware publication or a suitable invalidation protocol; TTL alone only bounds some stale periods.
No. A public product description may permit bounded staleness, while current access revocation or stock allocation may require fresh authority. Declare freshness per operation and keep the protected decision out of an independently stale cache.
Write your design before revealing the review
Can stale data be served during an origin outage for every resource?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. A public product description may permit bounded staleness, while current access revocation or stock allocation may require fresh authority. Declare freshness per operation and keep the protected decision out of an independently stale cache.
A delayed old loader overwrites a newer cached version after invalidation. Use version-aware publication or a suitable invalidation protocol; TTL alone only bounds some stale periods.
Check your understanding
Can stale data be served during an origin outage for every resource?
No. A public product description may permit bounded staleness, while current access revocation or stock allocation may require fresh authority. Declare freshness per operation and keep the protected decision out of an independently stale cache.
How would you recover from this failure: A delayed old loader overwrites a newer cached version after invalidation. Use version-aware publication or a suitable invalidation protocol; TTL alone only bounds some stale periods.
Start with the exact boundary that failed. Commit authoritative data before publishing an invalidation obligation. Invalidate or version affected cache entries. Bound concurrent loaders on a cold key. Then recover evidence through the observation path: Read a tenant-scoped key. On a miss, obtain one permitted origin result. Populate with a TTL/version rule and preserve the response freshness contract. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical workload: 5,000 reads/s with 80% hits leaves 5,000 × 0.2 = 1,000 origin reads/s normally. A cold cache sends all 5,000 reads/s unless admission or request coalescing intervenes. Ten simultaneous loaders each taking 200 ms occupy ten origin slots for one key, whereas one coalesced loader occupies one. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Use a distributed cache to avoid repeated origin work while retaining an explicit freshness policy. Cache-aside, write-through and invalidation have different failure windows. A cache entry must include the authorization and representation dimensions needed by its consumers.
Which component in this topology could be removed from a smaller first deployment?
Reader, Cache lookup, Origin loader, Database name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Commit authoritative data before publishing an invalidation obligation.
What evidence must a caller have before relying on the observation path?
Read a tenant-scoped key. On a miss, obtain one permitted origin result. Populate with a TTL/version rule and preserve the response freshness contract. No. A public product description may permit bounded staleness, while current access revocation or stock allocation may require fresh authority. Declare freshness per operation and keep the protected decision out of an independently stale cache.
45-minute interview rubric
- 00–05: scope lookup and authoritative record.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw authoritative record, numbered writes and reads.
- 28–40: challenge recovery: Bound miss traffic and give refresh work explicit ownership.
- 40–45: defend cache_key placement, observations and remaining assumptions.
Go deeper
- https://redis.io/docs/latest/develop/reference/client-side-caching/ · Primary document · redis.io. Bound miss traffic and give refresh work explicit ownership. Verified 2026-10-26.
- Key eviction | Docs · Primary document · redis.io. Bound miss traffic and give refresh work explicit ownership. Verified 2026-10-26.
- RFC 9111: HTTP Caching · Primary document · www.rfc-editor.org. Bound miss traffic and give refresh work explicit ownership. Verified 2026-10-26.
Decision log
Bound miss traffic and give refresh work explicit ownership.
Preserve lookup identity and authoritative record ownership.
Revisit changed workload, observations or recovery objectives.