SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Caching Basics

Cache Invalidation

How to remove or refresh old data so users do not see stale answers.

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Cache invalidation means making sure the cache does not keep serving old data after the real data has changed.

  • The main tools are TTL (expire after a time), purge on write (delete the key), update on write and versioned keys.
  • Every tool is a trade-off between freshness, speed and complexity.
  • A famous joke says the two hard things in computer science are cache invalidation and naming things.

02Concept: What is it?

A cached copy is a photo of the data. When the real data changes, the photo is old. Stale data is a cached value that no longer matches the source. Invalidation is how we remove or refresh the old photo.

The problem
✏️Price changed₹100 → ₹120
→↓database updated
🗄️Database₹120
⇢⇣cache not told
⚡Cache₹100 (old!)
→↓
👤User sees ₹100
Nobody told the cache that the price changed, so users still see the old price.

The main ways to invalidate

⏳TTL expiry
Each item dies after N seconds. Easy. Stale until then.
🗑️Purge / delete on write
When data changes, delete the cached key. Next read loads fresh data.
🔄Update on write
When data changes, also write the new value into the cache.
🏷️Versioned keys
A new version means a new key (price:v2). Old keys are never read again.
📣Event-based
The database or service publishes a “changed” event, and caches listen and delete.
🧹Manual purge
An admin or deploy clears keys or a whole CDN path.

03Real-Life Example

🍵The menu board
A restaurant prints its menu on a big board outside. The kitchen changes a price. If nobody fixes the board, customers still see the old price.
Restaurant
Cache invalidation
Board shows “fresh every morning”
TTL: everything expires on a timer
Kitchen tells a boy to take the board down when a price changes
Purge on write
Kitchen tells him to rewrite the price on the board
Update on write
Print a new board each time with “Menu v2” and ignore the old one
Versioned keys
Kitchen forgets to tell the boy
A missed invalidation: stale data
Customers who saw the old board earlier still remember the old price
Browser and CDN copies you cannot reach

04Why Do We Need It?

🧾Correct data
A wrong price or stock count can cost money or trust.
🔐Security
Removed permissions or a deleted post must stop being served.
📰Fresh content
News and live scores should not be hours old.
⚖️A good balance
We want the speed of a cache and the truth of the database.
Caching makes things fast. Invalidation keeps them right.

05Where Do We Use It?

LayerHow it is invalidated
BrowserCache-Control: max-age, ETag and Last-Modified checks; or new file names (app.3f9a.js)
CDNTTL, plus a purge or invalidation request for a URL or tag
Redis or MemcachedTTL, explicit delete in your code, or a message from the database
App memoryTTL or a reload when a config change event arrives
Search index or materialised viewsRebuilt or updated when the source changes

06Types / Parts / How It Works

1. TTL (time to live)

  • How: set an expiry time when saving, like 60 seconds.
  • Good: simple. A built-in safety net. No code needed on writes.
  • Bad: data can be stale for up to the whole TTL. Short TTL = more misses. Long TTL = older data.
  • Tip: add a little random jitter to TTLs so many keys do not expire together (see Cache Stampede).

2. Purge (delete) on write

  • How: after updating the database, delete the cached key.
  • Good: fresh after the next read. Safe against writer ordering problems.
  • Bad: the write path must know every key to delete. If the delete fails or is forgotten, data is stale until the TTL.

3. Update (write-through) on write

  • How: write the new value to the database and the cache.
  • Good: the cache is fresh at once.
  • Bad: two writers can leave the cache with the older value. Needs care, or a lock or version check.

4. Versioned (or tagged) keys

  • How: put a version in the key, such as product:9:v7. A change bumps the version. The app reads the current version from a small source.
  • Good: no deleting needed. Old and new never mix. Great for files (app.3f9a.js) and CDNs.
  • Bad: the “current version” itself must be correct and cached carefully. Old keys waste memory until they expire.

5. Event-based invalidation

  • How: when data changes, publish an event (for example via a message queue or database change stream). Every cache listens and deletes the key.
  • Good: works across many services and caches.
  • Bad: events can be late, lost or repeated. Keep a TTL as a backup.
Event-based invalidation
🗄️Databasechanges
→↓event
📬Message queue
→↓
⚡Cache A: delete key
⚡Cache B: delete key
🌍CDN: purge URL
One change, many caches told. Keep a TTL in case a message is lost.

Other useful tricks

TrickWhat it does
Negative cachingCache “not found” for a short time so missing items do not hit the database every time
Stale-while-revalidateServe the old value at once and refresh it in the background
Conditional requests (ETag)Ask “has this changed?” and get a tiny 304 reply if not
Tags or groupsMark many keys with a tag and invalidate them all together (for example “product:9”)
VisualizerChange the data and watch the cachePick a way to invalidate. Change the database, let the simulated clock run, and read. Compare how stale each one is.
How do we keep the cache correct?
TTL (time to live): every cached copy expires after a set number of seconds. Simple. But users can see old data until it expires.
👤Reader
↔
⚡Cacheholds version 1 · expires in 10 s
↔
🗄️Databaseversion 1
✔ Cache matches the database
Clock
0 s
simulated
Time stale
0 s
cache ≠ database
Stale reads
0/0
The cache and the database both hold version 1.

Try it: change the database, then press “A user reads” a few times. “Do nothing” stays stale forever. TTL is stale until the timer ends. Update, purge and versioned keys are never stale for long. Their risks (a missed update, a race between two writers) are explained above.

