How to remove or refresh old data so users do not see stale answers.
Cache invalidation means making sure the cache does not keep serving old data after the real data has changed.
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.
| Layer | How it is invalidated |
|---|---|
| Browser | Cache-Control: max-age, ETag and Last-Modified checks; or new file names (app.3f9a.js) |
| CDN | TTL, plus a purge or invalidation request for a URL or tag |
| Redis or Memcached | TTL, explicit delete in your code, or a message from the database |
| App memory | TTL or a reload when a config change event arrives |
| Search index or materialised views | Rebuilt or updated when the source changes |
| Trick | What it does |
|---|---|
| Negative caching | Cache “not found” for a short time so missing items do not hit the database every time |
| Stale-while-revalidate | Serve 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 groups | Mark many keys with a tag and invalidate them all together (for example “product:9”) |
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.
| Term | Meaning in easy words |
|---|---|
| Invalidation | Removing or refreshing a cached item because the real data changed |
| Stale data | A cached value that no longer matches the source |
| TTL | Time to live: seconds until a cached item expires |
| Purge | Deleting one or more cached items on purpose |
| Versioned key | A key that includes a version number or hash |
| Cache busting | Changing a URL (for example a file name) so browsers fetch the new file |
| Stale-while-revalidate | Serve the old copy now and fetch a new one in the background |
| ETag | A label for a version of a file. The client asks “changed since this ETag?” |
| Negative caching | Caching “not found” answers |
| Eventual consistency | Caches will match the source after a short delay if nothing else changes |
| Jitter | A small random extra added to TTLs |
| Method | Freshness | Complexity | Weak spot |
|---|---|---|---|
| TTL only | Up to one TTL old | Very low | Stale until it expires |
| Purge on write | Fresh after the next read | Medium | A forgotten or failed delete |
| Update on write | Fresh at once | Medium | Two writers can leave the old value |
| Versioned keys | Fresh once the version is known | Medium | Version lookup must be right |
| Events | Fresh after a short delay | High | Lost, late or repeated events |