Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Core concepts · Lesson 4 of 44

Cache consistency, stampedes and hot keys

How a cache fails at scale: the invalidation race, checked over every interleaving, and what deletes, leases and versions fix; stampedes when a popular key expires; and hot keys that placement cannot spread.

ConceptCore25 min readUpdated

  • 1 sequence flow
  • 5 code samples
  • 8 interviewer follow-ups
  • 4 self-checks

Read first: Caching

By the end you will be able to
  • Explain how a stale value gets into a cache-aside cache, and how deletes, leases, versions and a time to live close or bound the race.
  • Stop an expiring popular key from becoming a stampede, and compare coalescing, leases, serving stale and early refresh by measured database load.
  • Explain why a hot key cannot be fixed by placement, and fix it with a near cache or replicated copies.
  • Check a cache protocol by enumerating interleavings instead of arguing about which orders are possible.

5 code samples (239 lines), collapsed so the explanation stays in focus.

The caching lesson covers where to cache, the four read and write patterns and eviction. It ends with a list of failure modes: stale data, stampedes and hot keys. This lesson takes those three apart. Each is a place where a cache that passes every test fails in production, because the failure needs scale: millions of requests make a one-in-a-million interleaving certain, a popular key makes a rare expiry a daily event, and a skewed workload makes one key bigger than one machine. Each has a small simulation below that shows the failure and what fixes it, so an answer in an interview is a mechanism and not a slogan.

LLD

The stale set: how cache-aside loses a race

The database is the source of truth and the cache holds copies, so every write has to deal with the copies. The standard protocol is cache-aside: to read, get, and on a miss read the database and set; to write, update the database, then delete the key. Deleting beats updating the cached value because a delete is idempotent and does not depend on the order in which two writers finish. Even so, one ordering of three requests leaves a stale value behind.

Fig. The stale set: how an invalidation loses a race
Fig. The stale set: how an invalidation loses a race

