Search

Search papers and lessons

Cache-Aside Caching

Level 2 · 11 min read

In cache-aside caching the application checks a fast cache first, loads from the database on a miss, and removes the cached copy when the database changes.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Algorithms
  • Distributed systems
  • Networking
  • ReadReady to readNot yet

TL;DR

Cache-aside caching is a pattern in which the application, not the cache, decides what to store. To read a value, the application first looks in a fast cache. If the value is there, it returns it; if not, it reads the slower database, stores a copy in the cache, and returns that. To change a value, it writes the database and removes the cached copy, so the next read loads the new value. The cache stays small and only holds what people actually ask for.

Builds on: Memory Hierarchy, Key-Value Store · Leads to: Cache Eviction Policy, Database Transaction

Where it's used

Product and profile pages in web services. A shop page asks for the price of product 7 many times a second. The page reads price:7 from a key-value cache. Most reads hit the cache and never touch the database, which keeps the database free for writes and for requests the cache cannot answer. Large sites such as Facebook described their use of this pattern with memcache, in the paper Scaling Memcache at Facebook.

Session and user data. A login service stores a user's profile under user:1042 after the first read. Later requests in the same session come from memory, and the profile is evicted or expired when it has not been read for a while.

Expensive computed results. A report that takes two seconds to build can be stored under a key such as report:2026-11. The first viewer waits; later viewers read the stored result in a few milliseconds until it expires.

How it works

Take a tiny system: one database that holds the price of product 7 as 10, and one cache that starts empty. The application runs these steps.

  1. A customer loads the page. The application asks the cache for price:7. The cache has nothing under that key. This is a miss.
  2. The application reads price:7 from the database and gets 10.
  3. The application stores price:7 = 10 in the cache and returns 10 to the customer. Check: the cache now holds 10, and the database still holds 10.
  4. A second customer loads the page. The cache has price:7, which is 10. This is a hit, so the database is not read.
  5. The shop owner changes the price to 12. The application writes 12 to the database. Then it deletes price:7 from the cache. Check: the database says 12, and the cache has no value.
  6. A third customer loads the page. It misses, reads 12 from the database, stores it, and returns 12.

The rule that makes this work is in steps 3 and 5. Reads fill the cache, and writes remove from it. The application is the only place that knows both the database and the cache, which is why the pattern is called "aside": the cache sits to the side of the normal path.

flowchart TD
  R["Read price 7"] --> C{"In cache?"}
  C -->|"yes (hit)"| A["Return cached value"]
  C -->|"no (miss)"| D["Read database"]
  D --> S["Store in cache"]
  S --> A
  W["Write price 7"] --> DB["Write database"]
  DB --> X["Delete cache entry"]

The math

Let hh be the hit ratio, the fraction of reads found in the cache. Let tct_c be the time to check the cache and tdt_d the time to read the database. On a hit the cost is tct_c. On a miss the application checks the cache first and then reads the database, so the cost is tc+tdt_c + t_d. The average read time is a weighted average of the two costs, weighted by how often each happens:

T=h⋅tc+(1−h)(tc+td)T = h \cdot t_c + (1 - h)(t_c + t_d)

Expanding the brackets gives a simpler form,

T=tc+(1−h) tdT = t_c + (1 - h)\, t_d

This matches steps 2 and 4 of the walkthrough: hits skip the database term, and misses pay for it.

Checking the formula on the price example

With tc=1t_c = 1 ms and td=20t_d = 20 ms, a hit ratio of h=0.9h = 0.9 gives T=1+(1−0.9)⋅20=1+2=3T = 1 + (1 - 0.9) \cdot 20 = 1 + 2 = 3 ms. Without a cache every read would take 2020 ms, so the cache cuts the average from 20 ms to 3 ms.

Why the writes need a delete

Let xx be the stored value, xdbx_\text{db} the value in the database, and xcachex_\text{cache} the value in the cache. A correct state satisfies xcache=xdbx_\text{cache} = x_\text{db} whenever the cache has the key. A write that changes xdbx_\text{db} breaks this equality, and deleting the cache key restores it, because the next read misses and copies the new xdbx_\text{db} into the cache.

Worked examples

Example
1. Tiny: one key, four reads and a write

The database holds price:7 = 10. The cache starts empty. Track each request.

  1. Read 1: cache empty, so a miss. The database returns 10. The cache stores 10. The customer sees 10.
  2. Read 2: the cache has 10, so a hit. The customer sees 10. The database was not read.
  3. Read 3: a hit again, 10.
  4. Write: the database is set to 12, then the cache entry for price:7 is deleted.
  5. Read 4: the cache is empty, so a miss. The database returns 12. The cache stores 12. The customer sees 12.

Of the four reads, two were hits (reads 2 and 3). Read 1 was a miss that loaded the cache, and read 4 was a miss forced by the write. The hit ratio over the four reads is 2/4=0.52/4 = 0.5.

Example
2. Standard: average read time at three hit ratios

Use tc=1t_c = 1 ms and td=20t_d = 20 ms, the same numbers as before, with T=tc+(1−h) tdT = t_c + (1 - h)\, t_d.

  1. At h=0.5h = 0.5: 1−0.5=0.51 - 0.5 = 0.5, then 0.5⋅20=100.5 \cdot 20 = 10, so T=1+10=11T = 1 + 10 = 11 ms.
  2. At h=0.9h = 0.9: 1−0.9=0.11 - 0.9 = 0.1, then 0.1⋅20=20.1 \cdot 20 = 2, so T=1+2=3T = 1 + 2 = 3 ms.
  3. At h=0.99h = 0.99: 1−0.99=0.011 - 0.99 = 0.01, then 0.01⋅20=0.20.01 \cdot 20 = 0.2, so T=1+0.2=1.2T = 1 + 0.2 = 1.2 ms.
  4. The gain from 0.9 to 0.99 is 1.8 ms, while the gain from 0.5 to 0.9 is 8 ms. Each extra point of hit ratio helps less than the one before, because the average is already close to the cache time.

