Cache-Aside & Cache Consistency
Cache-Aside loads a cache only when an application misses, so repeated reads can skip the database. The application usually writes the database before deleting the cached copy. These are separate operations: an older read can refill stale data after a successful deletion, leaving even a later cache hit out of date.
The troublesome copy may be outside both stores. A reader has already fetched v1 and paused before caching it. Updating the database to v2 does not reach into that reader's memory. Nor does deleting a cache key. Follow that third copy, and the race becomes much easier to see.
How Cache-Aside Works
The database owns the record. The cache holds a replaceable copy, and the application manages the relationship between them.
| Path | Application actions | Database reads |
|---|---|---|
| Cache hit | GET the key; return the cached value | None |
| Cache miss | GET; read the database; SET that result; return it | One in this model |
| Write | Commit the database change; DEL the cached key | No read required |
Deletion makes a later request reload on demand. The cache does not fetch the new record by itself. A successful GET establishes that an unexpired entry exists; it does not establish that its version matches the database.
Why update the database first? If you delete first, another reader can miss, fetch the still-old database value, and cache it before your update commits. Writing first closes that particular window. It cannot remove an old snapshot that another reader already holds.
Cache-Aside Step by Step
The default uses item:7, initial value 10 / v1, updated value 20 / v2, and TTL of six
logical ticks. It writes the database first and delays one reader's cache fill.
- Warm the cache. R0 checks an empty cache, reads
10 / v1from the database, fills the cache at t=0, and returns it. H0 reads at t=1 and hits that entry. There has still been only one database read. - Start a new experiment. Restore DB v1 and an empty cache; reset time and counters. This is a separate run, not a database rollback within the warm-up.
- Let R1 read. R1 misses at t=0, reads DB v1 at t=1, and pauses with
10 / v1in hand. It has not yet filled the cache. - Commit the write. At t=2, W changes the database to
20 / v2. R1's copy stays v1. - Delete successfully. At t=3, W deletes the cache key. The key was absent, so this succeeds without removing a value. W completes. R1 still holds its earlier snapshot.
- Resume the old fill. At t=4, R1 sends SET with
10 / v1and returns that value. The cache accepts it. Its expiry is t=4 + 6 = 10, measured from this fill. - Read after the write. R2 starts at t=5, after W completed. It hits v1 while the database contains v2. R2 does not query the database, and its HIT does not extend TTL.
- Expire, then reload. Advance to t=10 with no further writes or fills. Expiry makes
the old entry unavailable. R3 then misses, reads
20 / v2, fills the cache, and returns it. That new entry expires at t=16. R2's already-returned response remains v1.
Watch R1's held-copy card during W's operations. It is the same v1 that later travels into the cache. The bottom receipt compares R2's returned version with the database version at that return; the clock separately marks the cached entry's lifetime.
What Consistency Does Cache-Aside Provide?
The default is a concrete counterexample to immediate freshness after a successful write. R2 begins after W has completed both operations and still receives v1. R1's old response is a different case: R1 overlaps W, so its return alone would not prove the same violation.
Change one condition at a time:
| Experiment | Result |
|---|---|
| One request at a time | R1 fills before W. W's later deletion removes that fill; R2 fetches v2. |
| Read between writes, DB first | R1 can hit v1 while W is incomplete. W then deletes it, so R2 gets v2. |
| Read between writes, cache first | R1 misses and fills v1 before the DB commit. R2 later hits that stale fill. |
| Late fill, either write order | R1 fills v1 after both writer operations. Both orders allow the shown stale hit. |
| DEL fails after DB commit | DB v2 survives; cache v1 survives too. W reports failure, and cleanup is still needed. |
| DEL fails before DB update | This model stops W at the failure. DB stays v1; it never committed v2. |
TTL limits the lifetime of one cache entry. It does not make two writes atomic. A delayed stale fill gets its own later deadline, so “staleness lasts at most one TTL after the database write” is not a general guarantee. With no more writes or stale fills, a finite TTL and a successful subsequent DB read let this example recover. With expiration off, there is no scheduled repair in the model.
The hit path saves a database read, but this lesson makes no latency or throughput claim. An application that must never serve an old value needs a stronger protocol or a read path that meets that requirement. Fixed delayed double deletion and ordinary process-local locks do not prove that every in-flight fill has been fenced.
Edge Cases
- Absent key: DEL succeeds without storing a tombstone or cancelling R1's snapshot.
- Failed invalidation: a committed DB update remains committed. The write attempt reports the cleanup failure instead of pretending both stores changed together.
- TTL disabled: the late stale fill remains at the end; no automatic refresh is invented.
- Deadline reached: an entry cannot supply a HIT at
now >= expiresAt. Expiration itself performs no database read. - Zero as a value:
0is valid data. The demonstration accepts distinct integers from 0 to 999; absence is represented separately. The TTL range 6–12 is a presentation bound.
Common Mistakes
- Treating HIT as a freshness check. GET normally knows only the cache entry.
- Deleting before committing, then letting a reader refill the old database value between the two operations.
- Assuming a successful deletion cancels work already held by application requests.
- Starting the claimed TTL bound at the DB commit instead of the actual cache fill.
- Reporting the write as fully successful after the DB committed but DEL failed, without tracking the incomplete cleanup.
A Note on Simplification
This is one key, one writer, one shared cache, and one primary database. Each store operation is atomic locally; there is no cross-store transaction. Successful receipts include their acknowledgements. The failure preset means DEL did not execute, rather than an ambiguous timeout after possible execution. Logical ticks describe ordering and expiry, not RPC latency or playback seconds. Version labels expose provenance; they do not enforce CAS.
The model omits replication, eviction, cache stampedes, negative caching, multiple writers, partitions, retries, CDC, leases, and conditional fills. In particular, a lease that rejects obsolete fills would change the default race. The animation deliberately uses ordinary unconditional SET. Physical background cleanup can occur later than logical expiration; the relevant property here is that an expired entry cannot answer GET.
The read/write ordering follows Microsoft's Cache-Aside pattern. Scaling Memcache at Facebook describes stale sets and lease-based protection. Redis EXPIRE documents expiration behavior. The particular schedules and tick values above are constructed teaching examples.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Premium players need paid access. Every Explain doc is free.
Found a mistake or something unclear? Leave feedback.