How systems work

Caches.

A cache keeps a copy of data somewhere faster than where it really lives. Reading a value from memory takes a fraction of a millisecond. Asking a database can take tens of milliseconds and uses up capacity the database needs for writes.

The hard parts are all about the copy: when to make it, when to throw it away, what to keep when you run out of room, and what happens when the real data changes and the copy does not. This page shows each one happening, then the fix.

In the labs after the walkthrough, every chip is a single read in a simulation running in your browser, and the letter is the key it asks for. The most popular keys are coloured; the long tail is grey. Each slot in the cache shows which key it holds and that copy’s version. The database on the right shows its workers and the line of queries waiting for one.

a read hit miss, going to the database served an old value a write

00 The life of one cached key

Before the live labs, follow one key from its first read to the day it is evicted. Step through at your own pace, or press Play all.

App serverRuns your codeCacheCopies in memory · 4 slotshits 0 · misses 0B$35TTL 41sC$8TTL 12sempty slotempty slotDatabaseEvery row · slowerkeypriceversionA$20v1B$35v1C$8v1D$12v1E$5v1no query runningruns your code, asksfor datacopies in memory: fast, but only room for4every row: slower, thesource of truth

Step 1 of 10

Meet the pieces

The app server runs your code and needs data. The cache keeps copies of a few rows in memory, where reading is fast. The database holds every row and is the source of truth, but each query is slower.

01 Why cache: speed and load

A cache helps in two ways. Reads that find their key in the cache (a hit) are answered fast. And every hit is a query the database does not have to run, so the database has room for the reads that do reach it (the misses) and for writes.

The second effect is often the one that matters. A database that can serve a few thousand reads a second can sit behind a cache that answers a hundred thousand, as long as the hit rate is high.

App4 reads/sReadersAsk for keysCache · 8 slotsCopies in memory, fastemptyemptyemptyemptyemptyemptyemptyemptyDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueued
Hit rate
0%
Average read
0 ms
Database reads/s
0.0
Waiting at database
0

Click any read to follow it.

