How do you keep a cache consistent with the database?
BackendSenior
In shortPick a pattern per use case (cache-aside with TTLs is the default), invalidate or update on writes, and design for the failure cases: races between readers and writers, stampedes on expiry, and stale data during outages. Accept bounded staleness where you can; where you can't, don't cache or use versioned keys.
Model answer
Patterns:
- Cache-aside (lazy loading): read from cache; on a miss, read the database and populate. On writes, update the database, then delete the key (not update it). The default for most read-heavy data.
- Write-through: writes go to cache and database together; reads are always warm, writes are slower.
- Write-behind: writes go to cache and are flushed later; fast, but risks losing data.
Races to know: with cache-aside, a slow reader can read the old row, a writer updates and deletes the key, and the reader then writes the old value back. Mitigations: short TTLs, delete after commit (and optionally a second delayed delete), or versioned keys (user:42:v17) where the version comes from the row.
Safety nets:
- TTL on everything, with jitter, so mistakes heal.
- Stampede protection: request coalescing (one loader per key), early probabilistic refresh, or serving stale while refreshing.
- Event-driven invalidation: publish change events (from the outbox or CDC) that delete keys in every service and region.
When not to cache: data that must be read-your-writes consistent for correctness (balances, inventory decisions) should come from the source, or the cache must be updated transactionally with it. Measure the hit rate; a cache with a low hit rate only adds a failure mode.
What they're looking for
Cache-aside, write-through and write-behind trade-offs, the delete-after-write rule and its race, TTLs as a safety net, stampede protection, versioned keys, event-driven invalidation, and knowing when not to cache.
Common mistakes
- Updating the cache before the database commit.
- No TTL, so a missed invalidation lasts forever.
- Caching data that must be strongly consistent, like balances.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior