How does the cache-aside pattern work?
The application checks the cache first. On a miss it reads the database, stores the result in the cache and returns it. On writes it updates the database and removes or updates the cache entry.
Explain it simply
Cache-aside, also called lazy loading, puts the application in charge of the cache. It is like keeping a notebook of answers on your desk: before walking to the library (the database), you check the notebook. If the answer is missing, you go to the library, copy the answer into the notebook, then reply.
Read path:
- Look up the key in the cache.
- Hit: return it.
- Miss: query the database, put the value in the cache with a TTL, return it.
Write path: update the database, then delete the cache key so the next read fetches fresh data. Deleting is safer than updating the cache because it avoids races between two writers.
Strengths: only data that is actually requested gets cached, and a cache outage does not break the app, it only slows it. Weakness: the first request for each key is slow, and stale data can appear until the TTL ends or the key is deleted.
Example
def get_user(uid):
user = cache.get(f"user:{uid}")
if user is not None:
return user # hit
user = db.query("SELECT * FROM users WHERE id=%s", uid)
cache.set(f"user:{uid}", user, ttl=300)
return user # miss path
def update_user(uid, data):
db.update(uid, data)
cache.delete(f"user:{uid}") # next read refillsWhat to say in the interview
"In cache-aside the app checks the cache, on a miss loads from the database and fills the cache with a TTL. On writes I update the database and invalidate the key. It is resilient to cache failure but needs TTLs and invalidation to limit stale reads."