The reader has to stall between reading the row and filling the cache: a garbage-collection pause, a slow network, a descheduled thread. That is rare for one request and certain across billions. Rather than argue about which orderings are possible, enumerate them. The checker below runs every interleaving of the steps of a reader and one or two writers (each actor's own steps stay in order) and counts the orders that end with a cached value different from the database, which would stay wrong until its time to live.

C# · Everything the interleavings can change: the database, the cache, the lease the cache…56 lines
using System;
using System.Collections.Generic;

// Everything the interleavings can change: the database, the cache, the lease the cache will accept a fill for,
// and where each actor is in its script.
public sealed class World
{
    public int Db = 1;                    // the database holds one value; writers change it
    public int? Cache = null;             // null means the key is not cached
    public int Lease = 0;                 // the lease token a fill must present (0: none outstanding)
    public int NextToken = 1;
    public int[] Next, Held, Token;       // per actor: its next step, the value it read, and its lease token

    public World(int actors) { Next = new int[actors]; Held = new int[actors]; Token = new int[actors]; }

    public World Copy()
    {
        var w = (World)MemberwiseClone();
        w.Next = (int[])Next.Clone(); w.Held = (int[])Held.Clone(); w.Token = (int[])Token.Clone();
        return w;
    }
}

// One step of one actor. Returning false ends that actor's script early (a read that hit the cache has nothing left to do).
public delegate bool Step(World world, int me);

public static class Interleavings
{
    // Tries every order in which the actors' steps can be interleaved (each actor's own steps stay in order) and counts the
    // orders that end with a cached value that differs from the database, which would stay wrong until its time to live.
    public static (int Orders, int Stale, string Example) Check(int actors, Step[][] scripts, string[] names, Func<World> start)
    {
        int orders = 0, stale = 0;
        string example = null;

        void Explore(World world, string path)
        {
            bool moved = false;
            for (int a = 0; a < actors; a++)
            {
                if (world.Next[a] >= scripts[a].Length) continue;
                moved = true;
                var next = world.Copy();
                bool more = scripts[a][world.Next[a]](next, a);
                next.Next[a] = more ? world.Next[a] + 1 : scripts[a].Length;
                Explore(next, path + names[a] + (world.Next[a] + 1) + " ");
            }
            if (moved) return;
            orders++;
            if (world.Cache != null && world.Cache != world.Db) { stale++; example ??= path.Trim(); }
        }

        Explore(start(), "");
        return (orders, stale, example);
    }
}
C# · The steps the protocols are made of.34 lines
using System;
using System.Diagnostics;

// The steps the protocols are made of.
Step get = (w, me) => { if (w.Cache != null) { w.Held[me] = w.Cache.Value; return false; } return true; };       // a hit ends the read
Step getWithLease = (w, me) => { if (w.Cache != null) return false; w.Token[me] = w.Lease = w.NextToken++; return true; };   // a miss is given a lease
Step readDb = (w, me) => { w.Held[me] = w.Db; return true; };
Step fill = (w, me) => { w.Cache = w.Held[me]; return true; };
Step fillWithLease = (w, me) => { if (w.Lease == w.Token[me]) { w.Cache = w.Held[me]; w.Lease = 0; } return true; };     // refused if the lease was cancelled
Step Write(int value) => (w, me) => { w.Db = value; return true; };
Step Set(int value) => (w, me) => { w.Cache = value; return true; };
Step delete = (w, me) => { w.Cache = null; w.Lease = 0; return true; };                                         // a delete cancels any lease

var cacheAside = new[] { get, readDb, fill };
var leased = new[] { getWithLease, readDb, fillWithLease };
World Empty(int actors) => new World(actors);

var results = new (string Name, (int Orders, int Stale, string Example) Result)[]
{
    ("update the database, then delete the key", Interleavings.Check(2, new[] { cacheAside, new[] { Write(2), delete } }, new[] { "R", "W" }, () => Empty(2))),
    ("delete the key, then update the database", Interleavings.Check(2, new[] { cacheAside, new[] { delete, Write(2) } }, new[] { "R", "W" }, () => Empty(2))),
    ("update, delete, and delete again later", Interleavings.Check(2, new[] { cacheAside, new[] { Write(2), delete, delete } }, new[] { "R", "W" }, () => Empty(2))),
    ("two writers: update the database, then set the key", Interleavings.Check(2, new[] { new[] { Write(2), Set(2) }, new[] { Write(3), Set(3) } }, new[] { "A", "B" }, () => Empty(2))),
    ("two writers that delete, and a reader", Interleavings.Check(3, new[] { cacheAside, new[] { Write(2), delete }, new[] { Write(3), delete } }, new[] { "R", "A", "B" }, () => Empty(3))),
    ("update, delete, and a reader with a lease", Interleavings.Check(2, new[] { leased, new[] { Write(2), delete } }, new[] { "R", "W" }, () => Empty(2))),
    ("two writers that delete, and a reader with a lease", Interleavings.Check(3, new[] { leased, new[] { Write(2), delete }, new[] { Write(3), delete } }, new[] { "R", "A", "B" }, () => Empty(3))),
};
Debug.Assert(results[0].Result.Orders == 10 && results[0].Result.Stale == 1 && results[0].Result.Example == "R1 R2 W1 W2 R3");
Debug.Assert(results[1].Result.Orders == 10 && results[1].Result.Stale == 6 && results[1].Result.Example == "R1 R2 W1 R3 W2");     // deleting first is worse
Debug.Assert(results[2].Result.Orders == 20 && results[2].Result.Stale == 1 && results[2].Result.Example == "R1 R2 W1 W2 W3 R3");   // a later delete does not remove the bad order
Debug.Assert(results[3].Result.Orders == 6 && results[3].Result.Stale == 2 && results[3].Result.Example == "A1 B1 B2 A2");
Debug.Assert(results[4].Result.Orders == 210 && results[4].Result.Stale == 24 && results[4].Result.Example == "R1 R2 A1 A2 B1 B2 R3");
Debug.Assert(results[5].Result.Orders == 10 && results[5].Result.Stale == 0 && results[5].Result.Example == null);                 // with a lease, no order goes wrong
Debug.Assert(results[6].Result.Orders == 210 && results[6].Result.Stale == 0 && results[6].Result.Example == null);

In the table R1 is the reader's first step, W2 the writer's second step, and so on. Each row shows one order that goes wrong.

ProtocolOrdersLeave a stale entryOne bad order
Update the database, then delete the key101R1 R2 W1 W2 R3
Delete the key, then update the database106R1 R2 W1 R3 W2
Update, delete, and delete again later201R1 R2 W1 W2 W3 R3
Two writers: update the database, then set the key62A1 B1 B2 A2
Two writers that delete, and a reader21024R1 R2 A1 A2 B1 B2 R3
Update, delete, and a reader with a lease100none
Two writers that delete, and a reader with a lease2100none
  • Delete after the write, never before. Deleting first leaves a window, from the delete to the database update, in which any reader refills the old value: 6 of 10 orders go wrong against 1 of 10.
  • A delayed second delete is a mitigation, not a fix. The bad order survives (1 of 20). It only needs the reader to stall for longer than the delay.
  • Updating the cache on a write is worse. Two writers can finish their database writes and their cache writes in opposite orders (2 of 6). Deletes do not depend on order.
  • A lease closes the race exactly. The cache hands a token to the client whose get missed, the client can fill only by presenting it, and a delete cancels outstanding tokens, so a fill that began before the invalidation is refused: 0 of 10 and 0 of 210. Facebook's memcache uses leases for this and to curb stampedes by limiting how often a token is issued for a key. The model here is a simplification with one token per key.
  • Versions are the alternative. Store the row's version in the entry and refuse a fill with an older one. A delete then has to leave a short-lived tombstone carrying the version, otherwise an old fill after a delete looks like a first fill.
  • Fill from the primary when it matters. A reader that fills the cache from a lagging replica re-creates stale data even under a perfect protocol. After an invalidation, read from the primary.
  • Invalidate from the change log. If the application crashes between the database write and the delete, the invalidation is lost: the dual-write problem from distributed transactions. Publish row changes through the database's log (see change data capture in logs, streams and Kafka) and have a consumer delete the keys. Deletes are idempotent and indifferent to order, so at-least-once delivery is enough.
  • The time to live is the guarantee. Every protocol above can still lose an invalidation somewhere (a failover, a bug), and the time to live bounds the damage. Choose it as the staleness the product accepts, and treat invalidation as an optimisation that usually makes staleness much shorter.

A stampede (a thundering herd) happens when a popular entry expires and every request that misses goes to the database for the same row. The same thing follows a node restart, a deploy that changes the key format (a deliberately cold cache) and a batch fill that gives thousands of keys the same expiry. The mitigations differ in what they cost:

  • Coalesce per server (single flight). A server with a rebuild in flight makes its other requests wait for it. One database read per server, not per request.
  • A lease or lock in the cache. Only the holder rebuilds, in the whole cluster. The rest wait briefly or retry.
  • Serve the stale value meanwhile. Keep a value for a grace period after its expiry (stale-while-revalidate). The lease holder rebuilds in the background and nobody waits, at the price of serving a slightly old value.
  • Refresh early, probabilistically. Each request that finds a fresh entry may recompute it before expiry, with a probability that rises as expiry nears. A VLDB 2015 paper (Vattani, Chierichetti and Lowenstein) analyses this and proposes recomputing when now - delta * beta * ln(random) >= expiry, where delta is how long a rebuild takes and beta tunes eagerness. The entry is rarely missing, so nobody waits, and no lock is needed. It works only for keys read often enough to trigger the refresh in time.
  • Jitter the times to live, so many keys do not expire together.
C# · Strategy, StampedeResult, Stampede77 lines
using System;
using System.Collections.Generic;

public enum Strategy { None, CoalescePerServer, Lease, ServeStale, EarlyRefresh }

public sealed class StampedeResult
{
    public int DatabaseReads, Rounds, PeakInFlight, Waited, ServedStale;
    public double ReadsPerRound => Rounds == 0 ? 0 : (double)DatabaseReads / Rounds;
}

public static class Stampede
{
    // One hot key. Requests arrive at `rate` a second (a Poisson process) spread over `servers` application servers.
    // The entry lives for ttlMs and rebuilding it takes rebuildMs of database time. Time moves in 1 ms steps,
    // and the entry is cached at t = 0.
    public static StampedeResult Run(Strategy strategy, double rate, int servers, int ttlMs, int rebuildMs, int durationMs, int graceMs, int seed)
    {
        var random = new Random(seed);
        var result = new StampedeResult();
        long expiresAt = ttlMs;
        var finishing = new List<long>();                  // when each rebuild in flight will finish
        var serverRebuild = new long[servers];             // per server: when its own rebuild finishes
        bool leaseTaken = false;
        double limit = Math.Exp(-rate / 1000.0);

        void StartRebuild(long now)
        {
            if (finishing.Count == 0) result.Rounds++;     // a new round: nothing was being rebuilt a moment ago
            finishing.Add(now + rebuildMs);
            result.DatabaseReads++;
            result.PeakInFlight = Math.Max(result.PeakInFlight, finishing.Count);
        }

        for (long t = 0; t < durationMs; t++)
        {
            for (int i = finishing.Count - 1; i >= 0; i--)          // a finished rebuild puts a fresh entry in the cache
                if (finishing[i] <= t) { finishing.RemoveAt(i); expiresAt = t + ttlMs; leaseTaken = false; }

            int arrivals = 0;
            for (double product = random.NextDouble(); product > limit; product *= random.NextDouble()) arrivals++;

            for (int request = 0; request < arrivals; request++)
            {
                int server = random.Next(servers);
                if (expiresAt > t)                                   // cached and fresh: served at once...
                {
                    // ...except that, with early refresh, the closer the expiry the likelier a request is to recompute now.
                    if (strategy == Strategy.EarlyRefresh && t - rebuildMs * Math.Log(random.NextDouble()) >= expiresAt)
                    { StartRebuild(t); result.Waited++; }
                    continue;
                }

                switch (strategy)
                {
                    case Strategy.None:                              // every request that misses goes to the database
                    case Strategy.EarlyRefresh:
                        StartRebuild(t); result.Waited++;
                        break;
                    case Strategy.CoalescePerServer:                 // one rebuild per server; its other requests wait for it
                        if (serverRebuild[server] <= t) { serverRebuild[server] = t + rebuildMs; StartRebuild(t); }
                        result.Waited++;
                        break;
                    case Strategy.Lease:                             // one rebuild in the whole cluster; everyone else waits
                        if (!leaseTaken) { leaseTaken = true; StartRebuild(t); }
                        result.Waited++;
                        break;
                    case Strategy.ServeStale:                        // one rebuild; meanwhile the expired value is served
                        if (!leaseTaken) { leaseTaken = true; StartRebuild(t); }
                        if (t - expiresAt < graceMs) result.ServedStale++; else result.Waited++;
                        break;
                }
            }
        }
        return result;
    }
}
C# · A key read 2,000 times a second by 20 servers, with a one-minute time to live and a 100…16 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;

// A key read 2,000 times a second by 20 servers, with a one-minute time to live and a 100 ms rebuild, for ten minutes.
var stampede = new Dictionary<Strategy, StampedeResult>();
foreach (Strategy strategy in Enum.GetValues(typeof(Strategy)))
    stampede[strategy] = Stampede.Run(strategy, rate: 2_000, servers: 20, ttlMs: 60_000, rebuildMs: 100, durationMs: 600_000, graceMs: 5_000, seed: 11);

Debug.Assert(stampede[Strategy.None].ReadsPerRound > 195 && stampede[Strategy.None].ReadsPerRound < 220);       // about rate x rebuild time = 200
Debug.Assert(stampede[Strategy.None].PeakInFlight > 200);
Debug.Assert(stampede[Strategy.CoalescePerServer].ReadsPerRound == 20 && stampede[Strategy.CoalescePerServer].PeakInFlight == 20);   // one per server
Debug.Assert(stampede[Strategy.Lease].ReadsPerRound == 1 && stampede[Strategy.Lease].PeakInFlight == 1);
Debug.Assert(stampede[Strategy.ServeStale].ReadsPerRound == 1 && stampede[Strategy.ServeStale].Waited == 0);
Debug.Assert(stampede[Strategy.ServeStale].ServedStale == stampede[Strategy.Lease].Waited);                    // the requests that waited are served stale instead
Debug.Assert(stampede[Strategy.EarlyRefresh].ReadsPerRound < 5 && stampede[Strategy.EarlyRefresh].ServedStale == 0);

The key is read 2,000 times a second by 20 servers, expires every minute, takes 100 ms of database time to rebuild, and the run lasts ten minutes (nine expiries, and ten refreshes for early refresh).

StrategyDatabase reads per expiryMost at onceRequests that waitedServed stale
None: every miss reads the database206.72371,8600
One rebuild per server20.0201,8150
One rebuild in the cluster (a lease)1.011,8040
A lease, with the stale value served meanwhile1.0101,804
Early refresh3.06300

Without protection each expiry sent about 207 identical queries to the database inside 100 ms (the rate times the rebuild time is 200). Coalescing per server cut that to one per server, a lease to one, and serving the stale value kept the single rebuild and made nobody wait. Early refresh needed about three rebuilds per refresh, because requests that arrive while the first is running can also trigger one, and 30 requests waited in ten minutes. The model uses a fixed rebuild time. A real stampede feeds itself: a busier database rebuilds more slowly, which lets more requests pile up behind the expiry. Real systems combine the defences: jittered times to live everywhere, coalescing in the client, and a lease or stale-while-revalidate for the hottest keys.

HLD

Hot keys: when placement cannot help

A hot key is a key whose traffic alone exceeds what one node can serve, while the rest of the cluster is idle. Placement cannot help, because placement spreads keys, and one key is one key. The sample hashes one million keys over 20 and over 100 nodes, gives them Zipf traffic (a few keys requested very often, a long tail requested rarely) and measures the busiest node against a fair share, which is 1/N of all traffic.

C# · Where does the traffic land? One million keys whose popularity follows a Zipf law…56 lines
using System;
using System.Diagnostics;
using System.Linq;

// Where does the traffic land? One million keys whose popularity follows a Zipf law, spread over nodes by hashing.
const int hotKeys = 1_000_000;

uint HashOf(string text)                                          // FNV-1a with a final mixing step
{
    uint h = 2166136261;
    foreach (char c in text) { h ^= c; h *= 16777619; }
    h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16;
    return h;
}

double[] ZipfShares(double exponent)                              // key r (counting from 0) is requested in proportion to 1 / (r + 1)^exponent
{
    var shares = new double[hotKeys];
    double sum = 0;
    for (int r = 0; r < hotKeys; r++) sum += shares[r] = 1.0 / Math.Pow(r + 1, exponent);
    for (int r = 0; r < hotKeys; r++) shares[r] /= sum;
    return shares;
}

int[] OwnersOf(int nodes) => Enumerable.Range(0, hotKeys).Select(key => (int)(HashOf("key:" + key) % (uint)nodes)).ToArray();
var ownerOf20 = OwnersOf(20);
var ownerOf100 = OwnersOf(100);

// The busiest node's load as a multiple of a fair share (1/nodes of the traffic). Keys numbered below `spread` are the
// hottest ones, and here each node holds a copy of them, so their traffic is split evenly.
double BusiestNode(double[] shares, int[] ownerOf, int nodes, int spread)
{
    var load = new double[nodes];
    for (int key = 0; key < shares.Length; key++)
    {
        if (key < spread) for (int node = 0; node < nodes; node++) load[node] += shares[key] / nodes;
        else load[ownerOf[key]] += shares[key];
    }
    return load.Max() * nodes;
}

// For each skew: the hottest key's share of all traffic, the busiest node's multiple of a fair share with 20 and with 100 nodes,
// and the same multiples when the 100 hottest keys are read from every node.
var expected = new[]
{
    (Exponent: 0.8, Hottest: 0.013, Busy20: 1.28, Busy100: 2.59, Spread20: 1.04, Spread100: 1.11),
    (Exponent: 1.0, Hottest: 0.069, Busy20: 2.38, Busy100: 8.71, Spread20: 1.08, Spread100: 1.18),
    (Exponent: 1.2, Hottest: 0.190, Busy20: 4.63, Busy100: 21.10, Spread20: 1.07, Spread100: 1.17),
};
foreach (var row in expected)
{
    var traffic = ZipfShares(row.Exponent);
    Debug.Assert(Math.Abs(traffic[0] - row.Hottest) < 0.001);
    Debug.Assert(Math.Abs(BusiestNode(traffic, ownerOf20, 20, 0) - row.Busy20) < 0.02 && Math.Abs(BusiestNode(traffic, ownerOf100, 100, 0) - row.Busy100) < 0.02);
    Debug.Assert(Math.Abs(BusiestNode(traffic, ownerOf20, 20, 100) - row.Spread20) < 0.02 && Math.Abs(BusiestNode(traffic, ownerOf100, 100, 100) - row.Spread100) < 0.02);
}
Zipf exponentHottest key's share of trafficBusiest of 20 nodesBusiest of 100 nodesThe 100 hottest keys on every node (20 nodes, 100 nodes)
0.81.3%1.28x2.59x1.04x, 1.11x
1.06.9%2.38x8.71x1.08x, 1.18x
1.219.0%4.63x21.10x1.07x, 1.17x

The multiples are against a fair share. The hottest key's share depends on the skew, not on how many keys there are: with an exponent of 1.0 it alone is 6.9% of all traffic, more than the fair share of 20 nodes (5%). More nodes shrink the fair share but not the hot key, so the busiest node gets relatively worse (8.71 times a fair share at 100 nodes against 2.38 at 20). Reading the hottest 100 keys from every node, which costs 100 entries on each node, brought the busiest node to 1.08 times. The techniques:

  • A near cache. A tiny in-process cache with a time to live of a second or so in every application server absorbs the hottest keys before they cross the network.
  • Copies under several names. Store the hot key as key#0 to key#k-1, read a random one, and write or delete all of them. It costs k copies and k deletes.
  • Detect hot keys automatically. Sample requests and keep the heavy hitters with a count-min sketch and a small heap (see probabilistic data structures), promote them to the near cache or the copied set, and demote them when they cool.
  • Split write-hot keys. A counter updated by everyone becomes ten counters (views:42:0 to views:42:9) that are summed on read.
Example · estimate
a hot key read 70,000 times a second by 500 application servers
near cache with a 1 s time to live: each server asks the cache once a second
remote reads: 500/s instead of 70,000, 140x fewer; staleness up to 1 s

With a near cache the remote load of a hot key becomes the number of servers divided by the time to live, whatever the traffic. The price is the staleness of the near cache, which is why it is used for keys where a second of staleness is acceptable.

HLD

Failure modes and edge cases

CaseWhat goes wrongResponse
A reader fills a stale value after an invalidationStale until the time to liveDelete after the write, leases or versions, a time to live as the backstop
An invalidation is lost (a crash, a failover)Stale until the time to liveInvalidate from the change log, idempotent deletes, a time to live
The cache is filled from a lagging replicaStale data is re-created after a correct invalidationRead the primary after an invalidation, or compare versions
A popular key expiresHundreds of identical database reads at onceA lease, coalescing, stale-while-revalidate, early refresh
Many keys share one expiry timeA wave of misses and a spike on the databaseJitter on every time to live
A deploy changes the key formatEvery key misses at onceVersioned keys, a gradual rollout, reading the old key as a fallback
A hot keyOne node saturates while the cluster is idleA near cache, copies under several names, heavy-hitter detection
A write-hot key such as a counterOne node serialises every updateSharded counters summed on read, or batching the writes

Senior depth

What senior interviews ask about cache consistency

Interviewer follow-upL5How does a stale value end up in a cache-aside cache, and how long does it last?How to answer

A reader misses, reads the old row, stalls, and fills the old value after a writer has updated the database and deleted the key. The entry then stays until its time to live (1 of 10 interleavings in the model). Closing it needs a lease or a version check on the fill. A time to live bounds how long any stale entry can last.

Interviewer follow-upL5What is a cache stampede and how do you stop it?How to answer

A popular entry expires and every request that misses rebuilds it from the database at once: about 207 identical reads per expiry in the simulation. Coalesce rebuilds per server, or take a lease so one client rebuilds (one read), serve the stale value for a grace period while it does, refresh early with a probability that rises near expiry, and jitter times to live so entries do not expire together.

Interviewer follow-upL6Why delete the key on a write instead of updating it?How to answer

A delete is idempotent and does not depend on order. Two writers that update the cache can finish their cache writes in the opposite order to their database writes and leave the older value behind (2 of 6 interleavings). Two writers that delete cannot. The next read repopulates the entry from the database.

Interviewer follow-upL6The application can crash between the database write and the delete. How do you invalidate reliably?How to answer

Do not make the application responsible for both. Publish row changes from the database's own log (change data capture or an outbox) and have a consumer delete the keys. Deletes are idempotent and order-insensitive, so at-least-once delivery is enough, and a replayed or duplicated delete is harmless. Keep a time to live as the backstop for a bug or a lost event.

Interviewer follow-upL6Is a delayed second delete a safe fix for the stale-set race?How to answer

No. It narrows the window, but the bad order still exists: the model shows it in 1 of 20 interleavings. The reader only has to stall for longer than the delay. It is a cheap mitigation. A lease or a version check is the fix.

Interviewer follow-upL6One key takes 7% of all traffic and its node is saturated. What do you do?How to answer

Placement cannot fix it, because it spreads keys, not the traffic of one key. Put a near cache with a time to live of about a second in every application server, store the key under several names and read a random one, and detect hot keys automatically with a heavy-hitters sketch so the set adapts. Split a write-hot key such as a counter into shards that are summed on read.

Interviewer follow-upL7How would you convince yourself a cache protocol is correct?How to answer

State the invariant (the cache never keeps a value the database has overwritten, apart from entries that will expire), list the actors and their atomic steps, and enumerate every interleaving, as the checker does, or use a model checker such as TLA+ for larger designs. Then test the implementation under injected delays and failures, because the model checks the protocol and not the code. A small model finds the race that code review and load tests miss.

Interviewer follow-upL7How do you invalidate caches across regions?How to answer

Each region keeps its own cache beside its own database replica. Deletes must reach every region, usually by reading the database's commit log and broadcasting them. A writer must not read a stale value from a lagging replica and cache it, so mark recently written keys and read them from the primary region. Everyone else accepts staleness up to the replication lag plus the time to live, and the product decides whether that is acceptable.

HLD

Putting it into an answer

Say what the cache may get wrong and for how long, then show the defence for each failure. For consistency: cache-aside, delete after the write, a lease or version check where the race matters, invalidation from the change log, and a time to live as the guarantee. For stampedes: coalescing or a lease, serve stale or refresh early, and jittered expiry. For hot keys: a near cache and copies of the hottest keys, found by a heavy-hitters sketch.

Summary

A cache-aside cache can keep a stale value when a slow reader fills the old row after a writer's delete. Enumerating every interleaving shows the plain protocol going wrong in 1 of 10 orders, deleting before updating in 6 of 10, a delayed second delete still in 1 of 20, and a lease in none. Deletes beat updates, the change log keeps invalidation reliable, and the time to live bounds whatever is left. A popular key that expires sends hundreds of identical queries to the database at once (about 207 per expiry in the simulation); coalescing cuts that to one per server, a lease or stale-while-revalidate to one, and early refresh to about three. A hot key cannot be spread by placement: at an exponent of 1.0 the hottest key alone is 6.9% of traffic, so the busiest node carries 2.38 times its fair share of 20 nodes and 8.71 times of 100. A near cache and copies of the hottest keys fix it.

Check yourself

Try answering out loud before you reveal each answer.

QuestionA writer updates the database and then deletes the cache key, yet the cache later serves the old value. How, and what closes the gap?Reveal answer

A reader missed, read the old row, was delayed, and set the old value after the writer's delete. The value then stays until its time to live. A lease (the fill is accepted only with a token that a delete cancels), a version check on the fill, and a time to live as a backstop close or bound it. Deleting before updating the database is worse, because any reader in the gap refills the old value.

QuestionA popular key expires and 200 identical queries reach the database in 100 ms. Name three ways to bring that to one or a few.Reveal answer

Coalesce rebuilds so one request per server rebuilds and the rest wait; take a lease or lock in the cache so one client in the cluster rebuilds; serve the stale value for a grace period while one request refreshes it; refresh early with a probability that rises as expiry nears. Jittering times to live also helps, because keys no longer expire together.

QuestionA key takes 7% of all traffic and you have 100 nodes. Why does adding more nodes not help?Reveal answer

Placement spreads keys, not the requests for one key. A fair share of 100 nodes is 1% and the hot key alone is 7%, so its node carries at least seven times a fair share however many nodes there are. Serve the hot key from a near cache in each application server, or keep copies under several names and read a random one.

QuestionWhy is it not enough to retry the delete if it fails, and what does a lost delete cost?Reveal answer

A lost delete leaves the old value in the cache until its time to live, and a retry from the application fails the same way if the application itself crashed. Publish changes from the database's log so a consumer deletes the key whatever happens to the application, and keep a time to live as the backstop.

Sources and further reading

Lesson 4 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 5Replication and shardingHow a database scales past one machine. Replicas for reads and failover, shards for writes and size, and the shard-key decisions that are very hard to undo.

Send a message

It goes straight to my inbox. I usually reply within a few days.