Sub topic 4
Cache-aside: the default read pattern
This chapter assumes you know basic Python, how an application talks to a database, and what hit ratio means from the cache fundamentals chapter.
How cache-aside works
In cache-aside (also called lazy loading), the application code manages the cache. The cache never talks to the database. On a read, the application does the following:
- It looks the key up in the cache.
- On a hit, it returns the cached value.
- On a miss, it reads from the database, stores the result in the cache, and returns it.
Data enters the cache only when something asks for it. Rarely requested data never takes up space, and a cache failure doesn't stop reads, because the application can fall back to the database.
A working example
The code below keeps the cache in a dictionary. Each entry stores its value and an expiry time. FakeDB is a stand-in so you can run the example.
import time
cache = {} # key -> (value, expires_at)
TTL_SECONDS = 60
class FakeDB:
def __init__(self):
self.users = {1: {"name": "Ada"}}
self.reads = 0
def fetch_user(self, user_id):
self.reads += 1
return self.users.get(user_id)
def save_user(self, user_id, data):
self.users[user_id] = data
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 write
db = FakeDB()
get_user(1, db)
get_user(1, db)
print(db.reads) # 1: the second call was a hit
update_user(1, {"name": "Grace"}, db)
print(get_user(1, db)["name"], db.reads) # Grace 2time.monotonic() is used for expiry because it never jumps backward when the system clock changes.
Writes: delete, don't update
On a write, update the database first and then delete the cached key. The next read repopulates it from the database. Deleting is safer than overwriting the cache with the new value. If two writers race, their cache updates can land in a different order than their database updates, which leaves a wrong value cached until the TTL expires. A delete is idempotent, so it has no such ordering problem.
Common errors
- Caching a miss as a value. The example stores
Nonewhen the user doesn't exist. That is deliberate, since it stops repeated database reads for missing rows. Use a short TTL for these entries so a newly created row appears quickly. - Skipping the TTL. Without an expiry, a missed invalidation leaves stale data in the cache forever. The TTL bounds the damage.
- Stale reads in a race. A reader can fetch the old row, a writer can then update the database and delete the key, and the reader can then store the old row in the cache. The TTL limits how long this lasts. It cannot be fully prevented without extra machinery.
- Stampedes. When a popular key expires, many requests miss at once and all hit the database. A later chapter covers mitigations.
Exercise
A user changes their email. Your code runs save_user, then cache.pop. Why is this order better than deleting the cache key first and then saving to the database?
Show answer
If you delete the key first, a concurrent reader can miss, read the old row from the database, and put it back into the cache before your write finishes. That stale value then stays until the TTL expires. Writing the database first means any reader that repopulates the cache after the delete sees the new data.