Cache Eviction, Write Policies and Invalidation
How caches decide what to drop, how writes reach them, and how to keep them fresh.
What is it?
A cache is small and fast; the data behind it is big and slow. That raises three questions every cache design must answer:
1. What do we throw out when the cache is full? That's the eviction policy: LRU, LFU, FIFO, or expiry by TTL. 2. How do reads and writes flow between app, cache and database? That's the caching pattern: cache-aside, read-through, write-through, write-back or write-around. 3. How do we stop serving stale data after the source changes? That's invalidation.
Getting these right decides whether the cache actually helps (high hit rate, fresh enough data) or quietly serves wrong answers.
Explain like I'm 10
Your desk holds only a few books; the library holds all of them. LRU means returning the book you haven't opened longest. LFU means returning the one you open least often. TTL means every book goes back after two weeks no matter what. Invalidation is the librarian telling you a new edition is out, so the copy on your desk is wrong.
Examples
An LRU cache in a few lines
// A JS Map remembers insertion order, so the first key is the oldest.
class LruCache {
constructor(capacity) {
this.capacity = capacity;
this.entries = new Map();
}
get(key) {
if (!this.entries.has(key)) return undefined;
const value = this.entries.get(key);
this.entries.delete(key); // move to the "most recent" end
this.entries.set(key, value);
return value;
}
set(key, value) {
this.entries.delete(key);
this.entries.set(key, value);
if (this.entries.size > this.capacity) {
const oldestKey = this.entries.keys().next().value;
this.entries.delete(oldestKey); // evict least recently used
}
}
}Every access moves a key to the end, so the front is always the least recently used. Classic implementations use a hash map plus a doubly linked list for the same O(1) behavior.
Cache-aside read and write
async function getProduct(id) {
const cached = await cache.get("product:" + id);
if (cached) return JSON.parse(cached); // hit
const product = await db.findProduct(id); // miss: load from source
await cache.set("product:" + id, JSON.stringify(product), { ttlSeconds: 300 });
return product;
}
async function updateProduct(id, changes) {
await db.updateProduct(id, changes); // 1. write the source of truth
await cache.delete("product:" + id); // 2. invalidate, don't update
}The app owns the logic. On writes, deleting the key (instead of writing the new value) avoids two concurrent writers leaving an older value in the cache; the TTL is a safety net for any invalidation that's missed.
How it works
Eviction policies
- LRU (least recently used): evict what was touched longest ago. Good default for workloads where recent items are likely reused. - LFU (least frequently used): evict what's accessed least often. Keeps long-term popular items, but needs counters that decay so yesterday's hit doesn't stay forever. - FIFO: evict the oldest inserted item, regardless of use. Simple, usually a worse hit rate. - TTL: each entry expires after a set time. Not really about space; it bounds staleness. Usually combined with LRU or LFU.
Real systems approximate: Redis samples a few keys and evicts the best candidate instead of keeping an exact LRU list, and its default policy, noeviction, rejects writes when memory is full, so set one explicitly (allkeys-lru, allkeys-lfu, volatile-ttl and others).
Read/write patterns
- Cache-aside (lazy loading): the app checks the cache, and on a miss reads the database and fills the cache. Most common. - Read-through: the cache library itself loads from the database on a miss. - Write-through: writes go to the cache and the database synchronously. Cache stays warm and consistent; writes are slower. - Write-back (write-behind): writes go to the cache and are flushed to the database later, in batches. Very fast writes, but data is lost if the cache dies before flushing. - Write-around: writes go only to the database; the cache fills on later reads. Avoids filling the cache with data that's written but rarely read.
Invalidation strategies: TTL expiry, explicit delete on write, event-driven invalidation (listen to database change events and delete keys), and versioned keys (product:42:v7) so a new version simply uses a new key.
Cache-aside read Write-through Write-back
App -> Cache (miss) App -> Cache App -> Cache (ack)
App -> DB Cache -> DB (sync) ...later...
App -> Cache (fill) ack after both Cache -> DB (batch flush)
Write-around Invalidation on write
App -> DB App -> DB (update)
(cache untouched; next App -> Cache (delete key)
read misses and fills) next read reloads fresh valueWhy does it exist?
Memory is limited and expensive compared to disk, so a cache can hold only a fraction of the data. Eviction policies keep the most useful fraction. And because the cache is a copy, every design has to choose where to trade write speed, durability and freshness, which is what the write patterns and invalidation strategies encode.
When to use it
- LRU as a default; LFU when a stable set of popular items should survive bursts of one-off reads (a scan shouldn't flush the hot set). - Cache-aside for general read-heavy data; write-through when reads right after writes must hit the cache; write-back for very write-heavy data that can tolerate some loss (counters, metrics); write-around for data written once and rarely read soon after (logs, uploads). - Short TTLs when you can't reliably invalidate; explicit invalidation when staleness is visible to users.
When not to use it
Avoid write-back for data you can't afford to lose (payments, orders) unless the cache itself is durable and replicated. Don't cache data that must be strongly consistent on every read, such as an account balance used to approve a withdrawal. And don't pick LFU for workloads where popularity shifts quickly unless its counters decay.
Common mistakes
Updating the cache on write instead of deleting it, so two racing writers can leave the older value cached indefinitely.
Leaving Redis on its default noeviction policy, so writes start failing when memory fills up.
Using no TTL at all, so any missed invalidation means stale data forever.
Giving every key the same TTL, so many keys expire together and stampede the database.
Choosing write-back for critical data without understanding that a cache crash loses unflushed writes.
Practice exercises
- Easy:
With capacity 3, trace an LRU cache through accesses A, B, C, A, D, B, E. Which key is evicted at each step?
- Medium:
Implement an LFU cache with O(1) get and set. Explain how you break ties between keys with the same frequency.
- Hard:
A product page cache sometimes shows an old price for hours after an update. List every way that can happen with cache-aside, and design an invalidation scheme that fixes it.
Interview questions
What's the difference between LRU and LFU?
LRU evicts the item accessed longest ago; LFU evicts the item accessed least often. LRU adapts quickly to changing patterns; LFU protects consistently popular items but can hold stale favorites unless frequency counts decay.
How do you build an LRU cache with O(1) get and put?
A hash map from key to node in a doubly linked list ordered by recency. On access, move the node to the head; on insert past capacity, remove the tail node and its map entry. Both operations are O(1).
Explain cache-aside.
The application checks the cache first. On a miss it reads the database, stores the result in the cache (usually with a TTL), and returns it. On writes it updates the database and deletes the cache key. The cache holds only data that's actually requested.
Write-through vs write-back?
Write-through writes to the cache and database synchronously, so the cache is always current but writes are slower. Write-back acknowledges after writing the cache and flushes to the database later, giving fast writes at the risk of losing data if the cache fails before flushing.
When is write-around a good choice?
When data is written but unlikely to be read soon, such as logs or bulk imports. Writing only to the database keeps those writes from evicting genuinely hot entries.
Why delete the cache key on update instead of setting the new value?
With two concurrent writers, the cache sets can land in a different order than the database writes, leaving an older value cached. Deleting makes the next read load the current value. A small race still exists (a slow reader can refill with stale data), so keep a TTL as a backstop.
What is cache stampede and how do you prevent it?
Many requests miss the same key at once (often right after it expires) and all hit the database. Prevent it with request coalescing or a lock so one request refills, jittered TTLs, and serving stale data while refreshing in the background.
How does Redis implement LRU?
Approximately: instead of maintaining a full recency list, it samples a small number of keys (configurable with maxmemory-samples) and evicts the best candidate among them. Its LFU mode uses a small probabilistic counter that decays over time.
How would you invalidate a cache across many services when a row changes?
Publish change events, ideally from the database's change log via CDC so no write path is missed, and have a consumer delete the affected keys. Combine with TTLs as a safety net, and use versioned keys for objects where you can bump a version on every change.
Is a perfectly consistent cache possible?
Not cheaply. Without coordinating the database write and the cache update in one transaction, there are always windows where they disagree. In practice you bound staleness (TTLs, prompt invalidation) and skip the cache for reads that truly must be current.