Eight keys, a cache with room for all of them, and a database with four workers that can serve about 5.7 reads a second.
    Try this. Turn the cache off. Every read now waits for a database worker, so the average read slows from about 150 ms to the better part of a second. Raise reads per second to 8 with the cache still off: the line at the database grows without end. Turn the cache back on and it drains. Then shrink the cache to 3 slots and set skew to Even: the hit rate falls, because the reads no longer cluster on a few keys.

    Hit rate is the number to watch, and the top of the range matters most. At 99% hits, 1 read in 100 reaches the database. At 98%, it is 2 in 100: a one-point drop doubles the database load. Real traffic is usually skewed, a few keys get most reads, which is why a cache much smaller than the data can still catch most reads.

    A cache is a capacity tool as much as a speed tool. Size it for the hit rate you need, and plan for what the database sees when the hit rate drops.

    02 The read path: cache-aside

    The most common pattern is cache-aside, also called lazy loading. The application, not the cache, does the work:

    • Look for the key in the cache. If it is there, use it. That is a hit.
    • If not, that is a miss: query the database.
    • Store the answer in the cache, so the next read hits.

    The cache only ever holds keys someone asked for, and a cache that is down or empty only makes reads slower, not wrong. The cost is that every key’s first read is slow, and the cache needs a way to learn that data changed (sections 03 and 04).

    App1 reads/sReadersAsk for keysCache · 4 slotsCopies in memory, fastemptyemptyemptyemptyDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueued
    Hit rate
    0%
    Average read
    0 ms
    Database reads/s
    0.0

    Click any read to follow it.

    One read a second, slowed right down. Each read is logged below the lab.
      Watch. Follow one chip. A miss (dashed red outline) goes to the database, waits for its query, then flies back to a slot, which flashes orange as the copy is stored. The next read of that key turns green on its slot and is done in a quarter of the time. There are six keys and four slots, so now and then a key is pushed out to make room.

      Cache-aside: read the cache, on a miss read the database and fill the cache. Simple, and the default unless you have a reason to pick something else.

      03 The write paths

      When data changes, the database gets the new value. The question is what happens to the copy in the cache. Three common answers:

      • Write, then delete (invalidate). Save to the database, then delete the key from the cache. The next read misses and loads the new value. Simple and safe, at the cost of one extra miss per write.
      • Write-through. Save to the database, then put the new value in the cache. The next read hits. Writes take a little longer, and you may cache values nobody reads.
      • Write-behind (write-back). Put the new value in the cache and answer at once. The cache saves it to the database later, often in batches. Writes are fast, but if the cache dies before it saves, the write is gone.
      App3 reads/sReadersAsk for keysCache · 4 slotsCopies in memory, fastAv1Bv1Cv1Dv1Database · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueuedWritesStored valuesA v1B v1C v1D v1
      Hit rate
      0%
      Average write
      —
      Stale reads
      0
      Lost writes
      0

      Click any read to follow it.

      Four keys, all cached. Dark chips are writes. The database's stored values are listed under its workers.
      On a write
      1. Warm-up: a job loaded 4 keys into the cache at once.
      Try this. With “Write, then delete”, press Write A: the database moves to v2, A’s slot empties, and the next read of A misses and loads v2. Switch to write-through and write again: the slot changes to the new version straight away. Now pick write-behind, press Write A and then, within three seconds, Restart the cache. The slot showed “unsaved”, and that write is lost.

      Invalidate on write is the safe default. Use write-through when reads right after a write must hit, and write-behind only for data you can afford to lose or rebuild, like counters and view counts.

      04 TTL and stale data

      Sometimes the cache is not told about a change. Another service wrote to the database, a job ran a bulk update, or the code that deletes keys has a bug. The cache then serves the old value, a stale read, for as long as it keeps that copy.

      A time to live (TTL) puts a limit on that. Each entry expires a fixed time after it was stored, so even a copy nobody invalidates is replaced eventually. The TTL is your answer to “how old may this data be?”

      App5 reads/sReadersAsk for keysCache · 4 slots · TTL 8.0sCopies in memory, fastAv18.0s leftBv18.0s leftCv18.0s leftDv18.0s leftDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueuedWritesStored valuesA v1B v1C v1D v1
      Stale reads
      0
      Old values cached
      0
      Hit rate
      0%
      Database reads/s
      0.0

      Click any read to follow it.

      Writes go to the database only; the cache is never told. The bar along each slot is the time it has left.
      1. Warm-up: a job loaded 4 keys into the cache at once.
      Try this. Press Write A. The database has v2, but A’s slot turns red and every read of A comes back red, stale, until its bar runs out. Set the TTL to 2 seconds and write again: the stale window is short, but the database now sees many more reads. Set it to Never and the old value stays forever.

      Short TTLs mean fresher data and more database load; long TTLs the reverse. Invalidate on write for correctness, and keep a TTL anyway as a safety net for the writes you did not know about.

      05 Eviction: what to drop when full

      A cache has a fixed amount of memory. When it is full and a new key arrives, something must go. The eviction policy picks the victim:

      • LRU (least recently used) drops the key that has gone longest without a read. It adapts quickly when popularity changes, but a one-off scan of many cold keys can push out every hot key.
      • LFU (least frequently used) drops the key with the fewest reads. It holds on to steady favourites and shrugs off scans, but a key that used to be popular can sit there long after everyone stopped reading it.
      • FIFO (first in, first out) drops the oldest entry, however popular. Cheap to run, and usually the worst hit rate.
      App10 reads/sReadersAsk for keysCache · 5 slotsCopies in memory, fastemptyemptyemptyemptyemptyDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueued
      Hit rate
      0%
      Evictions
      0
      Database reads/s
      0.0

      Click any read to follow it.

      Sixteen keys, five slots. A, B and C get most of the reads. Each slot shows what the policy looks at.
      Eviction policy
        Try this. Compare the hit rate under each policy: LFU and LRU keep A, B and C cached and beat FIFO. On LRU, press Run a scan: ten cold keys push the hot ones out and the hit rate drops for a while. Do the same on LFU and the hot keys stay. Now press Shift popularity on LFU: the old favourites keep their high counts, the new hot keys are evicted again and again, and the hit rate stays low. LRU recovers within seconds.

        LRU is the usual default. Real caches blend recency and frequency, and LFU in practice decays its counts over time, to get the best of both.

        06 Cold starts and keys that expire together

        An empty cache, after a restart, a deploy or a new node, misses on everything. The database suddenly gets all the reads the cache used to absorb, often far more than it was sized for. A team that runs at a 95% hit rate has built a database for 5% of the traffic.

        A common fix is to warm the cache: a job loads the popular keys before traffic arrives. That brings its own trap. Keys stored at the same moment with the same TTL also expire at the same moment, and the database gets a wave of misses every TTL. Adding a little randomness to each TTL, jitter, spreads the expiries out.

        App16 reads/sReadersAsk for keysCache · 12 slots · TTL 6.0sCopies in memory, fastAv16.0s leftBv16.0s leftCv16.0s leftDv16.0s leftEv16.0s leftFv16.0s leftGv16.0s leftHv16.0s leftIv16.0s leftJv16.0s leftKv16.0s leftLv16.0s leftDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueued
        Hit rate
        0%
        Waiting at database
        0
        Database reads/s
        0.0
        Expired
        0

        Click any read to follow it.

        Twelve equally popular keys, warmed up all at once with a 6-second TTL.
        1. Warm-up: a job loaded 12 keys into the cache at once.
        Try this. Watch the TTL bars run down together and every slot empty at once: a line forms at the database. Set jitter to ±30% and press Warm up the cache. The bars now end at different times and the line stays short. Press Restart the cache to see a full cold start.

        Never assume the cache is warm. Know what your database sees at a 0% hit rate, warm caches gradually, and add jitter to TTLs that are set in bulk.

        07 The stampede on a hot key

        When one very popular key expires, every read in the next few hundred milliseconds misses. Each of those readers asks the database for the same row, and each one stores the same answer. This is a cache stampede (or thundering herd). For a key read thousands of times a second, it can be thousands of identical queries at once.

        Fixes, from simplest:

        • Coalesce loads. Only the first miss queries the database. Others for the same key wait for that one answer. This is a per-key lock, or Go’s singleflight, or request collapsing in a CDN.
        • Refresh early. When a key is read close to its expiry, reload it in the background while the old value is still served. Popular keys never actually expire. The XFetch approach makes the timing random, so servers do not all refresh at once.
        • Serve stale while revalidating. Keep serving the expired value for a short grace period while one request refreshes it. HTTP caches support this with stale-while-revalidate.
        App14 reads/sReadersAsk for keysCache · 6 slots · TTL 5.0sCopies in memory, fastemptyemptyemptyemptyemptyemptyDatabase · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueued
        Misses on A
        0
        Extra loads of A
        0
        Waiting at database
        0
        Hit rate
        0%

        Click any read to follow it.

        Six keys; A gets about half of all reads. Every 5 seconds A expires.
        Stampede protection
          Try this. With no protection, watch A’s slot when its bar runs out: a handful of A reads all miss and all queue for the database, and “Extra loads of A” jumps each time. Pick Coalesce loads: the misses now wait in the yellow row for the one load in flight, and the count stops rising. Pick Early refresh: a dashed ↻A query reloads A before it expires, and misses on A stop entirely.

          Any key that is read far more often than it is reloaded needs stampede protection. Coalescing is the minimum; early refresh avoids the miss entirely.

          08 Invalidation races

          “Write the database, delete the key” looks simple, but the writer and the readers run at the same time and their steps can interleave badly. Two classic cases:

          • Delete, then write. The writer deletes the key, then starts its database write. A reader misses in that gap, reads the old value from the database, and puts it back in the cache. The write lands, but the cache now holds the old value until its TTL ends, or forever if there is none.
          • Write, then delete, with a slow reader. A reader misses and reads the old value. Before it stores it, perhaps paused by garbage collection, the writer writes and deletes. Then the reader stores the old value. Rare, because the reader must miss and be slow at just the wrong time, but at scale rare things happen daily.

          Facebook’s memcache paper describes the fix for the second case: leases. A miss hands the reader a token, a delete cancels outstanding tokens, and a store with a cancelled token is refused. Versioned values (store only if newer) work the same way.

          App5 reads/sReadersAsk for keysCache · 3 slotsCopies in memory, fastAv1Bv1Cv1Database · 4 workersThe source of truth, slowerIdleIdleIdleIdleQueuedWritesStored valuesA v1B v1C v1
          Old values cached
          0
          Stale reads
          0
          Stores refused
          0

          Click any read to follow it.

          Three keys, no TTL, and a database write that takes 1.5 seconds. A is read about five times a second.
          On a write
          1. Warm-up: a job loaded 3 keys into the cache at once.
          Try this. On Delete, then write, press Write A. A reader misses during the write, loads v1 and stores it. The database moves to v2, but A’s slot stays red on v1 for good. Press Reset, choose Write, then delete, and write again: the slot ends on the new version. Now press Write A during a slow read: the slow reader stores its old v1 after the delete, and A is stuck again. Turn on leases and repeat: that store is refused.

          Write the database first, then delete the key. Add leases or version checks if stale data is costly, and always keep a TTL so that any mistake heals itself.

          09 Where caches live

          A request can pass several caches before it reaches the database, each nearer the user than the last:

          • Browser. The user’s own device keeps responses, as the server’s Cache-Control header allows. Free and instant, but only for that one user, and you cannot delete it from the server.
          • CDN. Servers near users cache public responses such as images, scripts and pages that look the same for everyone. They cut the long trip to your servers. Most CDNs let you purge a URL, but it takes time to reach every location.
          • App memory. A map inside each server process. The fastest cache you control, but each server has its own copy, so servers can disagree and each one warms up on its own.
          • Shared cache such as Redis or Memcached. One network hop away and shared by every server, so one delete reaches everyone.
          BrowserTTL 8.0sUser 1User 2User 3CDNTTL 12sPublic pages onlyApp memoryTTL 6.0sServer 1Server 2RedisTTL 30sShared by all serversDatabasethe sourceStored valuesAv1Bv1Cv1Dv1
          From browser
          —
          From CDN
          —
          From app memory
          —
          From Redis
          —
          From database
          —
          Stale answers
          0

          Click any request to follow it through the layers.

          Three users, a CDN, two app servers each with its own memory cache, Redis and the database. A and B are public pages; C and D are personal data, which the CDN must not cache. Each request stops at the first cache that has its key.
            Try this. Watch where reads stop: most never get past the browser or the CDN, and the database sees about one read in ten. Press Change A in the database. The app deletes A from Redis, the only cache it can reach directly, but browsers, the CDN and each server’s memory keep serving v1 (red) until their own TTLs end. Turn layers off to see the load move down to the database.

            The nearer a cache is to the user, the faster it is and the harder it is to invalidate. Cache public, slow-changing data near the edge and user-specific or fast-changing data in a shared cache you can delete from.

            10 Choosing a cache

            A rough map of the common choices:

            CacheWhat it isEvictionSharedGood for
            Redis / ValkeyIn-memory server with data structures (strings, hashes, sorted sets, streams), TTL per key, optional persistence and replicationConfigurable: approximate LRU or LFU, over all keys or only keys with a TTL, or noneYesThe default shared cache; also counters, rate limits, leaderboards, sessions
            MemcachedSimple multi-threaded key-value store, no persistence; clients spread keys across serversLRU (segmented)YesLarge, plain key-value caches with very simple operations
            In-process cachesA map in your process: Caffeine (Java), an LRU cache library in Node or PythonLRU, or a mix such as W-TinyLFU in CaffeineNo, one per serverVery hot, small, slow-changing data; config, feature flags
            CDN cachesCloudflare, Fastly, CloudFront, Akamai and others cache HTTP responses at the edgeProvider-managed, guided by Cache-ControlPer locationStatic files, images, public pages and API responses

            Check the current docs before you choose: features, limits and licences change. Redis changed its licence in 2024, and Valkey is a community fork that started from the last open-source release.

            11 Check yourself

            1. Your cache hit rate drops from 95% to 90%. Roughly what happens to the number of reads reaching the database?

            2. You update a product price in the database and delete its cache key. Which order is safer?

            3. One very popular key expires and the database briefly falls over. What is this, and what is a fix?

            4. A nightly report reads every row once. Next morning the cache hit rate is terrible. Which eviction policy made this worse?

            5. You cache user profiles in each app server’s memory for 5 minutes and in Redis. A user changes their name and you delete it from Redis. What do they see?

            Next partDatabases