Skip to content

Cache data while preserving a freshness contract

15 min reading

Choose placement, expiry, invalidation and stampede handling

Page details

System Design · Operate the system

15 min reading · 28 min with practice

Sources

Published · Last edited:

Prerequisite: Checkpoint: reconcile an uncertain operation. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. Dev proposes keeping Northwind prices in Redis for sixty seconds. Priya brings back the edge example: a response may already contain old evidence when the new cache timer starts. Maya asks which clock the visitor’s freshness promise actually uses.

Dev: “The local entry has not expired.”

Priya: “How old is the price evidence by the time the visitor receives it?”

Define eligible reuse and a bounded refill path. Preserve source age across cache layers rather than resetting it at each copy. The selected stress cases introduce their own load; they do not replace the original catalogue’s busy interval.

Which clock measures the age of this answer?

The earlier edge path used forty-five seconds of source age, twenty seconds of reuse and one second of delivery, producing sixty-six seconds. It exceeded the permitted sixty-second price-evidence age. Renaming the new layer Redis does not change that sum. Define what the evidence timestamp means and where it is checked before accepting a representation.

A display response may be allowed to disclose a stale description or return unavailable when current evidence is missing. The final reservation or checkout decision must follow its own authority contract. A warm hit is useful only when the representation remains eligible for this operation and caller.

A timer is not a source of truth

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.

Make a delayed fill lose to a newer version

Hypothetical scenario. A cache miss begins reading Q7 revision 11. Meanwhile the source commits revision 12 and a newer fill stores it. The delayed revision-11 reply arrives last. A blind cache set would regress the entry despite successful invalidation earlier in the timeline.

Make a delayed fill lose to a newer version — selected design evidence
Entry fieldExampleEnforced rule
Variant identityQ7 / UK / GBPNo cross-variant reuse
Source revision12Reject older replacement
Evidence timesource observationPreserve age at delivery
An invalidation is not enough when an earlier read can repopulate obsolete data afterward.An invalidation is not enough when an earlier read can repopulate obsolete data afterward. New fill rev12 to Cache: 1 · install revision 12; Old fill rev11 to Cache: 2 · delayed 11 must not replace 12.Old fill rev11CacheNew fill rev121 · install revision 122 · delayed 11 must not replace 12
An invalidation is not enough when an earlier read can repopulate obsolete data afterward. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

A version-aware fill rule can reject the older write when the cache or its publication authority supports that conditional transition. Alternatively use immutable versioned keys and a separately protected current pointer. Deleting a key on change without protecting later fills leaves the race open. A single-flight mechanism collapses compatible concurrent misses but does not itself prove source freshness or prevent an old in-flight fill.

The freshness deadline concerns source evidence at delivery. Capacity planning must also include the cold or evicted state: hit-rate savings can vanish while fill traffic, retries and background refresh compete. Admit refresh work with a separate bound so a cache recovery cannot exhaust the source needed for current requests.

Read through the validity boundary

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.

Reuse only after identity and validity checksA read checks a scoped cache key and validity. A usable hit returns a representation. A miss enters bounded refill work against the authoritative source. Updates invalidate or version derived entries under a stated policy.ReadKey + validityand permissionUsable hit → responseMiss → bounded refillfrom source

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.

Calculate the warm path and the refill wave

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 40 × 0.5 = 20 MB, giving 40 + 20 = 60 MB as a planning subtotal; measure actual keys, object overhead, fragmentation and buffers before setting the process limit.

In the wild: Facebook’s leases make refills a protocol

Nishtala and colleagues’ Scaling Memcache at Facebook describes leases for coordinating fills and dealing with stale-set races. The paper’s value here is the identified concurrency problem and its protocol, not a promise that Northwind should copy Facebook’s scale. A reader that misses needs controlled permission to refill; invalidation can make previously granted work obsolete.

For Northwind, trace a price update against a paused refill. Decide who may publish after the update, and how a delayed worker learns that its earlier result is no longer eligible. Treat this as a state transition that the implementation must enforce. A timer attached to an old result cannot establish that ordering by itself.

Stale data and stale work need different policies

