AlgoViz

Cache-aside

easy 22 min

With cache-aside, also called lazy loading, the application looks in the cache first, reads the database on a miss and stores a copy for next time.

Video lesson · Chapter 1 of 5

The second request takes a shorter route

0:00 / 3:50

Cache-aside

1:17Reel

Theory

Read or listen first. About 2 min.

What it is

Cache-aside is a way to use a cache in which the application does all the work. The cache sits to the side of the database. The two never talk to each other.

To read, the application asks the cache. If the value is there, it is done. If not, it reads the database, stores a copy in the cache with an expiry time, and returns the value. To change something, it writes the database and then deletes the copy.

It is also called lazy loading, because nothing is cached before somebody asks for it, and look-aside caching.

Why it exists

Most data is never read again soon. Loading copies only on demand keeps the cache small and useful.

Because the application can always read the database, a broken cache makes things slow instead of wrong. That makes it the usual first choice. The price is that every place that reads or writes the data has to follow the same steps.

A short history

  1. 2003

    Memcached is released in May. It is a plain key and value store, so applications decide what to put in and what to remove.

  2. 2009

    Redis is first released in February. It is often used in the same way.

  3. 2013

    Facebook engineers describe memcache as a demand-filled look-aside cache at USENIX NSDI, explain why they delete instead of update, and add leases against stale sets.

Words to know

Lazy loading
A copy is made only when someone asks for the value.
Look-aside
Another name: the application looks at the side before it goes to the database.
Fill
Storing a value after a miss.
Invalidate
Delete the copy because the original changed.
Stale set
A slow reader stores an old value after the delete.
Negative entry
A short note in the cache that says: this does not exist.
Cold start
The time when the cache is empty and nearly everything misses.

How it works

Step through the idea, or press Play.

Step 1 of 3

Look. Ask the cache first

Understand it

Start here

The spice rack

A chef keeps big jars in a storeroom and a small rack above the stove. Nobody fills the rack in advance. It fills up with what the cooking needs.

A rack that fills itself
STOREROOMcuminsaltmintchilisagecloveSPICE RACKThe rack starts empty

The idea

Four things that define it

  • The application is in charge

    Your code looks, reads, fills and deletes. The cache does nothing on its own.

  • Filled on demand

    A value is cached when somebody asks for it, not before.

  • Made for reads

    It pays off when the same values are read many times between changes.

  • A little stale

    For a moment after a change, a reader can get the old copy.

The whole picture

Who talks to whom

The cache and the database never meet

A reader asks the app for user 123. The app looks in Redis first, on a miss reads the database, and then keeps a copy in Redis. Redis and the database are not connected.
Solid arrows happen on every read. Dashed arrows happen only on a miss.

One read

  1. 1

    A read request arrives

    The application is asked for a key such as user:123.

  2. 2

    Look in the cache

    If the value is there, return it. Finished.

  3. 3

    On a miss, read the database

    The application runs the query itself.

  4. 4

    Store the result

    Put it in the cache with an expiry time.

  5. 5

    Return the data

    The caller does not know whether it was a hit.

Reading

A hit and a miss

Miss, then hit

Assumed: 1 ms for a cache trip, 10 ms for the query.

What the caller waits for

CaseTripsTime (assumed)
Hitlook1 ms
Misslook, read, fill1 + 10 + 1 = 12 ms
Miss, fill in the backgroundlook, read11 ms
No cacheread10 ms
Real numbers vary. A cache call in the same data centre is often around 1 to 5 ms with its network trip; a heavy query can take 50 to 200 ms, and then a hit saves far more.

When is it worth it?

h⋅1+(1−h)⋅12<10;⇒;12−11h<10;⇒;h>211≈18%h \cdot 1 + (1 - h) \cdot 12 < 10 ;\Rightarrow; 12 - 11h < 10 ;\Rightarrow; h > \tfrac{2}{11} \approx 18\%
With these numbers the average read gets faster once more than 18% of reads are hits. Below that the cache only adds work.
Text
function getData(key):    data = cache.get(key)    if data is not null:        return data                 // hit    data = database.query(key)      // miss    if data is not null:        cache.set(key, data, TTL)    return data
The whole read path.

Writing

Change the database, delete the copy

A save on one server, a read on another

