How do you keep a cache consistent with the database?
Perfect consistency is not achievable without giving up caching; aim for bounded staleness and correct behavior.
Practical rules:
- On write, commit to the database first, then delete the cache key. Deleting is safer than updating because concurrent writers can otherwise interleave stale values.
- Use a TTL as a backstop so any missed invalidation self-heals.
- For read-modify-write races, use a short delay before the second delete (double delete) or a versioned key so stale writes cannot overwrite newer data.
- Consider write-through when reads must immediately reflect writes.
- For cross-service data, publish change events and let interested caches evict.
1. UPDATE db
2. DEL cache:user:42
3. next read repopulates from db
A known race: reader misses, reads old DB value, writer updates DB and deletes cache, then the reader writes its stale value. Versioned keys or delayed double delete mitigate it. Document the accepted staleness window and test under concurrency.