The conference API has several replicas. Attendees refresh one popular session's schedule far more than any other, and each request recomputes the same details. A shared cache can absorb repeated reads. On the morning of the conference, the room changes, and somebody still sees the old room after an update. At the same time, newly added replicas can all try to refill the same key. A cache changes the behavior of reads, writes, and failures.

You will choose a cache pattern based on who owns the value, establish a freshness and overload policy, work through the race that can undo invalidation, and size the database path when cache reuse drops. Load Balancing and Horizontal Scaling provides the replica and failure-capacity model. Networking, HTTP, DNS, and CDNs covers HTTP-specific freshness and validation. Here the cached value is an application record or a computed projection.

Decide what the key and value mean#

An authoritative table stores the session's room and version. A cache may store that row directly or store a projection combining room, translated title, and accessible directions. Its key must include every input that defines the result. A possible key is schedule:v2:conference-17:stage-2:fr. The namespace makes incompatible representations coexist during deployment, the conference separates ownership, the session identifies the record, and the language selects a representation.

Use stable identifiers and deliberate key normalization. If the response depends on authorization, enforce access independently of the cache. Only share values among callers allowed to see the same result. The personalized ticket should use its authoritative path unless you can specify clear isolation, revocation, and freshness behavior. Include feature flags or a policy version when they change an otherwise shared result. Avoid putting secrets in key strings, logs, or eviction dashboards.

In-process caches are fast and isolated, but a cache on each app replica duplicates memory and load. Two replicas can return different versions. Scaling out creates more cold caches. A shared out-of-process cache can preserve reuse across app restarts and reduce duplicate fills. It adds a network hop and a shared dependency that can saturate. A local cache in front of a shared cache can absorb particularly hot reads, with a second invalidation and freshness policy to maintain.

Choose who loads reads and who acknowledges writes#

PatternRead or write pathWhere failures matter
Cache-asideApplication checks the cache and loads the source on a missEvery writer must follow the change policy; concurrent readers can refill stale data
Read-throughThe cache interface or wrapper invokes a loader on missesCaller is simpler; loader failure, deadlines, and coalescing are part of the cache interface
Write-throughA write passes through the caching layer and persists to the authoritative store synchronously before successCache visibility and partial failures still need explicit ordering and repair
Write-backA fronting layer accepts a write and persists it to the downstream store laterAcknowledged writes need a durable log or equivalent protection, bounded lag, ordering, and replay

Cache-aside is a practical starting point for the public schedule. On a cache hit, return the reusable projection. On a miss, load from the authoritative database, fill the cache, and return the result. Commit room changes in the database and send invalidations after commit. If a fill fails, the loaded value can still answer that request if it meets freshness requirements. Later misses may continue reaching the source until caching recovers.

With read-through, those lookup and loading steps live behind one interface. You can still choose application-controlled writes. Read and write choices are independent. Synchronous write-through can warm the cache as changes arrive, but define whether an authority commit with a failed cache update returns success. Retrying an ambiguous write must preserve identity. How you repair stale cache contents matters more than the label on the pattern.

Write-back shifts durable persistence out of the foreground path. If the fronting layer acknowledges data before the downstream write and can lose its only accepted copy, you've changed the service's durability contract. For ticket sales, the application needs durable acceptance and transactional enforcement before representing a reservation as committed. An asynchronous projection may still update after commit. Choose a durable ordered input, idempotent replay, backlog alerts, and conflict rules for such a projection.

Architecture canvasAn application serves a cache hit or loads the databaseThe API returns a usable cache entry. When none is available, it reads the authoritative source and can fill the cache for a later request.
An application serves a cache hit or loads the databaseThe API returns a usable cache entry. When none is available, it reads the authoritative source and can fill the cache for a later request.derive keyusable hitmissSchedule readCache lookupReturn cached copyRead and fill
Diagram key and text version
  • Entry
  • Process
  • Outcome
  • Data
  1. Schedule read → Cache lookup: derive key
  2. Cache lookup → Return cached copy: usable hit
  3. Cache lookup → Read and fill: miss

Expiration, eviction, and invalidation are different events#

Expiration is a time rule. A time to live (TTL) of 60 seconds lets the application stop serving an entry 60 seconds after it was filled, assuming clocks and cache semantics behave as specified. That does not prove the value is at most 60 seconds behind the database. A fill may read a lagging database replica or use an old snapshot from a long-running request. A delayed refill can start a new TTL for an already stale value. Measure source version and observation age when the product has a data freshness objective.

Eviction frees capacity. A least-recently-used policy favors recently read keys. A least-frequently-used policy favors keys with repeated accesses. A strict memory limit may also reject writes under the chosen policy. TTL gives a maximum eligibility period, while eviction can force a miss sooner. Check serialized size, key overhead, replication buffers, and fragmentation when budgeting memory. Redis documents sampled approximations to LRU and LFU. Do not assume it evicts in an exact global sort order.

