Highlights

Contents

Part II
02

Caching patterns

We look at the five standard ways to arrange reads and writes between an application, a cache and a database. Each pattern answers who loads a miss, who writes the cache, and what happens to a write if something crashes halfway. We will cover cache-aside and its race, read-through and write-through, and write-behind and write-around.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Why cache, and where2Caching patterns3Expiry, eviction andsizing4Invalidation andconsistency5Cache failure modes6Redis data structures7Redis internals8Redis at scale9HTTP caching and CDNs10The menu request end toend

#Section 4Cache-aside

Cache-aside, also called lazy loading, is the pattern most backends use, and Wren’s menu endpoint is a textbook case. The application asks Redis for menu:9. On a hit it returns the value. On a miss it loads the menu from PostgreSQL, writes it to Redis with a TTL, and returns it. When the menu changes, the code that updates the database also deletes menu:9, so the next read loads the new version.

CACHE-ASIDE: THE APPLICATION CHECKS, LOADS AND FILLSCACHE-ASIDE: THE APPLICATION CHECKS, LOADS AND FILLSappRedisPostgreSQL1 GET menu:9miss2 SELECT3 SET menu:9 EX 300v = redis.get(k)if v is None: v = db.load(9) redis.set(k, v, ex=300)return vthe cache knows nothing about the database; the code does all the work
Figure 7.5Check, load, fill. The cache is a passive store and the application does everything.

The pattern’s strengths come from its simplicity. Only data that someone actually reads ends up in the cache, so memory holds the working set and nothing else. If Redis is down, the application can fall back to the database, slower but still correct. And the cache needs no knowledge of the database, so any store can sit behind it.

Its weaknesses are just as concrete. Every miss costs three steps, the failed GET, the load and the SET, so a cold cache is slower than no cache. Each piece of code that reads must remember the pattern, which is why teams wrap it in one helper. And there is a race. A reader misses and loads tip 20 from the database, but before it writes to Redis, a writer updates the tip to 30 and deletes the key. The reader’s delayed SET then puts 20 back into the cache, where it stays until the TTL expires.

THE CACHE-ASIDE RACE: A SLOW READER PUTS BACK THE OLD VALUETHE CACHE-ASIDE RACE: A SLOW READER PUTS BACK THE OLD VALUEreaderwriterRedis holdstimemissSELECT → tip 20SET tip 20UPDATE 30DEL(empty)tip 20 until TTLthe delete happened before the stale SET, so the old value lives for the whole TTL
Figure 7.6The delete came before the stale SET, so the old value survives for the whole TTL.

The race needs a slow reader and a write in a narrow window, so it is rare, and that is exactly what makes it dangerous, because it is nearly impossible to reproduce. Three defences exist. A short TTL bounds how long the stale value lives. Deleting on write is better than updating on write, because two concurrent updaters can write to the cache in the opposite order from the database. And for data where the race matters, Part IV shows versioned keys and leases that close the window entirely.

Why delete and not update? If the writer sets the new value in the cache, two writers that update the database in the order A then B might update the cache in the order B then A, leaving A’s older value cached. A delete has no ordering problem, since the next reader fetches whatever the database holds.

#Section 5Read-through and write-through

In read-through caching, the application talks only to the cache, and the cache knows how to load a miss itself. The application calls cache.get("menu:9"), and on a miss the cache library calls a loader function that queries the database, stores the result and returns it. Local cache libraries such as Caffeine and Guava work this way, and so does a CDN, which fetches from the origin on a miss without the client doing anything.

READ-THROUGH: THE CACHE ITSELF KNOWS HOW TO LOAD A MISSREAD-THROUGH: THE CACHE ITSELF KNOWS HOW TO LOAD A MISSappcache libraryloader(key)databaseget(k)on missthe app only ever talks to the cache; Caffeine, Guava and many CDNs work this way
Figure 7.7The loader lives inside the cache. The application never sees a miss.

The benefit is that loading logic lives in one place, so every caller gets the same behaviour, and the library can add features such as coalescing concurrent misses for the same key, which Part V shows is the cure for stampedes. The cost is coupling. The cache now depends on the database, and for a distributed cache like Redis there is no built-in loader, so read-through usually means a local library or a wrapper the team writes.

