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.
See it run
The application runs the cache: look, fall back, fill, and delete on a change.
Operations
Read user:123 twice
Ten steps: a request that misses and fills the cache, then the next request that hits.
Step 1 of 10
1. A read request
Hits
0
Misses
0
The app is asked for the key user:123.
Step 1: 1. A read request
def get(key): value = cache.get(key) # 1 look if value is not None: return value # hit value = db.read(key) # 2 miss: read if value is not None: cache.set(key, value, ttl=300) # 3 keep return value- Caller waits
- 12 ms, then 1 ms
- Trips
- 3 trips, then 1
- Database only
- 10 ms every time (assumed)
A miss costs three trips: look, read, fill. That is slower than having no cache, and it is worth it because of the hits.
In the real world
The same cache-aside doing real jobs. Pick one and step through it.
One profile, read 2,000 times and changed once.
Step 1 of 4
Morning
Hits
0
Misses
1
The first read misses. The TTL is long, so the copy stays.
Step 1: Morning
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Setting the new value on update
majorTwo updates can reach Redis in the opposite order from the database. The older value then stays.
Wrongdb.write(key, value)cache.set(key, value)Rightdb.write(key, value)cache.delete(key)Removing many keys with KEYS
criticalKEYS walks the whole keyspace in one go and blocks everyone. The Redis documentation says not to use it in application code.
Wrongfor k in redis.keys("user:42:*"): redis.delete(k)Right# a version in the key: old keys simply expireversion = redis.incr("user:42:version")key = f"user:42:v{version}:profile"Treating a cached empty value as a miss
minorAn empty list, 0 and an empty string are real answers. A truth test sends them to the database every time.
Wrongif cached: return cachedRightif cached is not None: return cachedLetting a cache error reach the user
majorThe database could have answered. Cache-aside only survives a cache failure if you catch it.
Wrongvalue = cache.get(key) # raises, request failsRighttry: value = cache.get(key)except CacheDown: value = None # treat as a miss
Interview tips
How to explain it
- The app looks in the cache, then in the database, then fills the cache.
- The cache and the database never talk to each other.
- On a change: write the database, delete the key.
Memory trick: LAZY
- Look in the cache first.
- Ask the database on a miss.
- Zap the key on updates.
- Yield to the next read to fill it.
Reach for it when
- Reads far outnumber writes.
- A few seconds of stale data is fine.
- The app must live through a cache failure.
Move on when
- The value must be exact on every read.
- Almost every read follows a write.
- Writes are the bottleneck.