Q&A-1Explain the cache-aside pattern and one downside of it.
Answer
Cache-aside (lazy loading) puts the application in charge of the cache. On a read, the app asks the cache first; on a miss it goes to the database, then writes the value back to the cache with a TTL. Writes go to the database directly, and the app either invalidates the cache key or lets the TTL absorb the change. The database remains the source of truth, and the cache is disposable: you can flush it and nothing is lost except latency.
# Redis 7.x, redis-py 5.x — cache-aside read path
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached is not None:
return json.loads(cached) # hit: ~0.5 ms
row = db.execute(
"SELECT * FROM users WHERE id = %s", (user_id,)
).fetchone() # miss: ~15 ms
redis.set(key, json.dumps(row), ex=300) # 5-minute TTL
return rowThe downside worth explaining: the inconsistency window. Because the cache is populated lazily and expires on a timer, the cache can serve stale data even after a write has committed. Two distinct mechanisms produce this:
- TTL staleness. A write updates the database but the cached copy isn't touched. Until the TTL lapses or the key is explicitly invalidated, every read returns the old value. With a 5-minute TTL, a user can update their profile and see the old version for up to five minutes. If you invalidate on write, you shrink the window to milliseconds, but you don't eliminate it.
- Read-then-write race. Two concurrent misses both read the database; between the read and the
SET, a writer commits a newer value; the stale reader then overwrites the cache with the old value. Now the cache is wrong for the entire TTL even though you invalidated on write. Mitigations: short TTLs as a backstop, or delete-on-write plus a versioned write to the cache (e.g., a Lua script that only sets if the version is newer).
The failure mode that actually pages people: the expiry stampede. A hot key expires and 500 concurrent requests all miss simultaneously, all hit the database, and all try to repopulate the cache. At 10,000 QPS with a 90% hit rate the database sees 1,000 QPS; if a top key expires and 20% of traffic lands on it, that's 2,000 extra queries in the ~15 ms it takes the first one to repopulate: enough to saturate a connection pool and turn a cache miss into a full outage. Fixes: request coalescing (a single-flight lock so one request fetches and the rest wait), probabilistic early expiration (repopulate slightly before the TTL at random offsets), or a mutex per key (SET key:lock 1 NX EX 1).
When cache-aside is the wrong choice.
| Pattern | Write path | Staleness | Best for |
|---|---|---|---|
| Cache-aside | DB only; cache filled on read | Up to TTL after write | Read-heavy, tolerant of slight staleness |
| Write-through | DB and cache together | Near-zero on writes | Read-after-write consistency required |
| Write-behind | Cache first, DB async | DB can lag; data loss risk | Very high write throughput, loss-tolerant |
If users must read their own writes (profile updates, config changes, balance after a payment) cache-aside with a long TTL will produce bug reports. Write-through costs you write latency (every write pays the cache round trip) but closes the window. Write-behind is faster still but the database lags, and a cache node dying before the flush loses committed-looking writes.
Cache-aside earns its place when reads dominate, stale-for-seconds is acceptable, and you want the cache to be a pure optimization: turn it off and the system still works, just slower. That degradation property is the real reason it's the default at most shops, but it's also why the stampede scenario needs to be designed for, not discovered in production.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.