Caching

Caching patterns

How cache-aside, read-through, write-through, write-behind and write-around work, how each one fails, and how to pick a read and a write strategy for a workload.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A shop’s product page runs one query that joins product, price, stock and review summary. It takes about 40 ms on PostgreSQL. At 200 requests a second that is 8 seconds of query time per second, which a 16-core machine handles comfortably.

Then a campaign takes traffic to 5,000 requests a second. That is 200 seconds of query time every second, which would need about 200 cores doing nothing else. The team adds read replicas, which helps in proportion to what they spend and brings replication lag. They check the indexes, which are already right. They buy a bigger primary.

Then someone looks at the access log. About 95% of those requests are for the same few hundred products, and the answer for each one changes a few times a day. The database is computing the same result thousands of times a second. Keeping that result in memory, keyed by product id, turns most reads into a lookup that takes under a millisecond.

That is the easy part. The hard part is the set of questions a cache raises. Who puts a value into the cache? Who changes it when the data changes? What does a reader see between those two moments? What happens when the cache is down? A caching pattern is one consistent set of answers. There are five worth knowing: two for the read path (cache-aside and read-through) and three for the write path (write-through, write-behind and write-around). A real design picks one of each.

Where caches sit on the path of one request5 components: Browser, CDN edge, App servers, Redis or Memcached, Database. Connections: Browser to CDN edge; CDN edge to App servers (on a miss); App servers to Redis or Memcached (look up first); App servers to Database (on a miss).BrowserHTTP cache, one userCDN edgeshared HTTP cacheApp serversin-process cacheRedis orMemcachedshared application cacheDatabasebuffer pool in memoryon a misslook up firston a miss
Where caches sit on the path of one request

This lesson is about the shared application cache in the middle of that picture. The same patterns appear at the other layers: a CDN is a read-through cache for HTTP, and the operating system’s page cache is a write-behind cache for the disk.

Cache-aside

In cache-aside (also called lazy loading or look-aside) the application owns all the logic.

  • Read. Ask the cache. On a hit, return. On a miss, read the database, store the result in the cache with a TTL, and return.
  • Write. Update the database, then delete the cache key.
Cache-aside read and write4 components: Client, App server, Cache, Database. Connections: Client to App server; App server to Cache (GET, SET, DEL); App server to Database (on a miss or write).ClientApp serverowns the caching logicCacheRedis, TTL 5 minemptyDatabasesource of truthGET, SET, DELon a miss or write

Step 1 of 8

In cache-aside the application does all the work. The cache and the database never talk to each other. The cache starts empty and only ever holds what some request has asked for.

Read the steps as text
  1. In cache-aside the application does all the work. The cache and the database never talk to each other. The cache starts empty and only ever holds what some request has asked for.
  2. A client asks for product 7. The app server asks the cache first. The key is not there, so the cache answers with a miss.
  3. On a miss the app reads the row from the database. This is the slow path, and it is the same query the app would have run with no cache at all.
  4. The app stores the result in the cache with a time to live of five minutes, then answers the client. A miss cost three round trips instead of one.
  5. The next read for product 7 is a hit. The cache answers in under a millisecond and the database is not involved. On a read-heavy page this is what almost every request looks like.
  6. Now the price changes. The app writes the new row to the database first, because the database is the source of truth.
  7. Then the app deletes the cache key. It does not write the new value. A delete gives the same result however concurrent writers are ordered, and no value is computed that nobody reads.
  8. The next read misses and loads the new price from the database, exactly as the first read did. Between the database write and the delete, readers could still see the old price, and that short gap is the price of this pattern.
Cache-aside read and write

What you get:

  • Only data that someone reads is cached, so memory goes to what is popular.
  • The cache is optional. If it is unreachable, reads fall back to the database. The service survives as long as the database can carry the load, which is the subject of Cache stampede and thundering herd.
  • The cached value can be any shape: a rendered fragment or a joined object, not a copy of a row.

What it costs:

  • A miss takes three round trips, so the first read of every key is slower than having no cache.
  • There is a window between the database write and the delete in which readers see the old value, and a rarer race that can leave a stale value in place until the TTL. Cache invalidation covers both.
  • Every service that touches the data has to implement the same logic correctly.

The paper “Scaling Memcache at Facebook” (2013) describes this pattern at very large scale: look-aside reads, and a delete sent to the cache after each database write.

Read-through

The read sequence is the same, but the cache layer does the loading. The application asks the cache and nothing else. On a miss the cache calls a loader, stores the result and returns it.

Caffeine’s LoadingCache does this inside a Java process. Amazon DAX does it as a service in front of DynamoDB. A CDN does it for HTTP.

The gain is that loading lives in one place. The cache can see that a load for a key is already running and make other callers wait for it, and it can refresh popular entries before they expire. The costs are that the cache must know how to reach the store, the cached value usually mirrors what the store returns, and the cache is now on the critical read path unless the client can bypass it.

Write-through

The application writes to the cache layer. The cache updates its own entry and writes to the database synchronously, and acknowledges only when both are done.

Reads that follow a write are hits and are current. That is the point of the pattern. The costs:

  • Every write pays for two writes.
  • Data is cached whether or not anyone reads it, so pair write-through with a TTL or an eviction policy.
  • The two writes are not atomic. If one fails, the layer has to undo or retry the other.

Write-behind

Write-behind (also called write-back) acknowledges as soon as the cache is updated. The cache queues the change and writes it to the database later, usually in batches, and often merging changes to the same key. A hundred increments of a counter become one UPDATE.

