Cache consistency
medium 26 minCache consistency is about how closely cached copies follow the source of truth.
Video lesson · Chapter 1 of 5
A lock has to protect the right read and write
Cache consistency in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A cached value is a copy. The moment the original changes, the copy is wrong until somebody deletes or replaces it. Cache consistency is the set of rules that decides how long that may last and how it ends.
The database is the source of truth. A cache and a database are two systems, so a write cannot normally change both in the same instant. There is always a short window, and the design decides who may see it.
Why it exists
Stale data is not only ugly. A sold-out product that looks available, a price that changed, a permission that was revoked: each can cost money or trust.
Perfect freshness also has a price: waiting, locks and less availability. Most data does not need it. A good design uses the strict way for the few values that do, and lets the rest be a little late.
A short history
1983
Bus snooping appears as a way to keep processor caches coherent: each cache watches the writes of the others.
1984
Papamarcos and Patel publish the protocol now known as MESI, or the Illinois protocol.
2000 and 2002
Eric Brewer presents the CAP conjecture; Seth Gilbert and Nancy Lynch publish a formal proof two years later.
April 2013
"Scaling Memcache at Facebook" describes leases against stale sets, and markers for lagging replicas.
June 2022
Meta engineers report raising the measured consistency of their TAO cache from six nines to ten nines.
Words to know
- Source of truth
- The one place whose value counts, normally the database.
- Stale read
- A read that returns an older value than the source holds.
- Stale window
- The time during which a copy is out of date.
- Invalidation
- Deleting or expiring a copy so that the next read is fresh.
- Coherence
- Rules that make several caches agree about one value.
- Stale set
- A late reader stores an old value after the delete.
- Version
- A number that grows with every write, so that copies can be compared.
How it works
Step through the idea, or press Play.
Write the source. The database commits the new value
Understand it
Start here
Lunch on three boards
Imagine the lunch menu of a school. The kitchen decides. Three chalk boards around the building repeat it, so that nobody has to walk to the kitchen.
Wiping boards is easy. The late helper is what makes it hard.
Why
What stale data costs
Confusion
People see outdated information and make mistakes.
Business
Sold-out items look available. A price is wrong.
Trust
I changed my name and it is still the old one.
Integrity
A decision made from an old copy, in finance or health, can do real damage.
One shared cache
One write and its stale window
Strict
Strong consistency
Strong means: once a write is confirmed, every later read returns that value or a newer one. A reader can never see an older value again. The models are explained in consistency models.
The lock recipe
- 1
Acquire a lock
One writer at a time for this key.
- 2
Write the database
The source of truth first.
- 3
Delete or update the cache
Before the write is confirmed to the caller.
- 4
Release the lock
Other operations may continue.
Ways to read strictly
| Way | Price |
|---|---|
| Skip the cache and read the primary | Database load, the simplest way |
| Keep the copy, check its version at the source | One small query per read |
| Lock readers and writers of a key | Waiting, and trouble when the lock service fails |
| Give the cache a lease it must hold to answer | Writes wait for leases to end |
Advantages
- No stale reads after a confirmed write
- Simple reasoning in the application
- Predictable for users
- Right for decisions about money
Costs
- Higher latency
- Less availability during failures
- Contention under load
- More difficult to build
Relaxed
Eventual consistency
Eventual means: if no new writes come, all copies become the same in the end. Until then a reader may see an old value. The stale window is often milliseconds to seconds, but only a TTL or a check gives it a maximum.
How many stale reads?
Advantages
- Available when parts fail
- Fast
- No locks
- Scales out well
Costs
- Stale reads for a while
- Conflicts if several places accept writes
- The app must live with it
- Wrong for critical decisions
Good uses: social feeds, browsing a catalogue, dashboards, articles and images.
Sync
Delete or update the copy?
| Delete (invalidate) | Update | |
|---|---|---|
| Steps | Write database, delete key, next read fills | Write database, write the new value |
| After a write | One slow read | Warm |
| Danger | A late reader fills an old value | Two writers finish in the wrong order |
| Work | None for data nobody reads | Wasted if nobody reads |
Why not delete first?
Races
Two races to know
Race 1: stale set
Race 2: two updates cross
- 1
A writes 10 to the database
Then A pauses.
- 2
B writes 20 to the database
And stores 20 in the cache.
- 3
A continues
And stores 10 in the cache. The database says 20.
Answers
| Tool | How it helps |
|---|---|
| TTL | Ends every mistake after a known time |
| Version check | Store only if the version is newer, in one atomic step |
| Lease | A delete cancels the reader's permission to fill |
| Second delete after a pause | Catches most late fills; a guess, not a proof |
| Change log | One ordered stream of changes decides |
One gap is left: after a delete the cache forgets the version, so a late fill looks new. Keep a small marker with the latest version for a minute, or use a lease.
Failure
When the delete gets lost
The database commits, then the app crashes before the delete. "Update both or neither" is not possible with two plain calls. Three ways to close the gap:
- 1
TTL as a safety net
Simple, always.
- 2
Retry from a durable list
Write an invalidation row in the same transaction (an outbox) and work through it.
- 3
Follow the database log
A change stream deletes keys for every committed change, including manual fixes. See change data capture.
What lost deletes cost
Many caches
Coherence between caches
Every app server may keep its own copy in memory. Now one write must reach many caches. Processors solved this first, with two families of protocols.
Write-invalidate
One cache changes to v2 and all others drop their v1.
Write-update
One cache changes to v2 and sends v2 to all others.
A change log tells every copy
How to send the news
| Channel | Guarantee | Need |
|---|---|---|
| Redis Pub/Sub | At most once: a disconnected server misses it | A short TTL, and clear the cache on reconnect |
| A log such as Kafka | Kept, so a server can catch up | A reader per server |
| Redis client tracking | Redis remembers who read a key and notifies | Flush the local cache if the connection is lost |
| No channel | None | A very short TTL |
See distributed caching for shared caches over many machines.
Theory
Where CAP fits
CAP says: when the network splits, a distributed store cannot be both consistent and available. If the cache cannot reach the database, it must either refuse (consistent, CP) or answer from its copy (available, AP).
| Letter | Meaning |
|---|---|
| C, consistency | Every read sees the latest write or gets an error |
| A, availability | Every request to a working node gets an answer |
| P, partition tolerance | The system goes on although messages are lost |
Decide
Choose per kind of data
| Aspect | Strong | Eventual |
|---|---|---|
| Latency | Higher | Lower |
| Availability | Lower in failures | Higher |
| Stale reads | None after a confirmed write | Possible |
| Scaling | Limited by coordination | Easy |
| Hard part | Locks and failures | Handling old data |
| Use | Payments, stock at checkout | Social, content |
How fresh must it be?
A hybrid shop
- 1
Product page
Eventual: the stock shown may be a minute old.
- 2
Checkout
Strict: the order takes stock with one conditional update in the database.
- 3
Own profile
After an edit, send this user to the primary for a few seconds.
- 4
Recommendations
TTL only.
Operate
Measure it
- 1
Compare samples
Read a few keys from cache and source, and count differences older than your limit.
- 2
Measure the delay
From commit to delete, at the 99th percentile.
- 3
Count failed deletes
And the age of the oldest one in the retry list.
- 4
Have a way out
A version in the key prefix lets you drop a whole group at once. Watch for the thundering herd.
Summary
The whole topic in one minute.
A cache is a copy, so it can be late. Write the database first, then delete the key. Add a TTL for the delete that gets lost and a version or lease for the reader that comes late.
Strong consistency means reads never return an older value after a write is confirmed. With a cache this usually means reading the source, or checking with it. Use that for money and stock decisions, and eventual consistency for what people only look at.
- A cache is a copy, so plan for it being late.
- Write the database first, then delete the key.
- A TTL limits every mistake; versions and leases stop late writers.
- A lock on writers alone does not stop stale reads.
- Show from the cache, decide from the source.