07How to Use It / Steps / Implementation

A sensible recipe

  1. 1
    Decide how stale is OK
    A news list can be 1 minute old. A bank balance should not be cached that way.
  2. 2
    Set a TTL on everything
    It is the safety net that repairs mistakes.
  3. 3
    Delete the key after you update the database
    Do it in this order: database first, cache second.
  4. 4
    Use versions for files and big objects
    Change the name when the content changes.
  5. 5
    Use events for many caches
    A queue or change stream tells every cache to delete the key.
  6. 6
    Monitor
    Track how often users get stale data and how fast invalidation reaches every cache.
⚠️Order matters
If you delete the cache first and then update the database, a reader can load the OLD value in between and save it back. Update the database, then delete the cache.

Choosing

Need data to be fresh
  • Purge or update on write
  • Event-based invalidation
  • Short TTL as a backup
Can live with some staleness
  • Longer TTL
  • Stale-while-revalidate
  • Versioned keys for files

08Key Terms to Know

TermMeaning in easy words
InvalidationRemoving or refreshing a cached item because the real data changed
Stale dataA cached value that no longer matches the source
TTLTime to live: seconds until a cached item expires
PurgeDeleting one or more cached items on purpose
Versioned keyA key that includes a version number or hash
Cache bustingChanging a URL (for example a file name) so browsers fetch the new file
Stale-while-revalidateServe the old copy now and fetch a new one in the background
ETagA label for a version of a file. The client asks “changed since this ETag?”
Negative cachingCaching “not found” answers
Eventual consistencyCaches will match the source after a short delay if nothing else changes
JitterA small random extra added to TTLs

09Pros, Cons and Trade-offs

✅ Pros
  • Users see correct, fresh data
  • Mixed tools let you balance speed and freshness
  • TTL gives a free safety net
  • Events scale to many caches
⚠️ Cons
  • Hard to get right in every layer
  • Extra code on every write path
  • Events can be late or lost
  • Short TTLs reduce the cache's benefit
  • Browser and CDN copies are hard to reach

Trade-offs

MethodFreshnessComplexityWeak spot
TTL onlyUp to one TTL oldVery lowStale until it expires
Purge on writeFresh after the next readMediumA forgotten or failed delete
Update on writeFresh at onceMediumTwo writers can leave the old value
Versioned keysFresh once the version is knownMediumVersion lookup must be right
EventsFresh after a short delayHighLost, late or repeated events

10Common Problems and Mistakes

Common mistakes

  1. No TTL and no invalidation. Wrong data lives for ever.
  2. Deleting the cache before updating the database. A reader can put the old value straight back.
  3. Forgetting related keys. You delete the product but not the list page and the search result that contain it.
  4. Invalidating only one cache layer. The CDN and the browser still serve the old copy.
  5. Trusting events completely. Messages can be lost. Keep a TTL.
  6. Invalidating everything at once. A full flush means a cold cache and a database stampede.

Typical problems

🏁Races
Reader and writer overlap, and an old value is saved after the delete.
🕸️Dependent data
One change affects many cached views.
🌍Copies you cannot reach
Browsers and ISPs may keep old files for the whole max-age.
🐘Stampede after a purge
A popular key is deleted, and many requests rebuild it together.

11Real-World Examples

📦Web builds
Build tools put a hash in file names (app.3f9a.js). A new build means a new name, so browsers fetch the new file.
🌍CDNs
Offer purge by URL, path or tag, plus TTLs from Cache-Control headers.
🛒Shopping sites
Prices and stock use short TTLs or purge on change. Images use long TTLs with versioned names.
📰News sites
Stale-while-revalidate keeps pages fast while updates arrive in the background.
🔔Microservices
A service publishes “user changed” and other services drop their cached copy.
⚙️Feature flags and config
Short TTLs or change events so a switch takes effect quickly.
📝Note
These are general ideas. The exact set-up inside each company is more complex.
Mini timeline: a price change with purge on write
  1. 1
    Admin changes the price in the database
    ₹100 → ₹120
  2. 2
    The code deletes the cached key
    product:9
  3. 3
    The next user asks for the product: cache miss
    The app reads ₹120 from the database
  4. 4
    The app saves ₹120 in the cache with a TTL
  5. 5
    Later users get ₹120 from the cache

12Related Topics to Read Next

What is Caching?→

The basics: hits, misses and why caches work.

Caching Strategies→

Write policies decide what the cache and database do on a write.

Cache Eviction Policies→

Removing items because the cache is full.

CDN→

Caches spread across the world and how to purge them.

Cache Stampede→

What can go wrong right after a key is purged or expires.

Pub/Sub→

A good way to tell many caches that data changed.

CAP Theorem→

The bigger idea behind stale reads when data lives in many places.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Problem: the data changes, the cache still holds the old copy (stale).
  • ✔Tools: TTL, purge on write, update on write, versioned keys, events.
  • ✔Default: TTL on everything, plus delete the key after the database update.
  • ✔Order: database first, cache second.
  • ✔Delete, do not update, when two writers can overlap.
  • ✔Files: put a hash or version in the name (cache busting).
  • ✔Many caches: use events, and keep a TTL as a backup.
  • ✔One line: “Caching makes it fast; invalidation keeps it right. Always keep a TTL.”
← Previous
Cache Eviction Policies
Next →
HTTP Caching (Cache-Control, ETag)