Summary#
Two different problems keep a cache useful. Eviction decides what to throw out when the cache is full: LRU (least recently used, the common default), LFU (least frequently used), FIFO, random, or TTL-based expiry; modern caches use W-TinyLFU for higher hit ratios. Invalidation removes entries that are wrong because the source data changed: by TTL, explicit delete on write, versioned keys, or event-driven deletes from the database's change log (CDC). Races between the cache and the database can leave stale data, so write the database first, delete rather than update the cache, and keep TTLs as a safety net. As the saying goes, cache invalidation is one of the two hard things in computer science.
Why It Exists#
A cache has limited memory, but the dataset is usually much bigger, so something must leave when new data arrives. A good eviction policy keeps the entries most likely to be requested again, which directly sets the hit ratio. Separately, the moment data changes in the database, every cached copy is potentially wrong. Users then see old prices, deleted posts or outdated permissions. Invalidation is how you bound or remove that staleness. This page builds on Caching Strategies.
How It Works#
Eviction policies#
| Policy | Evicts | Strength | Weakness | Used in |
|---|---|---|---|---|
| LRU | Entry not accessed for the longest time | Simple, adapts to recency | A one-off scan of many keys flushes hot data | Memcached (segmented LRU), many in-process caches |
| LFU | Entry with the fewest accesses | Keeps long-term popular items | Slow to adapt when popularity changes; needs counters with decay | Redis allkeys-lfu |
| FIFO | Oldest inserted entry | Trivial, no per-access bookkeeping | Ignores popularity | Simple buffers, some CDN tiers |
| Random | A random entry | No bookkeeping, surprisingly decent | Can evict hot items | Redis allkeys-random, hardware caches |
| TTL-based | Entries whose TTL expired (or nearest to expiry) | Bounds staleness | Not a size policy by itself | Redis volatile-ttl, all caches with TTL |
LRU is usually implemented with a hash map plus a doubly linked list: every access moves the entry to the front; eviction removes from the back. Both are O(1). Exact LRU costs extra memory per entry, so Redis uses approximated LRU: it samples a few keys (5 by default) and evicts the least recently used among them, which is close to true LRU for much less memory.
LFU keeps an access counter per entry. To adapt to change, counters must decay over time; otherwise yesterday's viral item stays forever. Redis's LFU uses a logarithmic 8-bit counter with configurable decay.
Redis eviction settings (maxmemory-policy): noeviction (writes fail when full; right for Redis as a primary store), allkeys-lru, allkeys-lfu, allkeys-random, and volatile-* variants that only evict keys with a TTL. For a pure cache, allkeys-lru or allkeys-lfu is the usual choice.
# redis.conf for a pure cache
maxmemory 24gb
maxmemory-policy allkeys-lfu
maxmemory-samples 10 # more samples, closer to exact policyEviction policies, in depth#
What eviction really optimises. Every eviction is a bet about the future: "this entry is the least likely to be requested again before the others." A policy is good when its bets match the workload's actual reuse pattern. Two signals carry most of the information: recency (how long since the last access) and frequency (how often the key has been accessed). LRU uses only recency, LFU only frequency, and modern policies blend both and add an admission decision, which asks whether a new item deserves a place at all.
LRU and its hidden cost. The textbook LRU (hash map plus doubly linked list) is O(1), but every read modifies the list, because the entry moves to the head. In a multi-threaded cache that means a lock or an atomic update on every hit, which becomes a bottleneck at millions of operations per second. Production systems work around it in three ways:
- CLOCK (second chance). Entries sit in a circular buffer with one "referenced" bit each. A hit only sets the bit, with no list movement. The eviction "hand" sweeps the buffer: if the bit is set it clears it and moves on, if it is clear the entry is evicted. CLOCK approximates LRU closely and is what operating systems use for page replacement.
- Sampled LRU. Redis stores a 24-bit last-access timestamp in each object. When it needs memory, it samples
maxmemory-sampleskeys (5 by default), keeps the best candidates in a small eviction pool of 16 entries, and evicts the oldest. Raising samples to 10 gets very close to true LRU at a little extra CPU. - Buffered updates. Caffeine records reads in lock-free ring buffers and applies them to the policy structures in batches, so hits do not contend on a lock.
LRU's weakness: scans and one-hit wonders. Suppose an LRU cache holds 1 million entries with a 95% hit ratio, and a nightly report scans 5 million keys once each through the same cache. Every scanned key enters at the head, and after the first million the entire hot set has been pushed out. The next morning starts at a hit ratio close to zero, and the database takes the full load until the hot set reloads. The same happens more quietly with "one-hit wonders", keys requested once and never again, which are common in CDN and web workloads. A large share of objects in CDN traces are requested only once, and plain LRU gives each of them a full trip through the cache.
Memcached's segmented LRU and slab classes. Memcached allocates memory in slab classes, each holding items of a similar size range (for example 96 bytes, 120 bytes, 152 bytes, growing by a factor of 1.25). Eviction happens within a slab class, not globally. If your workload shifts from small items to large ones, the large-item class can be starved while the small one holds stale memory, a problem called slab calcification. Modern Memcached runs a slab rebalancer (automove) that moves pages between classes, and splits each class's LRU into hot, warm and cold segments. New items enter hot, items hit twice move to warm, and eviction takes from cold, which gives scan resistance. A background LRU crawler also reclaims expired items proactively.
LFU in practice: counters that decay. Exact LFU needs a full counter per key and never forgets. Redis's LFU stores an 8-bit logarithmic counter per key, a probabilistic (Morris-style) counter that increments with decreasing probability as it grows, so 255 levels can represent up to about a million accesses at the default lfu-log-factor of 10. The counter decays by one for every lfu-decay-time minutes (default 1) that the key is not accessed, so yesterday's viral item gradually loses its protection. New keys start with a counter of 5 rather than 0, otherwise every newly inserted key would be the immediate eviction candidate and nothing new could stay in the cache.
FIFO is back. FIFO ignores hits completely, which sounds bad, but it is cheap and scales well because hits change no metadata. Recent research showed that FIFO plus a little extra logic beats LRU on many real traces:
- S3-FIFO (Yang and colleagues, SOSP 2023, "FIFO queues are all you need for cache eviction") uses three FIFO queues: a small queue (about 10% of space) for new items, a main queue (about 90%) and a "ghost" queue that remembers recently evicted keys without their values. New items enter the small queue. Items evicted from it without a second access are dropped quickly, which handles one-hit wonders. Items accessed again move to main, and items in the ghost queue go straight to main when they return.
- SIEVE (Zhang and colleagues, NSDI 2024) keeps one FIFO queue with a visited bit and a moving hand that evicts unvisited items and leaves visited ones in place, a simpler cousin of CLOCK that also demotes new items quickly.
The common lesson is "lazy promotion, quick demotion": do not spend work reordering on every hit, and get rid of new items fast unless they prove themselves.
Random eviction. Evicting a random entry needs no metadata at all. On skewed workloads it performs worse than LRU, but not by as much as you would expect, because hot keys are few and a random pick usually lands on a cold one. "Sample k, evict the worst of them", as Redis does, interpolates between random (k = 1) and the exact policy (k large). This is the same "power of choices" idea used in load balancing.
TTL expiry mechanics. Expired keys are not freed the instant they expire. Redis combines lazy expiry (a key is checked and deleted when accessed) with an active expiry cycle that runs about 10 times a second, samples 20 keys with TTLs, deletes the expired ones and repeats immediately if more than 25% were expired. Memcached also expires lazily and uses its LRU crawler to reclaim dead items. The practical consequence: a burst of keys expiring together still occupies memory for a while, and volatile-ttl eviction can pick keys that are about to expire anyway, which is a cheap way to make room.
W-TinyLFU (briefly)#
W-TinyLFU, used by the Java library Caffeine, combines the strengths of recency and frequency:
- A small window LRU (about 1% of capacity) admits new entries, so bursts of new items get a chance.
- A compact frequency sketch (Count-Min sketch, a few bytes per entry, with periodic halving to age counts) estimates how often each key has been seen.
- When an entry would move from the window into the main area, it competes with the main area's eviction candidate; the one with the higher estimated frequency stays (admission policy).
The result is near-optimal hit ratios across many workloads, resistance to scans, and small memory overhead. Similar ideas (admission filters to keep "one-hit wonders" out) appear in CDN caches. See Probabilistic Data Structures.
W-TinyLFU, in depth#
The paper. TinyLFU was introduced by Gil Einziger, Roy Friedman and Ben Manes ("TinyLFU: A Highly Efficient Cache Admission Policy", ACM Transactions on Storage, 2017). Ben Manes built it into Caffeine, the standard in-process cache for Java, and its design has since been adopted by caches in other languages, such as Ristretto in Go.
The key idea: admission, not just eviction. Classic policies always admit a new item and only decide what to evict. TinyLFU asks a different question at each insertion: is the newcomer likely to be more popular than the item it would replace? If not, the newcomer is dropped and the cache keeps its current contents. This single decision makes the cache immune to scans and one-hit wonders, because a key seen once can never beat an established key seen many times.
How it estimates frequency cheaply. Storing an exact counter for every key ever seen would cost more than the cache. TinyLFU uses a Count-Min sketch: a small 2D array of counters with d rows (typically 4), each with its own hash function. To record an access, increment one counter per row at the hashed positions. To estimate a key's frequency, take the minimum of its d counters. Collisions can only inflate counters, so the minimum is the least-polluted estimate. Caffeine uses 4-bit counters (maximum 15), about 8 bytes of sketch per cache entry. A frequency of 15 is enough to separate hot from cold, and small counters keep the sketch in a few CPU cache lines.
How it forgets: the reset. After a sample of W accesses (about 10 times the cache size), every counter is halved. This keeps counts proportional to recent popularity, so a key that was hot last week but is now cold loses its advantage within a few reset periods. Halving is cheap (a shift on packed counters) and gives exponential decay without timestamps.
The doorkeeper. Most keys are seen only once. The original design puts a small Bloom filter in front of the sketch: the first access to a key sets its bits in the doorkeeper only, and only later accesses increment the sketch. One-hit wonders therefore never consume sketch counters. The doorkeeper is cleared at each reset.
Why the "W". Pure TinyLFU has one weakness: a brand-new key that will become hot (breaking news, a new release) starts with a low frequency and keeps losing admission contests. W-TinyLFU adds a small window LRU in front, which admits every new item unconditionally. Items leaving the window compete with the main area's victim using the sketch. The main area is a segmented LRU (by default 20% probation, 80% protected). Caffeine starts the window at 1% of capacity and adapts its size by hill climbing: it periodically measures the hit ratio, grows the window if recency-heavy workloads benefit, and shrinks it when frequency matters more.
Hash flooding defence. An attacker who could predict the sketch's hashes could raise a junk key's estimated frequency and push out real data. Caffeine randomises hash seeds and admits a small fraction of "warm" candidates at random when frequencies are close, which breaks such attacks at almost no cost.
What you get. On published traces (search, database, web and analytics workloads), W-TinyLFU's hit ratio is consistently close to the offline optimum and at or above ARC and LIRS, with lower metadata cost. In practice, switching a JVM service's in-process cache from a plain LRU map to Caffeine often raises the hit ratio by several percentage points on skewed workloads, which can remove a large share of the remaining backend load (remember that load is proportional to the miss ratio).
Invalidation strategies#
| Strategy | How | Staleness | Complexity | Fits |
|---|---|---|---|---|
| TTL | Entry expires after a fixed time | Up to the TTL | Lowest | Data where some staleness is fine; safety net for all |
| Explicit delete on write | Writer deletes the key after updating the DB | Milliseconds (plus race windows) | Every write path must know the keys | Object caches keyed by ID |
| Versioned keys | Include a version in the key (product:123:v7 or v=hash in asset URLs); writes bump the version | None for readers that fetch the new version | Must store or derive the current version | Static assets, config, whole-namespace flushes |
| Event-driven (CDC) | A consumer tails the DB change log and deletes or updates affected keys | Tens of ms to seconds | A pipeline to run | Many writers to the same tables, multi-service systems |
TTL is always worth having, even with other methods, so a missed invalidation heals itself.
Explicit delete is the cache-aside default. Its weakness is coverage: a batch job, a manual SQL fix or another service writing the same table will not delete the key. It also breaks for derived entries: when a product changes, which cached search results include it?
Versioned keys avoid deleting at all. For static files, the build adds a content hash to the file name (app.3f9c1b.js), so you can cache forever with Cache-Control: max-age=31536000, immutable; a new release uses new names. For data, you can keep a namespace version (catalog_version = 42) in the cache and prefix keys with it; bumping it to 43 effectively invalidates the whole namespace at once, and old keys expire by TTL.
Event-driven invalidation puts the database log in charge:
Every change, from any writer, produces an invalidation, in commit order. See Change Data Capture.
Invalidation, in depth#
The real difficulty is the dependency map. Deleting one key is easy. Knowing which keys a change affects is hard. When product 123's price changes, the stale entries may include product:123, the category page listing it, three search-result pages, a "recently viewed" widget, a recommendations block and a CDN-cached HTML page. Invalidation strategies differ mainly in how they solve this mapping.
Approach 1: key by identity only. Cache only entities keyed by ID (product:123, user:42) and assemble pages from them at request time. Invalidation becomes exact and cheap: the changed row maps to one or a few keys. The cost is more cache lookups per page (an MGET of 50 keys instead of one GET), which is usually fine because a pipelined MGET takes about the same time as a single GET.
Approach 2: tags and reverse indexes. For derived entries (lists, search pages, rendered HTML), record which entities each entry depends on. A cached category page is tagged product:123, product:456 and category:7. When product 123 changes, delete every entry carrying that tag. In Redis you can keep a set per tag (tag:product:123 holds the keys) and delete members on change. CDNs offer this natively: Fastly calls them surrogate keys, Cloudflare and Akamai call them cache tags, and Varnish supports tag-based bans. Tag sets need a TTL as well, or they grow forever.
Approach 3: generational (namespace) keys. Keep a version number per namespace and build keys from it: catalog:v42:product:123. To invalidate everything in the namespace, increment the version to 43. Readers fetch the current version (itself cached for a second or two in process) and naturally start missing on the old keys, which are never read again and expire by TTL. This turns "delete a million keys" into one increment. The cost is a burst of misses right after the bump, so use it for rare, wide changes such as a schema change, a pricing rule change or a bad deploy that cached broken data.
Approach 4: content-addressed names. For immutable artefacts (JavaScript bundles, images, compiled templates), put a hash of the content in the name. A new version is a new name, so the old entry never needs invalidating and can be cached for a year with immutable. HTML pages that reference the assets are then the only thing with a short TTL.
Approach 5: CDC-driven invalidation. A change data capture tool (Debezium on the PostgreSQL WAL or MySQL binlog, or DynamoDB Streams) emits every committed row change. An invalidator consumes the stream and maps each row change to keys using the rules from approaches 1 to 3. Design points:
- At-least-once delivery. The stream will sometimes redeliver events. Deletes are idempotent, so duplicates are harmless, which is one more reason to delete rather than set.
- Ordering. Kafka preserves order within a partition, so partition the change topic by primary key. Then all changes to one row are applied in commit order.
- Lag is your staleness. Monitor the lag from commit to invalidation. Typical figures are tens of milliseconds to a couple of seconds. During a pipeline outage, the TTL is the only remaining bound, so do not make TTLs infinite just because CDC exists.
- Capture from the right place. If readers refill from read replicas, invalidating as soon as the primary commits lets a reader reload the old row from a lagging replica. Capturing changes from the replica, or delaying the delete by the replica lag, fixes it.
In-process (L1) caches need a broadcast. When each application server keeps its own local cache in front of Redis, a delete must reach every server. Options are a pub/sub channel that every server subscribes to (Redis pub/sub or a Kafka topic), short local TTLs (1 to 10 seconds) that bound staleness without any messaging, or Redis server-assisted client-side caching. In that Redis 6 feature, the server remembers which keys each connection has read (or which key prefixes it subscribed to in broadcasting mode) and pushes an invalidation message when any of them changes.
Choosing TTLs from the data, not by habit. A TTL is the maximum staleness you accept when every other mechanism fails. A news-feed post cache is a good example: posts are created often but edited rarely, so post objects can have a long TTL (hours or a day) with LRU eviction, and only an edit triggers an explicit delete. As long as the cache can hold the recent posts, almost all reads hit it. Permissions, prices at checkout and inventory sit at the other end, where TTLs are seconds or the data is not cached at all.
Hot keys complicate invalidation. In that post cache, a viral post concentrates all its reads on the one cache node that owns its key, and every invalidation of it causes a burst of misses. A common fix is redundant caching: run several independent cache replicas behind a load balancer, each able to serve any post, so a hot post's traffic spreads across all of them. The price is up to N database reads per invalidation (one per replica) instead of one, and less total distinct capacity, which is small compared with the load the replicas absorb. See Cache Failure Modes for hot-key techniques.
Data that invalidates itself. Some data does not need invalidation because each update replaces the previous value and old values expire. Driver locations in a ride-hailing system are the textbook case. Writing millions of location updates per second to a relational or key-value database directly is very expensive, so the live positions are kept in Redis geospatial sets instead, where each GEOADD overwrites the driver's previous position. Drivers who stop sending updates are cleaned up by a periodic job that uses a companion sorted set of last-update timestamps and removes entries older than about 30 seconds. Losing the cache is tolerable because fresh locations arrive every few seconds. The same idea appears in locks: a Redis lock with a 10-second TTL releases itself when its owner crashes, whereas an in-memory timer inside a service is lost when that service restarts and leaves the lock stuck. Expiry is often the most reliable form of invalidation you have.
Stale data and cache/DB race conditions#
Two copies updated by separate operations will sometimes disagree. Common races:
1. Delete before write. A writer deletes the key, then updates the database. In between, a reader misses, reads the old row and caches it, so the cache stays stale until TTL. Fix: update the database first, then delete.
2. Stale set after delete (the classic cache-aside race). Reader A misses and reads the old row. Writer B updates the database and deletes the key. Reader A, delayed, sets the old value. Rare (the read must straddle the write), but real at scale. Fixes: short TTL, delayed double delete (delete again ~1 second later), versioned conditional sets (only set if the version is newer), or leases (Meta's approach, where a delete invalidates the reader's right to set).
3. Concurrent updates to the cache. Two writers each update the database, then each sets the cache with their own value. If their cache sets arrive in the opposite order to their database commits, the cache keeps the older value indefinitely. This is why deleting is safer than updating.
4. Replica lag. The writer deletes the key; a reader misses and reloads from a lagging read replica, caching the old value. Fixes: reload from the primary right after writes, or delay the delete until replicas catch up (CDC from the replica achieves this naturally).
Races and visibility, in depth#
Two more races worth knowing. Beyond the four above, two show up in larger systems:
- 5. Invalidation overtakes replication across regions. A write commits in the primary region, and the invalidation is broadcast to all regions at once. A reader in a replica region misses, reloads from its local database replica, which has not yet received the write, and caches the old value. Fixes: send invalidations from each region's own replication stream (so a region invalidates only after its replica has applied the change), or route reads of recently written keys to the primary region for a short time, as with Meta's remote markers (described in Caching Strategies).
- 6. Eviction hides a failed invalidation. The writer's delete fails, but the stale key happens to be evicted soon afterwards, so tests pass. In production, with a larger cache and less eviction, the same bug leaves stale data for the whole TTL. Inject delete failures in tests rather than relying on eviction to mask them.
"The update must be visible immediately." Some requirements leave no room for TTL staleness: a user changes their privacy setting, an admin revokes access, a seller corrects a wrong price. Approaches, from simplest to strongest:
- Do not cache it. If the data is cheap to read from the database, reading it directly is the only approach with no edge cases.
- Invalidate synchronously before acknowledging. The write path commits, deletes the key, waits for the delete to succeed (retrying if needed), and only then returns success. Any read that starts after the acknowledgement misses and reloads. The stale-set race can still reinsert the old value, so pair it with versioned sets or leases.
- Read-your-writes for the writer, bounded staleness for others. Mark the writer's session with the time of the write and send their reads to the database for a few seconds. Other users see the change within the invalidation lag. This is usually what "immediately" really means.
- Version check on read. Keep a tiny, authoritative version number per entity (in the database or a strongly consistent store), and on every cache hit compare the cached version with it. A mismatch is treated as a miss. This costs one small lookup per read, but it gives fresh reads even if an invalidation is lost, and it is common for permission and security data.
- Short TTLs plus a kill switch. For security-sensitive caches (tokens, ACLs), keep TTLs at seconds to a minute and provide a way to bump the namespace version and invalidate everything at once during an incident.
Millions of concurrent reads of one key. A single Redis node handles on the order of 100,000 to a few hundred thousand simple operations per second. A key read a million times per second will saturate its node no matter how good the eviction policy is, and every invalidation of that key turns into a stampede. Techniques:
- Local caching of the hottest keys in each application server for a second or two. Ten thousand servers each reading Redis once per second replaces millions of requests with ten thousand.
- Replicating the key. Write copies under suffixed keys (
feed:global#0tofeed:global#15) that hash to different nodes, and have readers pick one at random. Invalidation must delete all copies. - Read replicas of the cache with reads spread across them, accepting replica lag.
- Coalescing on misses, so an invalidation produces one reload per process instead of one per request.
- Refresh in place instead of deleting for such keys: a background job writes the new value over the old one, so the key never disappears.
Delete vs update on write#
| Delete the key on write | Update (set) the key on write | |
|---|---|---|
| Next read | Miss, reload from DB | Hit, fresh value |
| Concurrent writers | Safe: worst case an extra miss | Risky: out-of-order sets leave old data |
| Wasted work | None if not read again | Computes values that may never be read |
| Derived/aggregated entries | Easy: just delete | Must recompute the derived value correctly |
| Hot keys | A burst of misses after each write | Smooth |
Default to delete. Update on write only when the key is very hot (deleting would cause a stampede) and writes to it are serialised (one writer, or versioned conditional sets).
Delete vs update, in depth#
Why delete is the safe default, stated precisely. A delete is idempotent (applying it twice is the same as once) and order-insensitive (two deletes in either order leave the same state). A set of a full value is neither: two sets in different orders leave different states. Concurrent writers, retried messages and redelivered CDC events all reorder or duplicate operations, so only operations with these properties stay correct without coordination.
When updating is also safe. The same reasoning tells you when update-on-write is fine:
| Update type | Example | Safe under reordering? |
|---|---|---|
| Commutative increments | INCRBY views:123 1 | Yes, in any order, but retries double-count unless deduplicated |
| Set additions and removals of distinct members | SADD likes:123 user:9 | Yes, for distinct members |
| Versioned full-value set | Set only if version is newer | Yes, the newest version always wins |
| Unconditional full-value set | SET product:123 {...} | No |
| Read-modify-write of a cached JSON blob | Fetch, change a field, set back | No, concurrent writers lose updates |
So counters, membership sets and versioned values can be updated on write, which keeps hot keys warm. Everything else should be deleted.
The hidden cost of delete on hot keys. Each delete of a key read 10,000 times a second creates a miss storm until it reloads. With a 50 ms reload that is about 500 requests reaching the backend, or one if coalescing works. For keys like this, prefer an in-place versioned update from a single writer (or the CDC consumer), or serve the stale value while one request refreshes it.
A worked decision. A product page's cached object combines catalogue data (edited a few times a day by merchants), price (changed by a pricing service several times an hour) and stock level (changing constantly). Caching all three in one object means every stock change deletes the whole object and the hit ratio collapses. Split it instead: cache the catalogue object for an hour with delete-on-edit, cache the price for a minute with versioned updates from the pricing service, and do not cache exact stock at all. Show "in stock" from a 10-second cached flag and check the real count at checkout. Separating data by change rate is often the single most effective invalidation decision.
Operating eviction and invalidation#
Read the counters. Redis exposes evicted_keys (removed for space), expired_keys (removed by TTL), keyspace_hits and keyspace_misses in INFO stats. Memcached exposes evictions, expired_unfetched and evicted_unfetched. The last two are especially useful: items that expired or were evicted without ever being read show how much memory is spent on data nobody uses. A high evicted_unfetched rate means you are caching too much of the long tail, so shorten TTLs or stop caching that key type.
Evictions are not always bad. A full cache that evicts steadily is working as designed. Worry when evictions rise together with misses on keys that were recently evicted (the cache is too small for the working set), or when evictions happen while most memory is held by keys with long TTLs that are rarely read.
Know the per-key overhead. Each Redis key costs roughly 50 to 100 bytes of overhead beyond its value (dictionary entry, object header, expiry entry), more for small hashes and sets that outgrow their compact encodings. For 100 million small keys, that overhead alone is 5 to 10 GB. Memcached's slab allocator wastes up to the gap between slab sizes for each item. Size the cache from measured memory per key, not from the value sizes.
Policy traps.
volatile-lru,volatile-lfuandvolatile-ttlevict only keys that have a TTL. If your keys have no TTLs, these policies cannot evict anything and Redis behaves likenoeviction, rejecting writes when memory is full.- Mixing cache data and durable data (sessions, queues, locks) in one Redis instance with
allkeys-*eviction means the durable data can be evicted. Separate them, or usevolatile-*and give only cache keys TTLs. - Setting
maxmemoryto the full machine RAM leaves no room for fragmentation, replication buffers or fork-time copy-on-write during persistence. Leave 20 to 30% headroom.
Invalidation runbook items. Have a tool to delete keys by pattern safely (using SCAN in batches, never KEYS on a large instance, because KEYS blocks the single-threaded server), a namespace version you can bump in an emergency, a CDN purge procedure with a documented propagation time, and a dashboard showing CDC invalidation lag. A cache incident is usually solved by one of these four.
Eviction in other layers#
The same ideas appear wherever there is a cache, and knowing the variants helps when you tune the layer below your application cache.
- PostgreSQL shared buffers use a clock sweep. Each buffer has a usage count that is incremented on access, up to a maximum of 5. The sweep decrements counts as it passes, and evicts a buffer whose count has reached zero. A page hit many times survives several sweeps, which is a cheap blend of recency and frequency. Large sequential scans use a small ring buffer instead of the main pool, so a full-table scan does not flush the cache, which is scan resistance built into the database.
- MySQL InnoDB's buffer pool uses LRU with midpoint insertion. The list is split into a young sublist and an old sublist (by default the old part is 37% of the pool, set by
innodb_old_blocks_pct). New pages enter at the head of the old sublist and move to the young sublist only if they are accessed again afterinnodb_old_blocks_time(1,000 ms by default). A scan touches each page in quick succession, so its pages never get promoted and age out of the old sublist. - The Linux page cache keeps active and inactive lists. Pages start on the inactive list and are promoted to active on a second access, the same two-touch idea as 2Q and segmented LRU.
- CDNs combine TTL expiry from
Cache-Controlheaders with LRU-like eviction on each edge server, tiered caching (edge, regional tier, origin shield) so a miss at one edge can be served by a parent, and admission filters on flash. A CDN purge is invalidation, while eviction happens silently when edge storage is full, which is why rarely requested objects miss often at the edge even with long TTLs. - Browsers keep a per-profile HTTP cache with an overall size limit and evict roughly by least recent use. Long
max-agevalues are therefore a ceiling, not a guarantee.
The lesson for application caches: the most successful production policies (clock sweep, midpoint insertion, two-touch promotion) all make new entries prove themselves before they can push out established ones.
Measuring and tuning a policy#
Miss-ratio curves. The most useful tool for sizing and tuning a cache is a miss-ratio curve (MRC): the miss ratio as a function of cache size for your real request stream. It tells you how much a bigger cache would help before you buy memory. Mattson and colleagues (IBM Systems Journal, 1970) showed that for LRU you can compute the miss ratio for every size in one pass over a trace, using stack distances: for each request, the number of distinct keys accessed since the previous request for the same key. A request with stack distance d hits in any LRU cache larger than d. A histogram of stack distances is therefore the whole MRC.
Sampling makes it cheap. Exact stack distances need a lot of memory on large traces. SHARDS (Waldspurger and colleagues, FAST 2015) samples keys by hash, for example keeping only keys whose hash falls in 1% of the hash space, and scales the distances up. It builds accurate MRCs with a small fraction of the memory and CPU, which makes continuous online MRCs practical.
A tuning workflow.
- Capture a trace of cache keys (key hash, timestamp, value size) for a representative day, sampled by key so per-key patterns stay intact.
- Replay it through simulators of the candidate policies (LRU, LFU, W-TinyLFU, S3-FIFO) at several sizes. Caffeine's simulator and libCacheSim are open-source options.
- Plot hit ratio against size per policy. Look for the knee of the curve, the point beyond which more memory buys little.
- Translate miss-ratio differences into backend load: at 50,000 requests per second, going from a 4% to a 2% miss ratio removes 1,000 backend reads per second.
- Validate in production with a canary instance, comparing hit ratio and latency, before rolling out.
A worked reading of an MRC: if the curve shows 92% hits at 16 GB, 96% at 32 GB and 97% at 64 GB, the step from 16 to 32 GB halves backend load (8% to 4% misses), while the step from 32 to 64 GB removes only a quarter of what remains. The 32 GB cache is likely the right size, unless that last quarter of misses lands on a very expensive backend.
Worked example: a news site's cache#
The setting. A news site serves 40,000 page views per second at peak, mostly through a CDN, with an application cache in Redis behind it. Articles are written once, edited a few times in the first hour (corrections, updates to breaking stories) and then rarely touched. Section pages (home, politics, sport) list the latest articles and change whenever one is published or edited. Editors expect corrections to be visible to readers within about 30 seconds.
Eviction choices. Article objects follow a strongly skewed popularity curve: today's top stories get most of the traffic, while the archive gets a long tail of search and social traffic. Redis runs with allkeys-lfu, so the top stories stay cached even when an archive crawler sweeps through old URLs. At the CDN, HTML pages use second-hit admission on flash so crawler traffic does not churn edge storage.
Invalidation choices. Article objects are keyed by ID with a 6-hour TTL, deleted on edit. Rendered HTML at the CDN is tagged with the article ID and the sections it appears in. Section pages have a 60-second TTL plus stale-while-revalidate, and are also tagged with the IDs of the articles they list.
Why it meets the requirement. The CDC lag is typically under a second and a tag purge propagates across the CDN within seconds, so a correction is visible well within 30 seconds. If the CDC pipeline is down, the 60-second section TTL and the 6-hour article TTL bound the damage, and the newsroom runbook includes a manual purge-by-tag command for urgent corrections. Breaking-story pages, which are edited many times in the first hour, are a special case: they get a short 30-second TTL during that hour, so a missed purge never matters.
Hot keys. When a major story breaks, its article page becomes the hottest key on the site. The CDN absorbs nearly all of it, and the origin cache receives only revalidation traffic. Redis sees one reload per purge thanks to coalescing at the origin service. The only real load risk is a purge of a very popular tag such as the home page, which is why section pages use stale-while-revalidate: after a purge, edges serve the stale page once while one request fetches the fresh one.
Derived data: lists, counts and aggregates#
Why derived entries are the hardest. An entity cache entry depends on one row. A list ("latest 20 articles in sport"), a count ("1,204 comments") or an aggregate ("average rating 4.6") depends on many rows, and a single write can affect several of them. Three approaches cover most cases:
- Recompute on a short TTL. Accept that the list or count is up to N seconds old, and rebuild it on expiry with coalescing or refresh-ahead. This is simplest and right for most feeds and counters.
- Update incrementally with commutative operations. Maintain the derived value in the cache directly:
ZADDa new article into the section's sorted set,INCRthe comment count, add to a running sum and count for the rating. These operations are safe to apply in any order, so they can be driven from a CDC stream. Periodically rebuild from the database to correct drift from lost or duplicated events. - Invalidate by dependency. Tag the derived entry with the entities it covers and delete it when any of them changes. This is exact, but popular entities can fan out to thousands of derived entries, so combine it with a TTL fallback for very wide tags.
Choose per derived value, considering how wrong the value may be, for how long, and how expensive a rebuild is.
A worked comparison. A product's review summary ("4.6 stars from 2,310 reviews") changes with each new review, which happens a few times a minute for popular products. Recomputing on every review means an aggregate query over thousands of rows per write. Deleting on every review causes misses on a heavily read key. Incremental maintenance stores a sum and a count, adds the new rating to both and divides on read. It is exact, cheap and order-independent, and a nightly rebuild from the reviews table catches any drift.
When to Use It#
- Always choose an eviction policy and memory limit for every cache.
- Explicit delete for ID-keyed object caches with few write paths.
- Versioned keys for static assets and whole-namespace changes.
- CDC invalidation when many services or jobs write the same data, or correctness matters across teams.
When NOT to Use It#
- Do not rely on TTL alone for data whose staleness causes harm (permissions, prices at checkout).
- Do not update cache values from multiple concurrent writers without versions.
- Do not cache derived results (search pages, aggregates) unless you can either invalidate them or accept TTL staleness.
How to Implement It#
- Set
maxmemoryand a policy:allkeys-lfuorallkeys-lrufor pure caches; Caffeine (W-TinyLFU) in-process. - Give every key a TTL, with jitter.
- On writes: commit to the database, then delete keys; never delete before the write.
- For hot keys, use versioned sets or leases to avoid stale sets and stampedes.
- Version static assets with content hashes and long cache lifetimes.
- Add CDC-driven invalidation when multiple writers exist; make the invalidator idempotent.
- Measure staleness by sampling: compare cached values with the database for a small share of reads.
| Technology | Fits when |
|---|---|
Redis (allkeys-lru/lfu) | Shared cache with approximated LRU/LFU |
| Memcached (segmented LRU) | Simple shared cache |
| Caffeine (W-TinyLFU) | In-process JVM caches with top hit ratios |
| Debezium + Kafka | CDC-based invalidation |
| CDN purge APIs, versioned asset names | Edge invalidation |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| LRU | Simple, recency-aware | Scan pollution | General default |
| LFU / W-TinyLFU | Higher hit ratio on skewed data | Counters, tuning | Stable popularity, scan-heavy mixes |
| TTL invalidation | No coordination | Bounded staleness | Tolerant data, safety net |
| Explicit delete | Fast freshness | Misses writers; races | ID-keyed objects |
| Versioned keys | No deletes, instant switch | Version lookup, orphaned keys until TTL | Assets, namespaces |
| CDC invalidation | Covers all writers | Pipeline, small delay | Multi-writer systems |
| FIFO-based (S3-FIFO, SIEVE) | Scales without per-hit locking, quick demotion of one-hit wonders | Newer, fewer battle-tested implementations | High-throughput caches, new implementations |
| Tag-based invalidation | Exact invalidation of derived entries | Tag sets to maintain, fan-out on popular tags | Rendered pages, search results, CDN content |
| Namespace version bump | Invalidates millions of keys with one write | Burst of misses, orphans until TTL | Rare, wide changes and emergencies |
Common Pitfalls#
- No
maxmemorylimit, so the cache grows until the OS kills it. - Using
noevictionon a pure cache, causing write errors when it fills up. - Deleting from the cache before writing the database.
- Purging a CDN for every change instead of versioning asset URLs.
- Forgetting derived keys (lists, counts) when an entity changes.
- Using a
volatile-*policy when keys have no TTL, so Redis cannot evict and starts rejecting writes. - Storing locks, sessions or queues in the same Redis as an
allkeys-*cache, so durable data gets evicted. - Invalidating from the primary's change stream while readers refill from lagging replicas.
- Running
KEYS patternon a large production instance to clean up, blocking the server.
Real-World Examples#
Caffeine's documentation and the TinyLFU paper (Einziger, Friedman and Manes) describe W-TinyLFU's near-optimal hit ratios, and Caffeine is widely used in Java, including as a supported cache provider in Spring.
Meta's memcache paper describes deleting keys after MySQL commits by tailing the database commit log (the mcsqueal daemon), which broadcasts invalidations to cache clusters across regions.
Memcached's segmented LRU, slab rebalancer and LRU crawler are documented in its project wiki, and they explain much of its scan resistance. Akamai's second-hit admission using Bloom filters shows how much an admission policy matters at CDN scale.
In the Interview#
Eviction and invalidation in an interview#
Separate the two questions out loud. "When the cache is full, Redis evicts with allkeys-lfu. When data changes, we delete the key after the database commit, and a CDC consumer deletes keys for writes from other jobs. Every key also has a TTL as a safety net." That one sentence covers both problems and shows you know they are different.
Tie TTLs to requirements. Give a number and the reason for it: "post objects keep a 24-hour TTL because posts are rarely edited and edits trigger a delete. The like count is cached for 5 seconds because users accept a slightly old count." Interviewers notice when TTLs come from the data rather than habit.
Expect the dependency question. If you cache derived results (search pages, feeds, aggregated counts), the interviewer may ask how they are invalidated when an underlying entity changes. Good answers: cache only entities and assemble at read time, tag derived entries and delete by tag, accept TTL staleness for derived views, or bump a namespace version for rare wide changes.
Mention eviction only as deeply as needed. For most designs, "LRU or LFU with a memory limit" is enough. Go deeper (W-TinyLFU, scan resistance, admission) when the problem is a CDN, a large in-process cache, or a workload with scans and one-hit wonders, where the policy changes the hit ratio enough to matter.
Have an answer for "updates must be visible immediately". Name a concrete mechanism: synchronous invalidation before acknowledging plus versioned sets, read-your-writes routing for the writer, or a version check on read for security data. Then admit the honest alternative, which is not caching that data.
Deep Dive: Belady's optimum, scan resistance and segmented LRUShow
Belady's algorithm (the theoretical optimum) evicts the entry whose next use is furthest in the future. It is impossible in practice, but used in simulations as the upper bound to compare policies against.
Scan resistance. A full-table scan or a crawler touching millions of keys once each would flush a plain LRU cache. Segmented LRU (SLRU) splits the cache into a probationary segment for new entries and a protected segment for entries hit at least twice; only probationary entries are evicted by scans. Memcached uses a segmented LRU with hot, warm and cold queues. 2Q and ARC (Adaptive Replacement Cache, used in ZFS) are related designs.
Hierarchical invalidation. For entities that appear in many derived entries (a user in many group lists), maintain a reverse index from entity to keys, or use tag-based invalidation (some CDNs support purge-by-tag, such as Fastly surrogate keys and Cloudflare cache tags) to delete everything tagged with user:42 at once.
Deep Dive: The theory and research lineage of eviction policiesShow
Belady's optimum, and why it is optimal. Bélády (IBM Systems Journal, 1966) showed that evicting the item whose next request is furthest in the future minimises misses for any request sequence. The exchange argument behind it is short. Take any other policy that, at some step, evicts an item x whose next use comes sooner than that of the item y that Belady would evict. Swap the decision so the policy evicts y instead and keeps x until x is used. The modified policy never misses more, because x is needed before y. Repeating the swap turns any policy into Belady's without increasing misses. Belady needs the future, so it serves as the yardstick in simulations: a policy that reaches 90% of the optimal hit ratio on a trace is doing very well.
Competitive analysis: how bad can LRU be? Sleator and Tarjan ("Amortized efficiency of list update and paging rules", Communications of the ACM, 1985) proved that LRU and FIFO with a cache of k entries never incur more than k times as many misses as the optimal offline policy with the same size, and that no deterministic online policy can guarantee better than k. That sounds terrible, but the bound comes from adversarial sequences, such as cycling through k + 1 keys, where LRU misses every time. The same paper shows that if LRU gets twice the memory of the optimal policy, it is at most about twice as bad. That resource-augmentation result is the theoretical reason why "add a bit more memory" works so well in practice.
Why real workloads are kinder. Request streams in web, database and CDN traffic are highly skewed (roughly Zipf-distributed) and have temporal locality, so the adversarial patterns are rare. The gap between policies then comes from two specific behaviours. The first is scan resistance: a burst of single-use keys should not displace the hot set. The second is adaptivity: when popularity shifts, the policy should forget old frequencies quickly. Every policy after LRU targets one or both.
The lineage.
| Policy | Source | Main idea |
|---|---|---|
| LRU-K | O'Neil, O'Neil and Weikum, SIGMOD 1993 | Rank by the time of the K-th most recent access (LRU-2 in practice), which separates "seen once" from "seen repeatedly" |
| 2Q | Johnson and Shasha, VLDB 1994 | A FIFO probation queue for new items and an LRU main queue for items referenced twice, giving LRU-2 behaviour at O(1) cost |
| LIRS | Jiang and Zhang, SIGMETRICS 2002 | Rank by reuse distance (how many distinct keys appear between two accesses) instead of recency |
| ARC | Megiddo and Modha, FAST 2003 | Two LRU lists (seen once, seen at least twice) plus ghost lists of recently evicted keys. Hits in the ghost lists shift the split between the two, so the cache adapts between recency and frequency with no tuning |
| TinyLFU / W-TinyLFU | Einziger, Friedman and Manes, ACM TOS 2017 | A frequency sketch used as an admission filter, with a small window for new items |
| LRB | Song and colleagues, NSDI 2020 | Machine learning that approximates Belady for CDN caches by predicting which objects are beyond a "good decision" boundary |
| S3-FIFO, SIEVE | Yang and colleagues, SOSP 2023. Zhang and colleagues, NSDI 2024 | FIFO queues with quick demotion of new items and lazy promotion, simple and scalable |
ARC's ghost-list idea, remembering keys after evicting their values, reappears in S3-FIFO and in W-TinyLFU's sketch, which in effect remembers frequencies of keys that are not cached. The recurring insight is that metadata about recently evicted keys is cheap and tells the policy whether its last decisions were mistakes.
Admission matters as much as eviction, especially for CDNs. Flash-based CDN caches add a further constraint: every admission is a write, and flash wears out with writes. Admitting only objects that have been requested at least twice (a "second hit" rule, often implemented with a Bloom filter) cuts writes sharply and usually raises the hit ratio, because one-hit wonders no longer push out useful objects. Akamai described this kind of Bloom-filter-based second-hit admission in its 2015 paper on algorithmic nuggets in content delivery (Maggs and Sitaraman, ACM SIGCOMM Computer Communication Review).
Variable sizes break the simple picture. All the policies above treat items as equal-sized. Real caches hold values from 100 bytes to many megabytes, so evicting one large item can make room for thousands of small ones. Size-aware policies such as GreedyDual-Size (Cao and Irani, USENIX Symposium on Internet Technologies and Systems, 1997) assign each item a priority of roughly cost divided by size, plus an aging term, so large, cheap-to-refetch items go first. Memcached's slab classes handle the same problem by segregating sizes, at the cost of per-class eviction.
Practical summary. For a shared Redis cache, use approximated LFU or LRU and spend your effort on TTLs and invalidation. For a large in-process JVM cache, use Caffeine. For a CDN or flash cache, admission control matters more than the eviction order. For a new cache implementation, a FIFO-based design such as S3-FIFO or SIEVE is a strong, simple starting point.
Key Takeaways#
- Eviction decides what to drop when the cache is full; invalidation removes entries that are wrong after data changes.
- LRU is the default eviction policy; LFU keeps long-term popular items; W-TinyLFU gives near-optimal hit ratios.
- Invalidate with TTLs always, plus explicit deletes, versioned keys or CDC-driven events as needed.
- Write the database first, then delete the key; deleting is safer than updating under concurrency.
- Rare races remain; bound them with TTLs and close them with versioned sets or leases.
- Eviction bets on future reuse. Recency and frequency carry most of the signal, and admission decides whether a newcomer deserves a place at all.
- Scans and one-hit wonders are LRU's weakness. Segmented LRU, W-TinyLFU and S3-FIFO all add quick demotion or an admission filter.
- The hard part of invalidation is mapping a change to keys: key by entity, tag derived entries, bump namespace versions, and drive deletes from CDC.
- Delete because it is idempotent and order-insensitive. Update only with commutative or versioned operations.