Cache-aside
easy 22 minWith 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
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
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.
2009
Redis is first released in February. It is often used in the same way.
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.
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.
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
One read
- 1
A read request arrives
The application is asked for a key such as
user:123. - 2
Look in the cache
If the value is there, return it. Finished.
- 3
On a miss, read the database
The application runs the query itself.
- 4
Store the result
Put it in the cache with an expiry time.
- 5
Return the data
The caller does not know whether it was a hit.
Reading
A hit and a miss
Miss, then hit
What the caller waits for
| Case | Trips | Time (assumed) |
|---|---|---|
| Hit | look | 1 ms |
| Miss | look, read, fill | 1 + 10 + 1 = 12 ms |
| Miss, fill in the background | look, read | 11 ms |
| No cache | read | 10 ms |
When is it worth it?
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 dataWriting
Change the database, delete the copy
A save on one server, a read on another
One update
- 1
Update the database
Commit first. The database is the truth.
- 2
Delete the cache key
Now nobody can read the old copy from the cache.
- 3
Wait for the next read
It misses, and fills the cache with the new value.
Why not set the new value?
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
| Guard | How | Cost |
|---|---|---|
| Short TTL | The wrong value ends by itself | More misses |
| Lease | The fill needs a token; a delete cancels it | Support in the cache layer |
| Version | Store the row version, refuse an older one | A compare on every fill |
| Second delete | Delete again a second later | A delayed job; a guess at the timing |
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
- 1
Short timeouts
Wait perhaps 50 ms for the cache, then treat it as a miss.
- 2
A limit on misses
Let only as many reads through as the database can serve.
- 3
Spread expiry times
Add a little randomness so keys do not end together. See cache TTL.
- 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
SCANin small steps for maintenance jobs - Let old versions expire by TTL
Avoid
KEYSwith 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
| Data | Why it fits | Watch out |
|---|---|---|
| User profiles | Read often, changed rarely | Delete on every kind of change |
| Product catalogue | Many readers, same rows | Prices: short TTL, exact at checkout |
| Configuration | Tiny and stable | Version in the key |
| Session data kept in a database | Read on every request | Delete on logout, and do not trust an old copy for permissions |
| Anything read far more than written | Hits pay for the misses | Measure 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.