Write-through waits for the database, write-behind does not6 components: App, Cache, Database, App, Cache, Database. Connections: App to Cache (1. write); Cache to Database (2. write, then ack); App to Cache (1. write, ack at once); Cache to Database (2. flush in batches).Appwrite-throughCacheupdates itself and the DBDatabasealways currentAppwrite-behindCachequeues changed entriesDatabaseseconds behind1. write2. write, then ack1. write, ack at once2. flush in batches
Write-through waits for the database, write-behind does not

Writes are as fast as the cache, bursts are absorbed, and the database does far fewer writes. The price is durability:

  • If the cache node dies before it flushes, writes that were acknowledged are gone.
  • The database lags the cache, so reports, other services and anything else that reads the database directly see old data.
  • A flush can fail long after the user was told “saved”, for example on a constraint violation, and there is nobody left to tell.

Choose it for counters, view counts, last-seen timestamps and similar data where losing a few seconds is acceptable. Do not choose it for orders, payments or stock.

Write-around

The write goes to the database only. The cache is filled later by reads, as in cache-aside.

This suits data that is rarely read soon after it is written: logs, message archives, bulk imports. Writing those into the cache would push out entries that are being read. The cost is that a read just after a write is a miss. And if the key was already cached, it stays stale until its TTL unless the writer also deletes it. Add that delete and you have the usual cache-aside write path.

Choosing a pattern

Pattern Who writes to the database Main risk Choose it when
Cache-aside The app, directly Stale entry after a failed or raced delete Read-heavy data, and the cache must be allowed to fail
Read-through The app, directly (the cache only reads) The cache is a hard dependency for reads You want loading and coalescing in one place
Write-through The cache, synchronously Slower writes, cold data cached Reads must see a write at once
Write-behind The cache, later Acknowledged writes can be lost Very high write rate, small losses tolerable
Write-around The app, directly A miss or stale read after a write Written data is rarely read soon

The usual pairing is cache-aside reads with delete-on-write and a TTL. Read-through with write-through is common when a library or managed product provides both. Write-behind is a specialist tool.

When not to cache

A cache is a second system with its own failure modes, so it has to earn its place. The number to estimate is the hit ratio. With a 1 ms cache and a 40 ms database, a 90% hit ratio gives an average read of about 5 ms. A 50% hit ratio gives about 21 ms, and you now pay for both systems.

The database serves the misses, so its load follows the miss ratio. At 99% hits it sees 1% of reads. At 98% it sees twice as many.

Skip the cache, or cache something else, when:

  • the data is written more often than it is read,
  • almost every request asks for a different key, so entries are evicted before they are reused,
  • the decision needs the current value, such as a balance check or a stock decrement, which should read the source of truth,
  • the database is already fast enough and has headroom.

In the interview

Bring a cache in when your estimates show a read-heavy, skewed workload, not by reflex. Then be specific: name the key, the value, the TTL and the pattern. “Cache-aside in Redis, keyed by product id, five-minute TTL with jitter, delete on write” is a complete sentence an interviewer can probe.

Say what happens on a write and what a reader can see in the gap. Say what happens when the cache is down and whether the database survives it. If you choose write-behind, say out loud which writes you are prepared to lose. And if the data does not suit caching, say so. Declining to cache a balance is a stronger answer than caching everything.

Key takeaways

  • A caching pattern answers three questions. Who loads the cache, who updates it on a write, and what happens when the cache and the database disagree or one of them is down.
  • Cache-aside with a TTL and delete on write is the default, because the cache can fail without taking the application down.
  • Read-through moves loading into the cache layer, which gives one place for loader logic and request coalescing but puts the cache on the critical read path.
  • Write-through keeps the cache current at the cost of slower writes. Write-behind makes writes fast at the cost of losing acknowledged writes if the cache dies.
  • Write-around skips the cache on writes, which suits data that is rarely read soon after it is written.
  • Database load is set by the miss ratio, not the hit ratio: going from 99% to 98% hits doubles the reads the database sees.

Check yourself

1. A service uses cache-aside. The whole cache cluster becomes unreachable. What should happen if the pattern is implemented properly?
2. A team stores order records with write-behind. A cache node crashes. What is the most serious consequence?
3. A cache's hit ratio drops from 99% to 97% after a deploy. Roughly how does the read load on the database change?
4. Which workload is the best fit for write-around?
5. Why does read-through make stampede protection easier than cache-aside?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What are the steps of a cache-aside read and a cache-aside write?

Read: get from the cache, on a miss read the database, then set the cache with a TTL. Write: update the database, then delete the cache key.

Cache-aside versus read-through in one sentence.

In cache-aside the application loads the database and fills the cache. In read-through the application only asks the cache, and the cache calls a loader on a miss.

What is the main risk of write-behind (write-back)?

The write is acknowledged before it is durable. If the cache node dies before flushing, acknowledged writes are lost, and the database lags the cache in the meantime.

When is write-through worth its slower writes?

When data is read soon after it is written and readers must see the new value straight away, and when the cache layer (not ad hoc application code) orders the two writes.

What is write-around and when does it fit?

Writes go only to the database and the cache fills on reads. It fits data that is rarely read soon after being written, such as logs, archives and bulk imports.

When should you not add a cache?

When the data is written more often than read, when almost every request is for a different key, when the decision needs the current value (balances, stock), or when the database is already fast enough.

Review the deck