AlgoViz

Cache consistency

medium 26 min

Cache consistency is about how closely cached copies follow the source of truth.

See it run

One value, v1 becoming v2. Watch what the cache holds, what the database holds, and who reads in between.

Operations

Strong, with locks

Readers and the writer of this key use the same lock.

Step 1 of 6

In sync

readwriteWriterReaderCachev1Databasev1

Cache and database both hold v1.

Step 1: In sync

def write(key, value):    with lock(key):                # readers take it too        db.write(key, value)        cache.delete(key)    return "confirmed"def read(key):    with lock(key):        return cache.get(key) or fill(key)
Stale reads
None
Price
waiting
Writers only
a reader can slip in

The lock must cover readers too. Often it is simpler to read the database.

In the real world

The same cache consistency doing real jobs. Pick one and step through it.

Show from the cache, decide from the source.

Step 1 of 3

The page

readwriteWriterReader2 people lookCache1 seatDatabase1 seat

The cache says 1 seat. Two people see it, and that is fine.

Step 1: The page

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Delete before write

    critical

    A reader refills the old value before the write commits.

    Wrong
    cache.delete(key)db.write(key, value)
    Right
    db.write(key, value)cache.delete(key)
  • No TTL because we invalidate

    critical

    One lost delete and the value is wrong for ever.

    Wrong
    cache.set(key, value)
    Right
    cache.set(key, value, ttl=600)
  • Deciding from the cache

    critical

    Two orders see the same last item.

    Wrong
    if cache.get("stock") > 0: accept()
    Right
    n = db.execute("UPDATE stock SET n = n - 1                WHERE id = ? AND n > 0")if n == 1: accept()
  • A version counter in the cache

    major

    The late reader gets the highest number when it stores the oldest value.

    Wrong
    version = cache.incr("version")cache.set(key, (value, version))
    Right
    value, version = db.read(key)fill_if_newer(key, value, version)

Interview tips

  • How to explain it

    • A cache is a copy and can be late.
    • Database first, then delete.
    • TTL for lost deletes, versions for late readers.
  • Memory trick: STALE

    • Sync and Timing.
    • Atomicity and Locking.
    • Expiry as the safety net.
  • Choose per value

    • Money and stock decisions: the source.
    • Own edits: read your own writes.
    • Feeds and catalogues: eventual.
  • Be ready for

    • A delete that fails.
    • A replica that lags.
    • A local cache that missed a message.