Some pages may tolerate a previously valid description while a refresh occurs. Other operations, such as accepting a reservation against current stock, require a stronger decision. Define permitted staleness by operation and consequence; do not let a performance optimization silently choose business semantics.

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.

Negative caching also needs a contract. Reusing “not found” can reduce repeated failed lookups, but an item may be created or permissions may change. Choose identity, lifetime and invalidation for negative results rather than assuming an absence is permanent. Do not use a shared negative result to conceal an authorization boundary.

An edge cache or CDN adds a reuse boundary closer to readers. Decide which representations are shareable, how request variants affect the key and how source changes reach that layer. A private response must not become public merely because it crosses an intermediary. An origin-side invalidation does not establish that every edge copy has changed; evaluate HTTP cache directives and application permissions together.

A paused refill overwrites the updated price

Hypothetical failure scenario. Reader R fetches price revision 7 and pauses. Writer W commits revision 8 and invalidates Redis. R resumes and fills revision 7 under a fresh timer. Invalidation occurred, yet a later reader still receives the old value. The fill boundary needs an enforced version or validity rule that makes obsolete work ineligible.

A lease granted before the pause is insufficient if the resource accepts writes after that authority expires. Connect this race to the earlier scheduling-generation lesson. The goal is controlled publication of reusable state, not merely a lock record that once existed.

Cache promises that need evidence

“More RAM guarantees more hits.” Allocation does not establish the popularity distribution or that useful entries are present.

“A high average hit rate protects every tenant.” Aggregation can hide a hot key, a cold tenant or an expensive class of misses.

“An invalidation message proves nobody can read the old value.” Concurrent fills and additional cache layers require their own ordering and visibility rules.

“A cache outage should simply bypass to the source.” That fallback can exceed source capacity. Admission and correctness requirements still apply.

Reuse only what the operation allows

Use caching where repeated work is material and a scoped validity policy can be implemented. Measure saved resource work, not only the existence of hits. Separate response-cache behavior from authoritative state and distinguish user-visible freshness from a particular storage timer.

Do not cache a result whose relevant identity or authorization dependencies are unknown. Avoid adding a cache merely because a reference architecture contains one. The resulting invalidation and recovery complexity must be justified by a concrete workload.

The next lesson controls which requests enter shared capacity. A cache miss is still admitted source work; a cache outage cannot justify bypassing that control.

Limits of this estimate

The examples count declared payload and source operations; they omit measured queueing, Redis object overhead and failure timing. Early refresh does not establish one global winner, a lease needs enforced publication rules, and serving stale data remains an operation-specific business decision. Validate checkout against authoritative prices and bound the cold-cache path before relying on warm-path capacity.

Challenge the proposed mechanism

A cache does not support conditional version updates. Can the application claim this fill rule anyway?

Reveal the design reasoning

No. Select an implementable pointer/version protocol, serialize fills at a defined authority, or weaken the cache contract and check current evidence before disclosure. Document the added failure and capacity responsibilities.

Decision and reconsideration: Protect fills as well as invalidations. Test cold-source demand and delayed-reply races before depending on cache savings.

Follow the cached value

  1. An entry's local timer is fresh, but the result belongs to a different account. May it be reused?

    Check identity, age and authority

    No. Timer state does not override identity or authorization. The request must satisfy the correct scope and access contract.

  2. Six processes each coalesce local requests. Does that prove exactly one source refill?

    Check identity, age and authority

    No. Each process can still start its own work. Cross-process coordination, if needed, introduces a separate contract and failure behavior.

  3. A source update invalidates an entry before an old read publishes its result. What must the design prevent?

    Check identity, age and authority

    It must prevent the older refill from becoming a valid newer representation under the chosen policy. Trace revisions and atomic ordering; repeating invalidation blindly does not establish that invariant.

A cache can reduce ordinary work while creating a refill surge when entries become unavailable. Page 33 turns that demand into an admission decision and asks which work the service should accept before capacity is exhausted.

Northwind decision log

Coalesce refreshes for a hot key before querying Postgres.

Allow stale prices only under an explicit display contract.

Validate the final checkout price against the source.

Go deeper: cache semantics and refill protocols