AlgoViz

Cache consistency

medium 26 min

Cache 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

0:00 / 3:42

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

  1. 1983

    Bus snooping appears as a way to keep processor caches coherent: each cache watches the writes of the others.

  2. 1984

    Papamarcos and Patel publish the protocol now known as MESI, or the Illinois protocol.

  3. 2000 and 2002

    Eric Brewer presents the CAP conjecture; Seth Gilbert and Nancy Lynch publish a formal proof two years later.

  4. April 2013

    "Scaling Memcache at Facebook" describes leases against stale sets, and markers for lagging replicas.

  5. 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.

Step 1 of 3

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.

The boards and the kitchen
KITCHENPASTADoorPASTAHallPASTALibraryPASTAFour places, one lunch

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

Users reach two app servers. Both use the same shared cache, which holds one copy of each value, and the same database, which is the truth.
With a shared cache there is one copy to fix. That already removes many problems.

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. 1

    Acquire a lock

    One writer at a time for this key.

  2. 2

    Write the database

    The source of truth first.

  3. 3

    Delete or update the cache

    Before the write is confirmed to the caller.

  4. 4

    Release the lock

    Other operations may continue.

Ways to read strictly

WayPrice
Skip the cache and read the primaryDatabase load, the simplest way
Keep the copy, check its version at the sourceOne small query per read
Lock readers and writers of a keyWaiting, and trouble when the lock service fails
Give the cache a lease it must hold to answerWrites 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?

S≈λ⋅W500/s×0.2 s=100500/s×300 s=150,000S \approx \lambda \cdot W \qquad 500/s \times 0.2\,s = 100 \qquad 500/s \times 300\,s = 150{,}000
Reads of the key per second times the window. Deleting after 0.2 s gives 100 stale reads per update. Waiting for a 300-second TTL gives up to 150,000.

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
StepsWrite database, delete key, next read fillsWrite database, write the new value
After a writeOne slow readWarm
DangerA late reader fills an old valueTwo writers finish in the wrong order
WorkNone for data nobody readsWasted if nobody reads

Why not delete first?

The reader refills the old value before the write. Write the database first, then delete.

Races

Two races to know

Race 1: stale set

Race 2: two updates cross

  1. 1

    A writes 10 to the database

    Then A pauses.

  2. 2

    B writes 20 to the database

    And stores 20 in the cache.

  3. 3

    A continues

    And stores 10 in the cache. The database says 20.

Answers

ToolHow it helps
TTLEnds every mistake after a known time
Version checkStore only if the version is newer, in one atomic step
LeaseA delete cancels the reader's permission to fill
Second delete after a pauseCatches most late fills; a guess, not a proof
Change logOne 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. 1

    TTL as a safety net

    Simple, always.

  2. 2

    Retry from a durable list

    Write an invalidation row in the same transaction (an outbox) and work through it.

  3. 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

1,000,000 writes a day×110,000=100 wrong keys a day1{,}000{,}000 \text{ writes a day} \times \frac{1}{10{,}000} = 100 \text{ wrong keys a day}
Assumed: 1 in 10,000 deletes is lost. With a TTL of 10 minutes each key is wrong for 10 minutes at most. Without one, until somebody notices.

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

One writer sends a write to a write service, which commits to the database. The database change goes into a change log, which tells the local copies on three app servers to drop the key.
The log is written after the commit, so it never announces a change that did not happen.

How to send the news

ChannelGuaranteeNeed
Redis Pub/SubAt most once: a disconnected server misses itA short TTL, and clear the cache on reconnect
A log such as KafkaKept, so a server can catch upA reader per server
Redis client trackingRedis remembers who read a key and notifiesFlush the local cache if the connection is lost
No channelNoneA 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).

LetterMeaning
C, consistencyEvery read sees the latest write or gets an error
A, availabilityEvery request to a working node gets an answer
P, partition toleranceThe system goes on although messages are lost

Decide

Choose per kind of data

AspectStrongEventual
LatencyHigherLower
AvailabilityLower in failuresHigher
Stale readsNone after a confirmed writePossible
ScalingLimited by coordinationEasy
Hard partLocks and failuresHandling old data
UsePayments, stock at checkoutSocial, content

How fresh must it be?

A hybrid shop

  1. 1

    Product page

    Eventual: the stock shown may be a minute old.

  2. 2

    Checkout

    Strict: the order takes stock with one conditional update in the database.

  3. 3

    Own profile

    After an edit, send this user to the primary for a few seconds.

  4. 4

    Recommendations

    TTL only.

Operate

Measure it

  1. 1

    Compare samples

    Read a few keys from cache and source, and count differences older than your limit.

  2. 2

    Measure the delay

    From commit to delete, at the 99th percentile.

  3. 3

    Count failed deletes

    And the age of the oldest one in the retry list.

  4. 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.

Sources