Write-through handles the other direction. Every write goes to both the cache and the database before the application acknowledges it. When restaurant 9’s owner changes the price of biryani, the service updates PostgreSQL and then sets the new menu in Redis, and only then replies. The cache is always warm for anything recently written, so the next read is a hit and never sees old data in the normal case.

WRITE-THROUGH: EVERY WRITE UPDATES THE CACHE AND THE DATABASE TOGETHERWRITE-THROUGH: EVERY WRITE UPDATES THE CACHE AND THE DATABASE TOGETHERappcachedatabasecache is always warmfor written keysevery write pays bothlatencies; rarely readkeys waste memorythe two writes are not atomic, so a failure between them still needs a TTL or a retry
Figure 7.8Both writes before the reply. Reads that follow are always hits.

Write-through has two costs. Every write pays both latencies. And it fills the cache with data that may never be read, which matters when writes are frequent and reads of the same data rare, such as Wren’s order status updates. The two writes are also not atomic. If the process dies after the database write and before the cache write, the cache holds the old value. Write-through therefore still needs a TTL as a safety net. In practice it is usually combined with read-through, so that the cache is filled on writes and on misses alike, and it fits data that is read soon after it is written, such as a user’s own profile after they edit it.

#Section 6Write-behind and write-around

Write-behind, also called write-back, acknowledges a write once it is in the cache and writes it to the database later, often in batches. Wren could use it for view counters. Each time someone views restaurant 9, the service increments a counter in Redis, and a job writes the totals to PostgreSQL every minute. Thousands of increments become one UPDATE per restaurant per minute.

WRITE-BEHIND: ACKNOWLEDGE FAST, FLUSH TO THE DATABASE LATERWRITE-BEHIND: ACKNOWLEDGE FAST, FLUSH TO THE DATABASE LATERappcachepending writesbatchdatabasecrash here loses everyunflushed write
Figure 7.9Writes pile up in the cache and flush in batches. A crash in between loses them.

Write-behind gives the fastest writes and absorbs bursts that would overwhelm the database. The cost is durability. Anything acknowledged but not yet flushed is lost if the cache crashes, so write-behind fits only data where small losses are acceptable, such as counters, analytics and presence. It also makes the database lag behind reality, so anyone reading the database directly sees old values. For orders, payments and anything a customer would notice, write-behind is the wrong choice.

Write-around writes only to the database and leaves the cache alone, apart from deleting the affected key. The next read misses and loads the new value. This is the write side of cache-aside and the right default when written data is not read immediately, so filling the cache would waste memory. Wren’s order status changes use write-around. The kitchen updates the status many times, and the customer’s app reads it every few seconds, so the cache is refilled by readers when they need it.

WRITE-AROUND: WRITE THE DATABASE, DELETE THE KEY, LET THE NEXT READ FILL ITWRITE-AROUND: WRITE THE DATABASE, DELETE THE KEY, LET THE NEXT READ FILL ITappcachedatabaseUPDATEDEL menu:9the usual write side ofcache-aside; good whenwritten data is rarelyread right away
Figure 7.10Write the database, delete the key, and let the next reader fill the cache.

Most real systems combine a read pattern and a write pattern per kind of data. Wren uses cache-aside with write-around for menus and orders, write-through for user profiles, and write-behind for view counters. The figure below sets the five side by side.

FIVE PATTERNS, SORTED BY WHO TALKS TO THE DATABASE AND WHENFIVE PATTERNS, SORTED BY WHO TALKS TO THE DATABASE AND WHENpatterntalks to the DBwhenwrites go tocache-asideappon missdelete on writeread-throughcacheon missanywrite-throughcache or appevery writeboth, nowwrite-behindcachelater, in batchescache firstwrite-aroundappevery writedatabase onlywrite-behind is the only one where an acknowledged write can be lost
Figure 7.11Who talks to the database and when. Write-behind alone can lose acknowledged writes.

The choice for each kind of data comes down to three questions. How soon after a write will it be read? How bad is a stale read? How bad is a lost write? Answer those and the pattern usually follows.