Invalidation makes a particular representation ineligible because an input changed. You can delete the entry, update it with a new version, or rotate a generation used in the key. Every representation affected by the write needs coverage. A room update can affect multiple languages, the session listing, and related schedule views. Consider an index of dependent keys, a broader versioned namespace, or targeted events from the source transaction. Broad invalidation produces more misses. Versioned immutable keys can coexist until expiration, but the resolver for “latest version” then needs its own freshness policy.

In Redis, write the value and TTL in a single SET schedule:stage-2 <value> EX 60 operation when the cache entry should always expire. A plain successful SET normally clears an existing TTL, and writing then setting expiry in a separate call allows a process failure between those commands. An eviction policy is still needed for reconstructible entries when memory is finite.

Work through a stale refill#

Start with an empty cache and database version 7, which says the session is in Studio A. Time in this trace is measured in seconds.

TimeActionDatabaseCache
0Reader misses and starts loading a snapshotVersion 7Empty
1Editor commits version 8 and deletes the cache keyVersion 8Empty
2Reader's delayed version 7 arrives and fills for 60 secondsVersion 8Version 7, expires at 62
3Another reader hits the cacheVersion 8Studio A returned from version 7

The actual room is now Studio B. The updater correctly deleted the key after commit. The old result still arrived later and repopulated it. Invalidating before commit adds another window where readers can load the old version between deletion and commit. Ordering commit before invalidation addresses that window, but cannot prevent the delayed fill shown here.

Architecture canvasA delayed fill can restore an invalidated valueA reader starts a load of version 7. The writer commits version 8 and invalidates the key. The delayed version 7 arrives afterward and is rejected if the cache compares it with the invalidation version.
A delayed fill can restore an invalidated valueA reader starts a load of version 7. The writer commits version 8 and invalidates the key. The delayed version 7 arrives afterward and is rejected if the cache compares it with the invalidation version.load pendinginvalidatev7 below floorReader loads v7Commit v8Record floor v8Reject late v7
Diagram key and text version
  • Entry
  • Process
  • Outcome
  1. Reader loads v7 → Commit v8: load pending
  2. Commit v8 → Record floor v8: invalidate
  3. Record floor v8 → Reject late v7: v7 below floor

An atomic fill can compare the version it intends to write with the highest invalidated version for the key, even when the key is empty. In the trace the cache records a minimum accepted version of 8 and rejects the delayed version 7. Track the stored value's version too, so a delayed fill cannot overwrite a newer copy. Ignore duplicate invalidation events and advance the floor monotonically as new versions arrive. The comparison and write must be atomic in the same consistency domain. A check in application code followed by a separate cache write leaves another race.

Invalidation can arrive late or disappear after a process crash. Write a durable outbox record alongside the authority update if you need eventual delivery after restart, and measure propagation lag. A version floor only protects the cache once it is known there. Its retention must exceed the risk window for old loads and delayed readers, including restarts, eviction, and replica lag. If you cannot bound that interval, read from an authority that can confirm the current version or use a stronger protocol. The original Facebook memcache paper describes a different protection, key-specific lease tokens that a delete can invalidate. Both approaches make the right to fill conditional.

Choose which reads require current information

For a viewer, a schedule projection may tolerate a short staleness window. For the editor who just moved the room, the confirmation screen should reflect the editor's latest commit. Carry a trusted minimum version or commit token with the session. If the cache does not meet that minimum, read from an authority or a replica known to have caught up. Bypassing the cache while reading an arbitrary lagging database replica can still show the old room. If the required version is unavailable within the deadline, return a status or error that acknowledges the unmet freshness request.

A transaction reserving the last seat cannot depend on a cached count. Let the client's informational display read an approximate count if the product permits, and enforce the reservation in the durable write path. This is the same separation between a derived view and authority established in API and Data Model Design.

Size misses and protect the database#

Suppose 5,000 public schedule reads arrive per second. A 96% hit rate means 5000(1-0.96)=200 backend reads per second if every miss causes one backend read and there is no other load. At 90% hits the backend takes 500 reads per second. That is 2.5 times the original load for only a six-point drop in hit ratio. If the cache is entirely cold, demand can reach 5,000 reads per second. When the database safely handles 700, blindly sending all misses there can turn a cache outage into a wider outage.

Count backend attempts, including refreshes, fallbacks, and retries. Estimate average service time only for a fixed workload and latency distribution. If a hit takes 2 ms end to end and a miss takes 55 ms end to end, a 96% hit stream averages 0.96(2)+0.04(55)=4.12 ms. Under this simplified two-point distribution, p99 is 55 ms because 4% of requests take the miss path. Measure p99 separately and check both a cold start and a typical steady state.

The cache working set is the subset of data actively accessed in the relevant interval. A large catalogue can have a small frequently used subset, so serialize real objects and measure the distribution before sizing the cache. If average key and value footprint is 2 KiB for 100,000 active entries, the payload estimate is about 195 MiB before overhead, replicas, and client buffers. Include enough resource margin to handle misses during a rolling deployment or a memory-pressure event.

