What are lazy loading and write-through caching strategies?
Lazy loading fills the cache only when a read misses, then stores the result. Write-through updates the cache at the same time as the database on every write, so reads are rarely stale but the cache holds data that may never be read.
Explain it simply
Lazy loading is a shopkeeper who stocks an item only after the first customer asks for it. The first customer waits, later ones get it quickly. Write-through is a shopkeeper who puts every new item on the shelf the minute stock arrives, so nothing is slow, but he fills shelves with items nobody buys.
Example
Lazy loading (cache-aside)
read(key):
value = cache.get(key)
if value is missing: # cache miss
value = db.read(key)
cache.set(key, value, ttl=300)
return value
+ only requested data is cached
- first read is slow; data can go stale until TTL expires
Write-through
write(key, value):
db.write(key, value)
cache.set(key, value)
+ cache is always current
- extra write cost, cache fills with unread dataMany systems combine both: write-through for hot data and lazy loading with a time-to-live (TTL) for everything else. A TTL limits staleness and stops the cache from growing without bound.
Cache failures should not break the app: if the cache is down, fall back to the database.
What to say in the interview
"Lazy loading caches on a miss, which keeps the cache lean but can serve stale data until the TTL ends. Write-through updates the cache on each write so it stays fresh, at the cost of extra writes. I usually combine them and always set a TTL."
Common mistakes
- Caching without any expiry or invalidation plan.