Cache invalidation and stale data
40 min · Intermediate
Cache invalidation means removing or replacing a cached copy when the original data changes. It sounds like one line of code, but with two stores, many servers and requests running at the same time, it is where most caching bugs live.
Topics in this lesson
- Why invalidation is hard
- Delete the entry, do not update it
- A stale price on the category page
- Cache stampede and its fixes
- How stale is acceptable?
Key points
- The database is the source of truth; stale data appears when the cache and database are updated separately.
- On update: write the database first, then delete the cache entry; deleting is safe in any order, updating is not.
- Delete every derived key that shows the changed row (category pages, home deals), or give those pages a short TTL.
- Stop stampedes with one loader per key or early refresh, and set a staleness budget per data type.
Interview questions this lesson answers
- Why is cache invalidation considered hard?
- On an update, do you update the cache or delete the entry? Why?
- Is delete-after-write fully safe?
- What is a cache stampede and how do you prevent it?
- A price changed but users still see the old price on the category page. How do you debug it?
- How do you decide how stale data can be?
- What happens if the cache delete fails after a successful database update?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.