A stampede and a hot key need different controls

A cache stampede happens when many callers miss the same key or many keys simultaneously expire and trigger redundant backend work. For 100 concurrent misses on the same key, a per-key coalescer can run one load while the other 99 await its result, assuming one coordination scope. With four app replicas using independent coalescers, as many as four loads can still reach the database. Put hard deadlines on waiting and allow a controlled retry once a leader fails, so followers do not all start replacements. A distributed lease should be scoped to the correct key, expire, and protect the fill when the loader overruns its lease.

Add bounded jitter to expiry times across keys to spread synchronized refreshes. Keep the maximum TTL consistent with the freshness budget. Jitter across keys cannot spread the requests for one absent hot key. A soft expiry can trigger one refresh while other callers receive the prior value. A hard deadline determines when that value can no longer be returned. Choose stale eligibility per route and report the age of degraded responses.

A hot key can overload the cache even when almost every read is a hit. Sharding by key moves other keys away but leaves this key on one shard. A short-lived local copy, a replicated read path, or serving an immutable snapshot nearer the client can distribute its reads. Each copy creates another lifecycle to explain. If a key sees mostly unique requests, adding cache capacity may produce more eviction and little reuse.

Cache negative results only when the authority reliably establishes absence. Give them a short TTL and invalidate them when the object is created. Map a timeout to an error path rather than caching it as “not found.” Budget database queries for high-cardinality keys that bypass a meaningful cache hit path.

Plan how a cold or unhealthy cache behaves#

Draw the cold-read path from the previous lesson's ready replicas to the database. State the maximum number of outstanding backend reads, and preserve a portion of that budget for ticket-critical work. On cache timeouts, avoid repeatedly waiting for a slow cache before reaching the source. Bound cache and source deadlines and decide how much fallback the source can absorb. For the schedule, choose among serving an explicitly permitted older copy, limiting requests, or returning an unavailable response.

SymptomInspectExercise the failure
Editor sees the previous roomReturned version, minimum version, dependency versionsOverlap a write, an invalidation, and a delayed fill
Backend spikes around a common deadlineExpiry bins, fill counts, coalescer waitsExpire hot keys together
Cache CPU saturates while hit rate is highRequests per key and shard, value bytesReplay skewed traffic against the hottest key
Hit rate collapses after adding replicasLocal versus shared reuse, evictions, cold boot rateReplace several replicas under load
Deleted records appear againInvalidation lag, cached negatives or old reads, generation retentionDelay and reorder delete and fill events

In an interview, choose one read and one write, identify the authority, specify the key and maximum acceptable staleness, and trace hit, miss, invalidation, and source failure. Quantify normal and cold backend demand, then state admission and stale-answer policy. In production, add version-aware tests, cache bypass canaries, invalidation-lag alerts, and load tests of cold starts. The metrics should distinguish an expired entry, an evicted entry, an unavailable cache, and a logical miss when the available copy fails a minimum version check.

Run the Python lab#

Download the file and run python3 07-caching-strategies-invalidation.py with Python 3.10 or newer. The deterministic clock reproduces the race, rejects the old fill after version 8 is known, tolerates a delayed version 7 invalidation, and checks the exact TTL boundary. It also compares a simultaneous burst with and without coalescing by counting expected reads. The lab models a single cache's atomic operations sequentially. A distributed cache implementation needs a real atomic update, version-floor retention and delivery guarantees, and a mechanism for timing out or taking over a stalled loader.

Try it yourself

Measure the miss budget

At 4,000 reads per second, your database can safely sustain 300 read requests per second after other traffic. What hit rate is needed if each miss triggers one database read? What should you measure when adding background refresh?

Reveal solution

Require 4000(1-h) ≤ 300, where h is the fraction of requests that hit, so h ≥ 0.925, or 92.5%. Measure total database attempts, including background refresh and retries. The foreground hit ratio can remain high while background operations use the headroom.

Try it yourself

Explain a second stale refill

Your team records the highest invalidation version but expires it after 20 seconds. At second 0 the authority commits version 12. At second 25 a delayed source read returns version 11 and the cache is empty. What needs to change?

Reveal solution

The expired version floor leaves the comparison without evidence of version 12. Retain it beyond the known maximum lifetime of an old response, restrict the loader to a source that can confirm the minimum version, or use an invalidation-aware lease that cannot survive the conflicting write. Require the loader to retry or fail when a sufficiently current version cannot be obtained.

Why can TTL alone fail to bound lag behind the database?

When can a distributed lock still allow an old fill?

Memory chart#

Key            identity + representation inputs + permitted sharing
TTL            time-based reuse window
Eviction       capacity-driven removal
Invalidation   source change makes an old answer ineligible
Freshness      source version + propagation + cache policy
Miss budget    foreground misses + refresh + fallback + retry
Failure        empty cache, lost refresh, hot shard, and cold replicas

The next lesson uses queues and workers to decouple foreground work from asynchronous processing, and asks what happens when consumers cannot keep up.

References#