An editor saves through app server 1, which updates the database and then deletes the key in Redis. A reader on app server 2 then misses in Redis and reads the fresh row from the database.
Because Redis is shared, a delete by server 1 is seen by server 2.

One update

  1. 1

    Update the database

    Commit first. The database is the truth.

  2. 2

    Delete the cache key

    Now nobody can read the old copy from the cache.

  3. 3

    Wait for the next read

    It misses, and fills the cache with the new value.

Why not set the new value?

Two sets can arrive in the wrong order. Two deletes cannot do harm in any order, and a repeated delete changes nothing.

Races

The stale set that remains

Deleting last is safer but not perfect. A reader that missed before the change can be slow, and store the old value after the delete.

A slow reader

What to do about it

GuardHowCost
Short TTLThe wrong value ends by itselfMore misses
LeaseThe fill needs a token; a delete cancels itSupport in the cache layer
VersionStore the row version, refuse an older oneA compare on every fill
Second deleteDelete again a second laterA delayed job; a guess at the timing
Cache consistency compares these in detail.

Missing things

Keys that do not exist

When the database has no row, nothing is stored, so every request for that key is a miss. A wrong link or a guessing robot can turn that into real load. Store a small marker with a short expiry, for example 30 seconds, and delete it when the row is created.

What to do with the result

Failure

When the cache is empty or down

The application can always read the database. That is the strength of the pattern, and also its trap: the database suddenly gets all reads.

The load that comes back

3,000/s reads×(1−0.95)=150/s,cache gone: 3,000/s=20×150/s3{,}000/s\ \text{reads} \times (1 - 0.95) = 150/s, \qquad \text{cache gone: } 3{,}000/s = 20 \times 150/s
At 95% hits the database serves 150 reads a second. Without the cache it gets twenty times as many.
  1. 1

    Short timeouts

    Wait perhaps 50 ms for the cache, then treat it as a miss.

  2. 2

    A limit on misses

    Let only as many reads through as the database can serve.

  3. 3

    Spread expiry times

    Add a little randomness so keys do not end together. See cache TTL.

  4. 4

    One refresher per hot key

    Others wait or get the old copy. See thundering herd.

Keys

Deleting many keys at once

Sometimes one change affects many keys, such as every page of a list. It is tempting to search for keys by pattern. The Redis documentation warns against its KEYS command in application code, because it walks the whole keyspace.

Do

  • Put a version number in the key and raise it on a change
  • Keep a set with the names of related keys
  • Use SCAN in small steps for maintenance jobs
  • Let old versions expire by TTL

Avoid

  • KEYS with a pattern in a request
  • Clearing the whole cache for one change
  • Guessing all key names in code
  • Keys without any expiry

Trade-offs

Strengths and weaknesses

Strengths

  • Only requested data is cached
  • Can fall back to the database when the cache fails
  • Simple to build and to explain
  • Works with any database
  • Very good for read-heavy data

Weaknesses

  • The first request for a key is slow: three trips
  • Copies can be stale for a while
  • Every reader and writer must follow the steps
  • A popular key can cause a stampede
  • Little help when most requests are writes

When to use it

Where it fits

DataWhy it fitsWatch out
User profilesRead often, changed rarelyDelete on every kind of change
Product catalogueMany readers, same rowsPrices: short TTL, exact at checkout
ConfigurationTiny and stableVersion in the key
Session data kept in a databaseRead on every requestDelete on logout, and do not trust an old copy for permissions
Anything read far more than writtenHits pay for the missesMeasure the hit rate

The other ways to keep a cache and a database in step are write-through and write-back. Choosing a cache pattern compares all three.

Summary

The whole topic in one minute.

Cache-aside is three steps on a read: look, fall back, fill. On a change it is two: write the database, delete the copy. The application owns all of them.

Give every copy an expiry time, retry lost deletes, and limit the database reads when the cache is empty or down. Use it for read-heavy data that may be a little old.

  • Read: look, fall back, fill with a TTL.
  • Change: write the database, then delete the key.
  • Delete instead of set, because deletes can be repeated and reordered.
  • A stale set is rare but possible. A TTL limits it, a lease or version prevents it.
  • Plan for an empty cache: short timeouts and a limit on database reads.

Sources