The lesson is that raising the hit ratio matters most when it is low, and a cache that misses half the time is far slower than one that misses a tenth of the time.

Example
3. Realistic: a stale read caused by a race

A web service caches user profiles with cache-aside and a time limit (time to live, TTL) of 60 seconds on each cached entry. Two requests run at nearly the same time, which is a race: request R reads a profile, and request W updates it.

  1. R misses the cache for user:1042 and reads the old profile from the database. The old profile has email [email protected].
  2. W writes the new email [email protected] to the database.
  3. W deletes user:1042 from the cache. The cache was already empty, so nothing is removed.
  4. R, which read the old profile in step 1, now stores [email protected] in the cache.
  5. Every later read of user:1042 hits the cache and gets the old email. The database has the new one.
  6. The entry expires after its TTL of 60 seconds. The next read misses, reads the database, and stores the new email.

So a stale value can survive for as long as the TTL allows, even though the delete was correct. Systems that cannot accept this add a short TTL, or delete the key a second time after a short delay.

Try it: a profile cache uses a TTL of 60 seconds. A stale value is stored at time 0 seconds, and then the database changes at time 5 seconds, with no delete reaching the cache. For how many seconds after that database change can readers still get the stale value, if no further writes happen? Answer: 55 seconds. The entry was stored at time 0 with a 60-second TTL, so it expires at time 60 seconds. Readers can see the old value from time 5 until time 60, which is 55 seconds.

Common mistakes and tradeoffs

It is tempting to think that writing the new value into the cache is better than deleting it. In fact, two writers can race and leave the cache with the older value, while a delete makes the next reader load whatever the database holds. Deleting is the usual choice, although it costs one extra miss.

It is tempting to think that a cache with cache-aside is always consistent with the database. In fact there is a window between the database write and the cache delete, and a race can leave a stale entry that lasts until it expires. The pattern gives eventual consistency, not a guarantee that every read is current. Transactions inside the database do not cover the cache, because the cache is outside them.

It is tempting to cache everything. In fact each cached item uses memory and must be invalidated on every write, so caching data that changes often and is rarely read wastes both. Cache Eviction Policy decides what to drop when memory is full, and it matters most when the cache is much smaller than the working set.

It is tempting to think a miss on a popular key is harmless. In fact, when a hot entry expires, many requests can miss at once and all hit the database together. Common fixes are a lock so that only one request reloads the value, or refreshing popular entries before they expire.

When to use it: reads far outnumber writes, slightly stale data is acceptable for a while, and the data can be rebuilt from the database. When not to use it: the data must be correct at every read, such as account balances, or the cache must be the only copy of the data. Alternatives are write-through caching, where writes go to the cache and the database together, and a cache kept in step by the database itself.

History

Caches predate web software. The Memory Hierarchy of computers has used small fast memories in front of large slow ones since the 1960s, and programs run quickly when they reuse nearby data. Web software needed the same idea when database load grew faster than the hardware that served it. In the early 2000s, memcached was written for a large blogging site and became a common way to put a key-value cache in front of a database. The cache-aside pattern, in which the application fills and clears the cache itself, became the standard arrangement because it works with any database and needs no special support from either side. The 2013 paper Scaling Memcache at Facebook described how a very large deployment ran this pattern across many distributed servers and regions, which made the approach widely known.

Recap

  • In cache-aside, the application reads the cache first, loads the database on a miss, and fills the cache with what it loaded.
  • On a write, the application updates the database and deletes the cached copy, so the next read reloads it.
  • The average read time is T=tc+(1−h) tdT = t_c + (1 - h)\, t_d, so a higher hit ratio hh cuts the average sharply when hh is already high.
  • A race between readers and writers can leave a stale value until its time to live runs out. Limit that window with a short TTL.
  • Read next: Cache Eviction Policy for choosing what to drop when the cache is full, and Database Transaction for what the database itself guarantees.

Check yourself

QuestionIn cache-aside, what does the application do on a read miss, and what does it do on a write?Show answer
On a read miss it reads the database, stores the value in the cache, and returns it. On a write it updates the database and then deletes the cached copy, so a later read reloads the new value.
QuestionA cache has a hit ratio of 0.75. The cache check takes 2 ms and the database read takes 40 ms. What is the average read time?Show answer
Use T=tc+(1−h)tdT = t_c + (1 - h) t_d. 1−0.75=0.251 - 0.75 = 0.25, and 0.25⋅40=100.25 \cdot 40 = 10. So T=2+10=12T = 2 + 10 = 12 ms.
QuestionWhy does deleting the cached entry on a write work better than writing the new value into the cache?Show answer
A delete makes the next reader load whatever the database holds, so a delete never leaves a value that was copied in earlier. Writing the new value into the cache can race with another writer or with a reader holding an old value, and then the older value can be left in the cache.
QuestionA team says their cache-aside cache is always consistent with the database because they delete the key on every write. Explain why this is not quite true.Show answer
Between the database write and the cache delete there is a window, and a reader that read the old value before the write can store it in the cache after the delete. The stale entry then lasts until it expires. The guarantee is eventual, not that every read is current.
QuestionA product page is read 1000 times for every write. Should it use cache-aside, and what would you check first?Show answer
Probably yes, because reads far outnumber writes and each write only has to delete one key. Check first whether slightly stale prices are acceptable for the time-to-live period, and whether a popular key could cause many simultaneous misses when it expires.

Sources