Sub topic 4
Cache-aside: the default read pattern
Prerequisites
This chapter assumes you can read basic Python and know how a client, a server, and a database exchange requests. It also assumes you know what a cache hit and a cache miss are, and that you understand latency, the time one request takes. Cache keys are covered in the previous chapter. Here, keys are plain strings such as user:42.
The working model
Cache-aside, also called lazy loading, puts the application in charge of the cache. The cache does not know about the database. The application talks to both.
On a read:
- The application looks up the key in the cache.
- On a hit, it returns the cached value.
- On a miss, it reads the value from the database, stores it in the cache, and returns it.
On a write, the application updates the database first and then removes the cached entry. The next read misses and loads the fresh value.
The cache fills only with data that someone has actually requested. This is the "lazy" part. Data nobody reads never takes up cache space.
A worked example
This code reads a user through an in-process dictionary. Each entry stores the value and an expiry time. A TTL (time to live) is the number of seconds an entry may be served before it counts as stale.
import time
cache = {} # key -> (value, expires_at)
TTL_SECONDS = 60
def get_user(user_id, db):
key = f"user:{user_id}"
entry = cache.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0] # cache hit
value = db.fetch_user(user_id) # cache miss: read from the source
cache[key] = (value, time.monotonic() + TTL_SECONDS)
return value
def update_user(user_id, data, db):
db.save_user(user_id, data)
cache.pop(f"user:{user_id}", None) # invalidate after the writePoints to notice:
get_usertreats an expired entry the same as a missing one. Both lead to a database read.time.monotonic()is used instead of the wall clock, so a system clock change cannot make entries live too long or expire early.update_userdeletes the entry instead of writing the new value into it. The reason is in the next section.
Why delete on write instead of updating
Two writers can race if each one updates the cache with its own value. Suppose writers A and B both change the same user.
- A writes to the database.
- B writes to the database.
- B writes its value to the cache.
- A writes its value to the cache.
The database now holds B's value and the cache holds A's. The cache stays wrong until the TTL expires. Deleting the key avoids this, because a delete does not carry a value that can be out of order. The next reader loads whatever the database holds at that moment.
The order also matters. Update the database first and delete second. If you delete first, a concurrent reader can miss, read the old row from the database, and put the old value back into the cache before your write lands.
Remaining race: a stale fill
Delete-after-write is not perfectly safe. This sequence can still happen:
- Reader R misses and reads the old value from the database.
- Writer W updates the database.
- W deletes the cache key.
- R stores the old value it read in step 1.
The cache now holds stale data. The window is small, because R must be slow between its read and its store while W completes both steps. It is real, though, and it is the reason to keep a TTL even when you invalidate on writes. The TTL puts an upper limit on how long such an entry can survive.
What cache-aside costs
| Aspect | Effect |
|---|---|
| First read of a key | Always a miss, so it is slower than having no cache, because it pays the cache lookup and the database read. |
| Application code | Every read path and every write path must include the cache logic. Forgetting one write path creates stale data. |
| Cache failure | The application can fall back to the database, so the cache is not a single point of failure. The database must be able to handle the extra load. |
| Memory use | Only requested data is cached. |
| Staleness | Bounded by invalidation on writes plus the TTL. |
The first row explains the cold start problem. After a deploy or a cache restart, the cache is empty and almost every read goes to the database. If the database was sized on the assumption that the cache absorbs 95% of reads, a cold cache can overload it. Plan for this with gradual traffic ramp-up or with pre-warming, which means loading known hot keys before serving traffic.
Common errors
Caching a missing result
If fetch_user returns None for an unknown user, the code above stores None. The next lookup finds an entry, but get_user returns the stored value, so the caller sees None without a database read. That is correct behavior and is called negative caching. It protects the database from repeated lookups of ids that do not exist. Give negative entries a shorter TTL, because the row may be created soon after.
The opposite mistake appears in code that tests if value: instead of checking whether the entry exists. A cached empty list or 0 is then treated as a miss, and the database is read every time. Compare against None or check for the key explicitly, as the example does with entry is not None.
Mutating cached objects
An in-process cache hands out the same object to every caller. If one caller modifies the returned dictionary, all later callers see the change, and the database does not. Return copies or immutable values.
Caching too much per key
Storing a whole object graph under one key means a change to any field invalidates everything. Cache what a reader needs, and keep the invalidation rule simple enough to describe in one sentence.
Unbounded growth
The dictionary in the example never removes expired entries unless the same key is read again. A long-running process that sees many distinct keys will grow without limit. Production caches pair TTLs with a size limit and an eviction policy, which a later chapter covers.
Thundering herds on popular keys
When a hot key expires, many requests miss at once and all hit the database. This is a cache stampede. Cache-aside has no built-in defense, so you add one. Per-key locking and early refresh are covered in the chapter on stampedes.
Cache-aside compared with other patterns
In cache-aside, the application code contains the load logic. In read-through caching, the cache itself loads missing data from the database, and the application only talks to the cache. The behavior on a hit is identical. The difference is where the miss-handling code lives, and that affects how many places you must keep correct.
Cache-aside is the default because it works with any cache and any database. A plain key-value store such as Redis or Memcached needs no special plugin. The application also controls exactly what is cached, how it is keyed, and what happens on errors. The price is that every caller must follow the pattern, which is why teams usually wrap it in one small data-access function.
When it fits
Cache-aside fits workloads that:
- read far more often than they write,
- tolerate data that is stale for up to the TTL,
- have a skewed access pattern, where a small set of keys receives most reads,
- need the system to keep working if the cache goes down.
It fits poorly when every read must see the latest write, or when writes dominate. In those cases most entries are invalidated before they are read again, and the cache adds cost without saving much.
Exercise
A service updates the database, then deletes the cache key. A slow reader that started before the update finishes after the delete and stores the old value. Why does this leave stale data in the cache, and what limits how long it stays?
Show answer
The reader read the old row from the database before the write, but it stored that value in the cache after the writer had already deleted the key. Nothing removes the entry afterward, so later readers get the old value. The entry's TTL limits the damage, because it expires after at most the TTL and the next read then loads the current row.
Exercise
Why should a cache-aside write path delete the cached entry instead of writing the new value into it?
Show answer
With concurrent writers, the database updates and the cache updates can happen in different orders, so the cache can end up holding the older value while the database holds the newer one. A delete carries no value, so the next read loads whatever the database currently holds.