Invalidate the cache when data changes
A record is updated or deleted but the cache keeps serving the old value until its TTL runs out.
Say it like this
I invalidate by deleting the cached key on every write and keep a short TTL as the safety net, so the next read always loads the current row.
Basic solution
On every write, delete (not update) the cache key for that record, then let the next read repopulate it. Add a short TTL as a safety net and version the key when the shape changes.
Delete on write, then reload on read
The write commits to the database and then deletes the cached key. A later read misses once, reloads the current row and repopulates with a TTL.
How it works
- The service writes the new row to the database inside a transaction and waits for the commit to succeed. Until this point the cache still holds the old value and that is fine.
- Right after the commit it sends DEL key for every cache entry that was built from that row: the record itself (post:123) and any cached list or page that embeds it, such as a cached search result that includes the post text.
- The next read for that key misses, runs the normal database query, gets the fresh row and writes it back into the cache with a TTL. So one read pays a database round trip and everyone after it hits.
- Every entry carries a TTL anyway, so if a delete is ever lost (the process crashed between commit and DEL) the stale entry disappears on its own within minutes rather than living forever.
- When the shape of the cached value changes (a new field, a different serialisation), the code bumps a version number inside the key, for example user:v3:42. Old entries under user:v2:42 are simply never read again and age out by TTL, so no mass invalidation is needed.
Why delete and not set
- Two writers updating the same row can finish in the opposite order to their cache SETs, leaving the cache holding the older value. Two DELs cannot leave anything wrong: the next read loads whatever is in the database.
- Setting writes values into the cache that nobody may read again; deleting spends cache memory only on keys that are actually read.
Worked example
News feed post edit
- A user edits a post that is already in 10K follower timelines. The timelines cache post ids only; bodies live in a post cache keyed by post id.
- On edit: UPDATE posts ... then DEL post:123. One delete, not 10K, because the timelines store ids and hydrate bodies at read time.
- Next feed read: ZREVRANGE on the timeline (hit), MGET post bodies, one miss on post:123, one database read, SET post:123 EX 600.
- Cost of the write: 1 DB write + 1 DEL. Cost of the stale window: the time between the DB commit and the DEL, a few ms.
- TTL 10 min with 10% jitter means a lost DEL (worker crashed between commit and DEL) shows stale data for at most ~11 min.
Variants and when each wins
Delete on write (cache-aside invalidation)
- The application deletes the cache key immediately after the database commit, and the next read reloads it. It is simple and correct enough for most products, and it is the default to reach for.
Write-through update
- The application sets the new value into the cache in the same request as the database write. It wins when a read right after the write must hit, but two concurrent writers can set values in the wrong order, and the cache fills with keys nobody reads.
Event-driven invalidation (CDC)
- A connector reads the database change log and deletes or updates cache keys for every row change. It wins once several services write the same tables or when a manual SQL fix must also clear the cache, because it does not depend on application code remembering to delete; the cost is one more moving part to run.
TTL only
- No invalidation at all: data is stale for at most one TTL. It wins for values where minutes of staleness do not matter, such as counts and rankings, and fails for anything a user expects to see change immediately.
Recommendation: delete on write plus a short jittered TTL; add CDC-driven invalidation once several services write the same tables.
Failure modes
Stale read after a write
- You notice a user saves a change, refreshes, and still sees the old value. It happens because of a race on the read side: request A misses the cache, reads the old row, and is slow; meanwhile the write commits and deletes the key; then A finishes and sets the old row into the cache. Fix it with a short TTL so the entry self-heals, and by routing reads for a few seconds after a write to the database instead of the cache.
Lost invalidation
- You notice one record stays stale until its TTL runs out, while others update fine. It happens because the application crashed or the cache call failed in the gap between the database commit and the DEL. Fix it by retrying the DEL with backoff, or by moving invalidation to a change data capture consumer that reads the database log and can replay anything it missed.
Over-invalidation
- You notice the cache hit rate drops after every write. It happens because whole cached pages or lists are deleted whenever any single item in them changes. Fix it by caching lists of ids separately from the item bodies, so editing one item invalidates one body and the list stays cached.
Thundering herd on a hot key
- You notice a brief database spike every time a very popular key is deleted. It happens because that key is read thousands of times per second, so the moment it disappears every reader misses at once. Fix it by letting one reader reload while the rest wait (single-flight), or, for the handful of keys this hot, set the new value instead of deleting.
Schema change
- You notice deserialisation errors right after a deploy. It happens because the new code reads cache entries that were written in the old shape. Fix it by putting a version in the key prefix so new code reads only entries it wrote, and never reading entries written by a different version.
Interviewer follow-ups
Answer out loud before you open each one.
Which should happen first, the database write or the cache delete?
Database first, then delete. If you delete first, a concurrent read can miss, reload the old row and set it before your write commits, leaving stale data until TTL. With database first the stale window is only the few milliseconds between commit and delete.
How do you invalidate when a write comes from a service that does not know about the cache?
Move invalidation out of the application and into a change data capture consumer that watches the database log. Every row change, from any writer including a manual fix, emits an event the consumer turns into cache deletes.
What TTL do you pick if you invalidate properly anyway?
Still set one, a few minutes, because it bounds the damage from any missed or failed delete. Add jitter so a bulk write does not create a wave of expiries all at once.
How would you invalidate CDN-cached content, which you cannot DEL?
Prefer versioned URLs so you never need to: a new file hash is a new URL and the old one can live forever. For content that must keep its URL, use the CDN purge API or surrogate keys, and accept that purges take seconds to propagate.
Connections
- In study paths
- Scaling reads
- Pairs with
- Cache the hot reads · React to database changes · Let users see their own writes · Let browsers and proxies cache
- Pulls against
- Keep cache and store in sync on write
- Used in
- URL Shortener (TinyURL / bit.ly) · News Feed (Twitter / X timeline) · Distributed Key-Value Cache (Redis / Memcached-like)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Database | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon ElastiCache | Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |