Caching: every layer, eviction, invalidation, and the LLM caches

Why a small copy catches most traffic, every layer from the CPU to the browser, the patterns, invalidation and the stale-set race, stampedes, Redis eviction measured on real traffic, what a hit is worth, Postgres's own caches, CDNs, and the three caches of an LLM product. Measured on a laptop with Redis 8.8, PostgreSQL 16.2 and two embedding models on real data. Child page of Topic: databases; data as of October 2026. Reading: 43 min, plus 22 in closed details.

The idea in one screen

A cache is a second, faster copy of data, and it pays because traffic is skewed: a copy of the popular few absorbs most reads. Everything hard follows from it being a copy: it can go stale (invalidation), it cannot hold everything (eviction), its misses still cost (weigh each hit by the miss it avoids), and one kind, the semantic cache, can hand back a wrong answer.

Fig. 1: one chat request passes up to nine copies; the further out, the bigger the saving and the harder to invalidate

  1. Seven copies, outermost on top. The chat product of Topic: databases keeps its data in a browser, a CDN edge, an in-process dict, Redis, Postgres's buffers and the OS page cache, in front of the SSD that holds the source of truth. Hit times beside each are from the ladder in section 2 (measured on the laptop or sourced there).
  2. A miss falls through. A request asks each copy in turn, outermost first, and the source of truth (Postgres, then the SSD) answers only when every copy misses; the answer comes back up and leaves copies on the way.
  3. A hit stops early. Found in Redis after 0.060 ms, nothing below it is touched. The further up the hit, the more it saves.
  4. Who keeps each copy correct. The top four are yours to invalidate (sections 3, 4, 7 and 9), with fewer tools the further out: nobody can purge a browser. Postgres and the kernel keep the two below correct for you. Sections 3 and 4 are about the copies you must invalidate yourself, 5 about what a full one throws away, 6 about what each hit is worth.
  5. The LLM lane: the same idea three times. A semantic cache, the provider's prompt cache and the GPU's KV cache sit in front of the model; a miss runs the full prefill.
  6. Only one of them can be wrong. The web copies are exact; the LLM lane's prompt and KV caches are exact too, and only the semantic cache (section 12) answers a question with another question's answer.

You need: the database map and where a read goes (Topic: databases), SQL and a primary key (SQL and data modelling), what a commit is (Transactions and concurrency). Running example: the root's chat product, its 10-million-message Postgres database, a Redis in front of it and an LLM behind it. measured: recorded for this page on a laptop (Apple M1 Pro, 16 GB) on 5 October 2026; a laptop has no network between client and server, so its timings are best cases, while hit ratios and counts carry over to production. illustrative: an input made up to show a shape.

Hit, miss
a request the cache answers; one it cannot, which goes to the source and usually leaves a copy behind.
Hit ratio
hits divided by all requests.
TTL (time to live)
an expiry time after which the cache drops an entry by itself.
Cache-aside
the app reads the cache, fills it from the database on a miss, and deletes the key after a write (section 3).
Invalidation
retiring a cached copy that is no longer true.
Eviction policy
the rule for choosing what to drop when the cache is full (LRU, LFU, ...).
Stampede
many requests missing the same hot key at once and all rebuilding it (section 7).
Lease
a token the cache hands out with a miss, permitting one fill; a delete revokes it (section 3).
Every section in one table, with what was measured (reference)
QuestionShort answer (measured or sourced on this page)Section
Why does a small cache catch so much?Traffic is skewed: in one real hour of English Wikipedia, the top 1% of pages got 34% of views and 55% of pages were viewed exactly once1
Where do caches live?At every layer, from a CPU's L1 (about 1 ns) to a browser (0 ms, but you cannot purge it). The further out, the bigger the saving and the harder to invalidate2
Is "delete the key on write" enough?No. Two real clients racing left a stale value in 57% of forced-overlap trials; Facebook's leases and versioned keys left 03
How stale can a reader be?Name every window: the TTL, a delete before the commit, a fill from a lagging replica, a lost invalidation. Each has a known fix4
Which Redis eviction policy?allkeys-lru or allkeys-lfu; set it, because the shipped default is noeviction. On real traffic LFU beat LRU by 10.1 points at a 50,000-key cache; the new LRM policies act like FIFO for a cache5
Is a 95% hit ratio good?Not by itself: weight each hit by what the miss would have cost. Here a miss costs 0.189 ms or 10.8 ms depending on the query6
What happens when a hot key expires?Every request in the rebuild window rebuilds it: 60 database queries for one key in the model of section 7, 1 with coalescing, a lease or XFetch7
Does the database cache for me?Its pages, yes (the buffer pool); query results, no. A materialised view answered a usage query 68× faster, at the price of being stale until the next refresh8
What do the LLM caches save?The KV cache makes generation possible; provider prompt caching bills reused input at a fraction (0.1× on most models) and pays from the first reuse; a semantic cache is the only cache that can return a wrong answer10 to 12

What other pages own and this one links: the buffer pool and the operating system's page cache (Storage engines and indexes, section 2), Redis persistence and the writes lost in a failover (NoSQL in practice, Redis), HTTP header semantics (HTTP), KV-cache internals (the inference topic, section 10), provider caching rules and bills (section 11), the cache in queueing and capacity terms (Capacity planning and performance).

1. Why caches work: a few things get most of the requests

A cache only helps if requests repeat. Locality is the name for that: temporal (used now, likely used again soon: a user's open conversation is re-read on every message) and spatial (stored together, used together: why hardware fetches 64-byte lines and Postgres 8 KB pages). Application caches live on the first kind plus skew: a small set of items far more popular than the rest. The chat product has no public access log, so this page uses the largest public one: one hour of English Wikipedia (15 September 2026, 12:00 to 13:00 UTC, desktop and mobile summed by title), 7,869,547 views of 1,683,268 distinct pages (Wikimedia pageviews) measured.

The top 0.1% of pages (about 1,683) got 17% of views, the top 1% 34%, the top 10% 65%. And 933,584 pages (55%) were viewed exactly once: no cache helps with those, because the first request for anything is a miss (a compulsory miss).

On log scales, views against rank fall near a straight line: views ≈ C / rankα, a Zipf distribution. Fitted on ranks 10 to 100,000, this hour gives α = 0.73; the larger α, the more the top dominates (at α = 1 the first item is twice as popular as the second and ten times the tenth). Web caches have been measured near this shape for decades: Breslau et al. found α "ranging from 0.64 to 0.83" across the web proxy traces they studied (INFOCOM 1999), which is why the Cache lab offers Zipf workloads at α 0.7, 0.9 and 1.1 beside the real trace.

Popularity drifts, slowly. Over six consecutive hours (06:00 to 12:00 UTC), 85% of each hour's 10,000 most viewed pages stayed in the next hour's top 10,000 measured. That drift separates eviction policies: pure frequency counting keeps yesterday's news; pure recency forgets steady favourites (measured in section 5). For the chat product: each user's own conversation list is hot only while that user is active, so a TTL of minutes fits it; shared things (the model list, feature flags, a popular shared prompt) are hot forever and need invalidation instead.

How the request trace was built from hourly counts (provenance)

The hourly file has no timestamps inside the hour, so the 2,000,000-request replay used in section 5 draws requests without replacement from the hour's views in random order. That keeps the skew exactly and removes any ordering inside the hour; the six-hour trace keeps the hour-to-hour drift. Both are real popularity, not a synthetic distribution.

One per cent of the pages got a third of the views

Pages sorted from most to least viewed. A cache that could hold exactly the most popular pages, under requests drawn independently from these counts, would hit on the share of views those pages get: that is the first view. Computed in measure/m_skew.py.

2. The layers: from the CPU to the browser

Read the ladder top to bottom as "where could this answer already be?". Each step down is roughly ten to a hundred times slower than the one above, which is the whole argument for caching.

The ladder as a table: what each layer holds, who invalidates it, and the source of each time (reference)

Four things change as you move outward:

  • Who invalidates. Hardware keeps CPU caches correct (a coherence protocol called MESI makes cores agree on each 64-byte line); the kernel keeps the page cache correct; Postgres keeps its buffer pool correct (it is the only copy writers change). From the application cache outward, you invalidate, with fewer tools the further out: you can delete a Redis key, ask a CDN to purge (a request that must reach every edge city), but you cannot reach into a browser at all.
  • Who shares it. A browser cache is one user's; a CDN is everyone's, so a personalised response cached at the edge leaks to other users unless it is marked private (section 9).
  • What a miss costs. An L1 miss costs nanoseconds; a CDN miss crosses an ocean. A layer's value is what it saves per hit times how often it hits (section 6).
  • How many copies: the local against distributed choice, next.

Local against distributed

In-process (local)

A dict, functools.lru_cache, cachetools.TTLCache, Caffeine in Java. A hit costs 11.3 ns in Python here measured: no network, no serialisation. But it exists once per process: 8 servers with 4 workers each hold 32 independent copies, each warming, missing and going stale on its own, and 32 places to invalidate.

Shared (distributed)

Redis, Valkey, Memcached: one hop away (0.060 ms on loopback here, plus a network round trip of about 0.5 ms inside a cloud region), one copy for every server, one place to delete. It is a service to run, and a slow cache must degrade into misses, not stall requests (client timeouts of tens of milliseconds).

The usual design is both: a shared cache for everything worth caching, and an in-process cache in front of it only for a few very hot keys (feature flags, the model list) with a TTL of seconds, which bounds how long the 32 copies can disagree and spares the Redis shard that owns a hot key.

Before adding Redis in front of Postgres, check that the working set fits in the database server's RAM: two caches you do not configure, the operating system's page cache and Postgres's buffer pool, already hold hot pages, and a database whose hot pages stay in memory answers a primary-key lookup in well under a millisecond.

The page cache and the buffer pool, measured (depth)

The page cache is the operating system keeping recently read file blocks in otherwise free RAM: an 8 KiB read of a cached block took 0.94 microseconds here, against about 100 microseconds from an NVMe SSD. The buffer pool (Postgres's shared_buffers) is the database's own page cache, on top of the operating system's, so a page can be cached twice ("double buffering"). Both are taught with measurements on Storage engines and indexes, section 2; this page measures only the buffer pool across a restart (section 8).

Every layer is a cache for the slower thing below it

Log scale: each grid line is ten times the one before; grey rows are what a hit avoids. Sources per bar in the table below; measured bars were timed for this page or for the system design root's Numbers to know on the same laptop.

3. Patterns and invalidation: who fills the copy, and who retires it

The patterns: who reads and writes the cache

Five patterns differ only in who talks to whom on a read and on a write. Pick one: solid arrows happen inside the request, dashed ones later; the numbers are the order.

"There are only two hard things in computer science: cache invalidation and naming things" is attributed to Phil Karlton (Martin Fowler's note: the attribution is by word of mouth).

The five patterns side by side (reference)
PatternOn a readOn a writeTrade-off
Cache-aside (lazy loading)App checks the cache; on a miss it reads the database and fills the cacheApp writes the database, then deletes the cache entryThe default. Simple, caches only what is read; the first read after a change is slow
Read-throughThe cache library loads missing entries from a function you give itAs cache-asideSame behaviour, less app code; the loader is one place to add coalescing (section 7)
Write-throughAs cache-asideWrite cache and database together, synchronouslyReads after writes are fresh; every write pays twice, and you cache data nobody may read
Write-behind (write-back)From the cacheWrite the cache now, flush to the database later in batchesFast writes, absorbs bursts; a cache crash loses acknowledged writes. Rarely right for user data
Write-aroundAs cache-asideWrite the database only; let the entry expireFor data written often and read rarely

Cache-aside for "load a conversation", with redis-py:

def get_chat(chat_id):
    key = f"chat:{chat_id}:v1"            # version the key so a format change cannot read old entries
    hit = r.get(key)
    if hit is not None:
        return json.loads(hit)
    chat = db_load_chat(chat_id)          # the slow path: a Postgres query
    r.set(key, json.dumps(chat), ex=300)  # TTL 300 s bounds how stale it can ever be
    return chat

def rename_chat(chat_id, title):
    db_rename_chat(chat_id, title)        # 1. write the source of truth (commit)
    r.delete(f"chat:{chat_id}:v1")        # 2. then delete, never update, the cached copy

Cache-aside is the default because the app, not the cache, decides what to fill and when to retire

Why invalidation is hard

Ada renames her chat "Trip plan" to "Trip plan v2". Postgres holds the new title; the cache still holds the old one. A cache makes a second copy of a fact, and two copies of a fact is a small distributed system. Five questions must each have an answer, and every caching bug is one left unanswered: what invalidates this entry, who knows it must happen, how the message gets there, what if it is lost or reordered, and how would you notice.

MethodHow it worksWhat it costsWhen not to use it
TTLEvery entry expires a fixed time after it was written (SET key value EX 300)Stale for up to the whole TTL even right after a change; a miss at expiry even if nothing changedAlone, for anything a user just changed and expects to see (read-your-writes)
Explicit deleteThe code that writes Postgres deletes the cache key right after the commitThe writer must know every key derived from the row; a forgotten path (an admin script, a migration) fails silently; races (below)When many caches in many services derive from one row: use events
Event-drivenPostgres's change stream (logical replication, read by a tool such as Debezium) or an outbox table feeds a consumer that deletes affected keysA pipeline to run; at-least-once delivery and lag of its own; still needs a TTLSmall systems with one writer path: explicit delete is simpler
Versioned keysThe key contains a version (chat:42:v7); a write bumps it, so readers stop asking for the old key, which ages outOne extra lookup for the current version; old entries use memory until evictedWhen the version itself cannot be read cheaply and reliably

Whatever the method, keep a TTL underneath: it is the only mechanism that also repairs the bugs of the others. Facebook runs the event-driven kind at the largest scale on record: daemons called mcsqueal read the committed SQL on every database, extract the cache deletes embedded in it and broadcast them to every cache cluster in the region; "only 4% of all deletes issued result in the actual invalidation of cached data" (Nishtala et al., Scaling Memcache at Facebook, NSDI 2013). The outbox and change data capture are taught on Queues, streams and async work.

Delete, do not update. Putting the new value into the cache on a write works with one writer and breaks with two: they can commit in one order and reach the cache in the other, leaving the older value cached until the TTL. Two real writers renaming the same chat, each setting the cache after its commit with a small random delay, left the cache disagreeing with Postgres in 36% of 400 trials measured. A delete is idempotent and order-free, which is why Facebook's write path deletes ("We choose to delete cached data instead of updating it because deletes are idempotent", same paper).

Fig. 2 · a measured race, step by step measured

One row per recorded event, in order (rows evenly spaced; the times on the left are as recorded). Orange is the old title, green the new; the gold bar is the reader's pause.

The race that delete alone does not close

The window: a slow reader fills a value it read before the writer's commit, after the writer's delete, and the old title stays cached for the whole TTL: a stale set, in Facebook's words. Predict before it plays: which of the four strategies can still lose? Fig. 2 replays real trials (two Python clients, the local Postgres 16.2 and Redis 8.8, timestamps as recorded); the same trial number has the same delays under every strategy.

Fig. 2: a delete cannot revoke a fill already on its way; a lease or a version can

Trial 5 of 400: reader pause 5.87 ms, writer start 2.40 ms, timestamps as recorded by the two clients.
  1. 0.21 ms · Reader misses. It asks Redis for chat 42's title; the key is empty, so it must go to Postgres.
  2. 0.33 ms · Reader reads the OLD title. Postgres returns "Trip plan": the writer has not committed yet. Then the reader is delayed 5.87 ms (a garbage-collection pause, a busy CPU, a slow hop).
  3. 3.78 ms · Writer commits "Trip plan v2". From this instant any cached "Trip plan" is wrong.
  4. 3.94 ms · Writer deletes the key. After its commit, as cache-aside says. But the key is already empty: this delete removes nothing, and the slow reader still holds the old value.
  5. 8.52 ms · Reader fills the OLD title: a stale set. The slow reader wakes and writes the value it read before the commit. Redis says "Trip plan" while Postgres says "Trip plan v2", and will for the whole 300-second TTL.

Over 400 trials per strategy, with timings forced to overlap (the reader pauses 0 to 10 ms in 90% of trials and 10 to 100 ms in 10%; the writer starts 0 to 10 ms in) measured: delete on write left 227 stale, a lease and versioned keys 0.

The stale shares are a property of these forced timings, not a production rate: in production the window is rare per request, but a busy key gets millions of requests, and one stale set leaves a wrong value for the whole TTL. The point is the zeros.

A lease is Facebook's fix: "The lease is a 64-bit token bound to the specific key the client originally requested. The client provides the lease token when setting the value in the cache... Verification can fail if memcached has invalidated the lease token due to receiving a delete request for that item." The writer's delete revokes the slow reader's lease, so its old value is refused. The same token tames stampedes (section 7). Redis has no built-in lease, but a few lines emulate it. Costs: a second key per miss and a script call; a client that dies holding a lease blocks fills of that key until the lease expires (10 seconds here, as in the paper). When not to: keys never written while being read (static configuration), or whose staleness for one TTL is harmless.

Versioned keys need no new primitive: the writer commits, then bumps the version (after the commit, never before, so any reader that sees the new version also reads the new row); a slow reader can only fill an old version nobody reads any more. Or take the version from the database row the caller already holds (an updated_at column), as HTTP ETags do (section 9).

Delayed double delete, the folk fix, deletes after the commit and again a little later (here 50 ms), hoping the slow reader has filled by then. It narrows the window but cannot close it: any reader slower than the delay still wins, as 30 of 400 trials showed measured. Cheap, better than nothing, not a guarantee.

The lease and versioned-key code the measurement ran (redis-py, Lua), and the version-counter trap (depth)

One trap the measurement does not show: if the version counter itself is evicted, readers fall back to version 0 and may find an ancient entry. Give version keys no TTL under a volatile-* policy, or take the version from the database row the caller already holds (an updated_at column), which is how many HTTP caches use ETags (section 9).

# reader, on a miss: take the lease (fails if another client holds it)
tok = str(r.incr("lease:ctr"))
if not r.set("lease:" + key, tok, nx=True, px=10_000):
    time.sleep(0.005); retry()                  # someone else is filling: wait and read again
value = db.execute("SELECT title FROM chats WHERE id = %s", (42,)).fetchone()[0]
# fill only while our lease is still valid (one atomic Lua script)
FILL = r.register_script("""
  if redis.call('GET', KEYS[2]) == ARGV[1] then
    redis.call('SET', KEYS[1], ARGV[2], 'EX', 300); redis.call('DEL', KEYS[2]); return 1
  end
  return 0""")
FILL(keys=[key, "lease:" + key], args=[tok, value])
# writer: commit first, then delete the value AND the lease in one command
db.execute("UPDATE chats SET title = %s WHERE id = 42", (new,))      # autocommit
r.delete(key, "lease:" + key)
# versioned keys. writer: commit, then bump the version (after the commit, never before)
db.execute("UPDATE chats SET title = %s WHERE id = 42", (new,))
r.incr("ver:chat:42")
# reader: ask for the current version's key; a slow reader can only fill an old version nobody reads any more
v = r.get("ver:chat:42") or b"0"
key = f"chat:42:v{v.decode()}"

4. Consistency: every window in which a reader sees an old value

The useful question is not "is my cache consistent?" (it is a copy, so no) but "in which windows can a reader see a value older than the last commit, and how long can each last?". For cache-aside in front of one Postgres:

WindowHow it opensHow long it lastsFix
Between the commit and the deleteReaders between the writer's two steps get the old cached valueMicroseconds to millisecondsAccept it: it is the minimum for any cache. If one user must see their own write, read from Postgres for that user for a few seconds
Delete before the commit (an ordering bug)The writer deletes, then commits; a reader misses in between, reads the old row (not yet committed) and fillsThe whole TTLAlways commit first, then delete; in an ORM, delete in an after-commit hook, not inside the transaction
Write-through before the commitThe writer sets the cache, then the transaction fails or rolls backThe whole TTL, for a value that never existedNever write a cache inside a transaction that can still fail; delete after commit
The stale set (section 3)A slow reader fills the old value after the writer's deleteThe whole TTLLeases or versioned keys
Fill from a lagging replicaThe reader's miss goes to a read replica that has not yet received the write, and caches the old valueThe whole TTL: the cache turns milliseconds of replication lag into minutes of stalenessFill from the primary for keys just written, or mark "recently written" (Facebook's remote markers, below)
A lost or late invalidationThe delete is dropped (a crash between commit and delete) or the event pipeline lagsUntil the TTL, or until the pipeline catches upThe TTL backstop; an outbox or change data capture makes the delete durable
Write-behindAnything that reads Postgres directly (analytics, other services) sees old data; a cache crash loses acknowledged writesUntil the flush, or foreverUse only for data you can lose or rebuild (counters)

For the chat product the simple version of the replica fix is enough: after a user writes, route that user's reads to the primary for a few seconds (read-your-writes, taught on Scaling a database; consistency models in full on Distributed systems fundamentals).

Facebook's remote markers and hold-off, in their words (depth)

Facebook's regions read from local replica databases while writes go to one master region, so a cache miss right after a write could fill from a replica that lags. Their fix, the remote marker: the writer "(1) sets a remote marker rk in the region, (2) performs the write to the master embedding k and rk to be invalidated in the SQL statement, and (3) deletes k in the local cluster"; a later miss that finds the marker reads from the master instead (Nishtala et al., "Across Regions: Consistency"). They also delete with a two-second "hold-off" when warming a cold cluster from a warm one, refusing fills for that time, for the same reason.

The rule that ties it together
A cache is an optimisation: the system must stay correct with it empty. If deleting every key would lose data or break behaviour, it is not a cache but a database with no durability, and it needs the treatment of one (the NoSQL in practice page measured how many acknowledged writes a Redis failover loses).

5. Redis as a cache: what it throws away when memory is full, measured

A cache is smaller than the data behind it, so when it is full something must go: the eviction policy picks the victim. LRU evicts the entry used longest ago (cheap, good for most workloads); LFU the one used least often, with counts that decay (better when a few keys are steadily popular and a scan of one-off keys would flush them out of an LRU); TinyLFU is an admission policy: a newcomer only gets in if a compact frequency sketch says it is read more often than the entry it would evict (Einziger, Friedman and Manes, ACM ToS 2017; Caffeine, the standard Java cache, uses W-TinyLFU, "a small admission LRU that evicts to a large Segmented LRU if accepted by the TinyLfu admission policy", Caffeine wiki).

Fig. 3: the same 17 requests through LRU and LFU, four keys each

  1. Two caches of four keys, the same requests. Front: LRU, ordered by last use (newest on the left; the next victim on the right, underlined). Back: LFU, each box as tall as its uses. A is Main_Page, B Special:Search, C Featured_pictures, three of the real hour's most viewed pages (section 1); s1 to s4 are pages read once, as 55% of that hour's pages were. The order of requests is illustrative.
  2. Warm-up: nine requests for the popular three. A four times, B three, C twice: three first-time misses, then six hits in both caches. LRU reorders on every hit; LFU's boxes grow.
  3. A scan of four one-off pages. Each misses in both. LRU makes room by evicting its least recently used key, and after four newcomers A, B and C are all gone. LFU evicts the key with the fewest uses: each newcomer (one use) evicts the previous one, and the popular three stay.
  4. The popular pages return. A, B, C, A: LRU misses three and hits one; LFU hits all four. Over the 17 requests LRU hit 7 and LFU 10: recency forgets steady favourites after one scan.
  5. What Redis does instead. Neither queue exists in Redis: it samples a few keys (maxmemory-samples, default 5) and evicts the best candidate among them, and its LFU counts are 8-bit counters that decay, so yesterday's favourite can leave. Measured below on the real hour, LFU still beat LRU by 10.1 points at 50,000 keys, and sampled LRU stayed within 2.0 points of exact LRU.

Two settings, and the default that bites

maxmemory caps the memory Redis uses for data; maxmemory-policy chooses the victim. Out of the box, maxmemory is 0 (no limit on 64-bit systems, so Redis grows until the machine runs out of memory) and the policy is noeviction: "The default is: maxmemory-policy noeviction" (redis.conf, 8.8). With a limit and that policy, a full Redis returns an error on every write that needs memory. For a cache, set both:

# redis.conf for a pure cache (Redis 8.8). Leave room for replication and persistence buffers,
# which are not counted in maxmemory (Redis key eviction docs).
maxmemory 6gb
maxmemory-policy allkeys-lfu        # or allkeys-lru; see the measurements below
maxmemory-samples 5                 # default; 10 is closer to exact at more CPU
save ""                             # a cache usually needs no snapshots: it can be refilled
appendonly no

Memory per key is more than the value. One cache-aside key with a 100-byte value cost 159 bytes here measured (key, hash-table entry and allocator overhead), and a TTL adds more: size maxmemory from the measured cost of your own keys, not from the values.

None of the policies is exact (Redis samples keys), and a volatile-* policy with no TTLs set behaves like noeviction, the classic 3 a.m. outage measured below.

How Redis approximates LRU and LFU, and the volatile-* trap (depth)

None of the policies is exact. Exact LRU would need a linked list updated on every read; Redis instead "samples a small number of keys at random and then evicts the ones with the longest time since last access", keeping a small pool of good candidates between evictions (Redis key eviction). LFU keeps 8 bits per key (a Morris counter: incremented with a probability that falls as it grows, so 255 can stand for about a million hits at the default lfu-log-factor 10) combined "with a decay period so that the counter is reduced over time" (lfu-decay-time 1: one minute). And a volatile-* policy with no TTLs set "behave[s] like noeviction" (docs): the classic 3 a.m. outage, measured below.

The menu: all ten policies, including the 8.6 LRM ones (reference)
PolicyVictimUse it when
noeviction (default)None: writes that need memory failRedis is a store of record (queues, counters you cannot lose), never for a cache
allkeys-lruLeast recently used key, approximatelyA pure cache; the docs call it "a good default option"
allkeys-lfuLeast frequently used, with counts that decay (since 4.0)A pure cache whose popular set is stable
allkeys-lrm (new in 8.6)Least recently modified: only writes refresh the timestampData refreshed by writes, where an unwritten key is stale however often it is read; not for cache-aside
allkeys-randomA random keyEvery key equally likely to be read (rare); a baseline
volatile-lru, volatile-lfu, volatile-lrm (8.6), volatile-randomAs above, but only among keys that have a TTLOne Redis holding both cache keys (with TTLs) and keys that must stay; the docs suggest two instances instead
volatile-ttlThe key whose TTL ends soonestYour code sets short TTLs on keys that are good victims

Measured: hit ratio by policy and memory, on real traffic

Redis 8.8 on the laptop; a client replays 2,000,000 requests as cache-aside (GET; on a miss, SET a 100-byte value); hit ratio counted after the first 500,000 have warmed the cache measured. Memory is set to hold about 20,000 to 200,000 keys. Five workloads: the real Wikipedia hour, six real hours with drifting popularity, and Zipf at α 0.7, 0.9 and 1.1. Each also shows exact LRU and Belady's OPT (evict the key whose next use is furthest in the future: the best any policy could do, knowable only offline), simulated on the same requests. Predict first: on the real hour, does LFU or LRU win, and by how much?

What the runs show. LFU beat LRU in 19 of 20 workload and size pairs (on the real hour by 10.1 points at 50k keys), because these traces have steady popularity. The 8.6 allkeys-lrm policy behaved like random eviction, as it must for cache-aside: a key is written once, at fill, so "least recently modified" means "filled longest ago". Redis's sampled LRU stayed within 2.0 points of exact LRU. The offline optimum hits 55.1% at 50k keys against 39.4% for the best Redis policy, and 36.5% of all requests were first-ever requests no policy can serve. noeviction looked fine on hit ratio while 781,318 SETs failed with an out-of-memory error.

Every finding with its numbers, computed from the runs (depth)

The findings, written by script from the run data so prose cannot drift (the Cache lab adds FIFO, which evicts the oldest entry regardless of use; it is the one classic policy where more memory can give fewer hits, Belady's anomaly, Belady, Nelson and Shedler, CACM 1969):

    Caveat on the real traces: inside each hour the order is random (the source has hourly counts, not timestamps), so the short-term bursts that favour LRU in live traffic are missing; the six-hour trace keeps the slower drift. On live traffic with strong bursts, LRU can close the gap or overtake, which is why the advice is to try both on a replay of your own traffic. Every run at every memory size, with the cost-weighted view of section 6, is in the Cache lab.

    LFU beat LRU on real traffic, and both sit far below the offline optimum

    Hit ratio over requests 500,001 to 2,000,000; x axis: keys the memory limit holds. Every point is one real run (measure/m_evict.py); dashed lines are exact simulations (measure/m_sim.py). At 50,000 keys on the real hour, LFU led LRU by 10.1 points.

    Redis, Valkey or Memcached (comparison)

    All three hold keys and values in memory behind a network protocol, and any of them is a fine cache. They differ in what else they do:

    Memcached 1.6Redis 8 / Valkey 9
    ValuesOpaque bytes with an expiry; get, set, delete, increment, compare-and-swapStrings plus hashes, lists, sets, sorted sets, streams; Redis 8 adds JSON, vector sets, search and time series
    ThreadsMultithreaded: "By default 4 threads are allocated" (memcached wiki)Commands run one at a time on one thread (so each command is atomic); network I/O can use extra threads (io-threads; Valkey 8 reworked this, see its 1 million requests a second post)
    MemoryA slab allocator: memory in 1 MB pages split into fixed-size chunks per size class, each class with its own LRU (memcached internals), a segmented LRU (hot, warm, cold) since 1.5 (memcached blog)One heap; the ten policies above
    Durability, replicationNone in the server: a restart empties itOptional snapshots and an append-only file; asynchronous replicas (acknowledged writes can be lost on failover: measured on NoSQL in practice)
    Scaling outClients hash each key to a server; servers never talk to each otherCluster mode: 16,384 hash slots spread over primaries
    LicenceBSD 3-ClauseRedis: your choice of RSALv2, SSPLv1 or AGPLv3 from 8.0; Valkey: BSD 3-Clause fork of Redis 7.2.4 (Linux Foundation, 2024)

    Versions and licences as in the root's Database atlas tab (Redis 8.10.2 of 17 September 2026 is the latest there; this page measured 8.8.0, the conda-forge build).

    How to choose. If you already run Redis or Valkey for anything else (rate limits, queues, sessions, leaderboards), use it for caching too: one fewer system. Memcached remains a good choice for a pure, very large cache of opaque blobs where multithreading per box and the absence of persistence are features. Most new systems pick Redis or Valkey; managed services (Amazon ElastiCache, Google Memorystore) offer both.

    6. What a hit is worth: hit-rate arithmetic and the cost of a miss

    With λ reads a second and hit ratio h, the database sees (1 − h) × λ. So going from 90% to 99% hits looks like a 9-point gain but divides the database's read load by ten (1,000 reads a second become 100, then 10). Mean latency is h × tcache + (1 − h) × (tcache + tdb). Predict: at the defaults the database is comfortable; what happens to it if the cache restarts empty? Then drag.

    Three consequences. The tail is the miss path: at a 95% hit rate the p99 is a database read however fast the cache is, so a cache improves the median far more than the p99. The cache has become capacity: when it empties (a restart, a failover, a deploy that changes every key) the full load lands on a database sized for a fraction of it; Facebook keeps spare "Gutter" servers, about 1% of the memcached fleet, to take a failed server's keys rather than let its misses reach the databases (Nishtala et al.). Warm up before taking traffic: fill a new cache from the old one, or ramp traffic (section 8 measures the same cold start inside Postgres). The queueing behind "more than it can take" is on Capacity planning and performance.

    The database is sized for the misses, so an empty cache sends it more than it can take

    Demand 1,000 reads a second against a database that answers about 600 (illustrative, the system design root's Step 2 example); tcache = 0.060 ms (Redis GET) and tdb = 10.8 ms (the usage aggregate below), both measured here on loopback. Formulas checked in recompute.py.

    Not every miss costs the same

    A miss on "chat 42 by its id" costs Postgres 0.189 ms; a miss on "this user's token usage by model" costs 10.8 ms (medians over random keys on the root's 10-million-message database, client round trips over a local connection) measured; a Redis GET took 0.060 ms on the same machine. Caching the first saves almost nothing (a Redis round trip costs about as much as the query); caching the second saves 182 times the cost of the lookup. A cache that hits 95% of cheap requests and misses every expensive one has a beautiful hit ratio and saves the database almost nothing. So count work saved:

    CWHR = Σhits cost(miss avoided) / Σall requests cost(miss)
    cost
    what a miss on that request would cost: backend milliseconds, database CPU, or dollars
    CWHR
    the cost-weighted hit ratio: the share of backend work the cache removed; equal to the hit ratio only when every miss costs the same

    In the Redis runs of section 5, one key in ten was marked expensive at random (independent of popularity), so CWHR equals the plain hit ratio up to noise: no Redis policy knows what a miss costs. A cost-aware policy does. GreedyDual (Young 1994; with sizes, Cao and Irani, USENIX 1997) gives each entry a priority of "L + the cost of missing it"; the victim is the lowest priority, and L rises to each victim's priority, so cheap entries leave first and expensive ones leave only when they stop being used. On the same Wikipedia requests with the measured costs simulated, not a Redis policy, it gives up plain hits and saves the most work:

    Redis has no such policy, so production systems get the same effect by hand: separate pools (Facebook: "a small pool for keys that are accessed frequently but for which a cache miss is inexpensive", and "a large pool for infrequently accessed keys for which cache misses are prohibitively expensive"; in Redis terms, two instances, so cheap churn cannot evict expensive results); longer TTLs for expensive results, or caching only results above a cost threshold (do not cache a 0.07 ms lookup at all); and precomputing the expensive ones (a materialised view, section 8). For an LLM cache the cost has an exact money form (section 11).

    What to put on the cache dashboard (reference)

    What to put on the dashboard (Redis's INFO stats exposes the first three): hits and misses (keyspace_hits, keyspace_misses); evicted_keys next to expired_keys (many evictions: memory too small or wrong policy; many expiries: TTL too short); latency split by hit and miss; database load with and without the cache; and the number of distinct keys, whose unbounded growth means a timestamp or request id got into a key.

    7. TTLs, jitter and stampedes: when a popular copy expires

    Choosing a TTL. A TTL is the staleness you accept, stated in seconds: the bound on how long a forgotten invalidation can last and on how long an un-invalidated copy can lie. Short TTLs cost misses; long ones cost staleness. Per-user data that is hot only during a session fits minutes; shared reference data that is invalidated explicitly can carry hours, with the TTL as the backstop.

    Jitter. Entries written together with the same TTL expire together: a deploy that refills 10,000 hot keys in the same second sends their next reads to the database in the same second, 300 s later. Adding a random extra 0 to j% to each TTL spreads those expiries over 300 × j seconds. Drag the jitter:

    Ten per cent of jitter turns one spike of 10,000 expiries into a plateau the database can absorb

    10,000 keys filled at t = 0, TTL 300 s plus a uniform random 0 to j% illustrative. Peak expiries per second = keys / (300 × j), derived; each becomes a database query on its key's next read. The 600 a second line is the same illustrative database as in section 6. TTL jitter is common advice (a random 0 to 10%), not from a single source.

    Stampedes. A stampede (dog-piling, a thundering herd) is one hot key expiring: every request that arrives before someone has rebuilt it misses and rebuilds it too. If the rebuild takes 300 ms and the key is read 200 times a second, 60 requests run the same expensive query at once, which makes the query slower, which widens the window. Facebook measured it: "Without leases, all of the cache misses resulted in a peak database query rate of 17K/s. With leases, the peak database query rate was 1.3K/s" (Nishtala et al.). Predict: which defence sends the database one query and makes no request wait?

    1. Request coalescing (single-flight): the first miss rebuilds; the others wait for its answer (Go's singleflight, nginx's proxy_cache_lock on; Facebook's leases across servers, "a token only once every 10 seconds per key"). Cost: the waiters still wait for the rebuild.
    2. Serve stale while revalidating: keep the old value a little past its TTL and refresh in the background (Cache-Control: stale-while-revalidate=30, RFC 5861). Cost: a few seconds of staleness.
    3. Probabilistic early expiry (XFetch): each reader recomputes early with a probability that rises as expiry approaches and as the rebuild gets more expensive: recompute if now − Δ · β · ln(rand()) ≥ expiry, Δ the last rebuild's duration (Vattani, Chierichetti and Lowenstein, VLDB 2015, proved optimal; β = 1 "already provides effective prevention against cache stampedes"). Cost: one early rebuild per expiry and no locks; only the reader that refreshes waits.
    The defences in their sources' words, and a minimal single-flight for asyncio (depth)

    Facebook's other clients are told to "wait a short amount of time" and retry. Go's singleflight: "making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results" (golang.org/x/sync v0.23.0). nginx's proxy_cache_lock on: "only one request at a time will be allowed to populate a new cache element" (nginx proxy module); its stale-while-revalidate is proxy_cache_use_stale updating plus proxy_cache_background_update on.

    import asyncio
    _inflight: dict[str, asyncio.Future] = {}
    
    async def get_coalesced(key, load):
        if (fut := _inflight.get(key)) is not None:
            return await fut                   # someone is already loading this key: share their answer
        fut = asyncio.get_running_loop().create_future()
        _inflight[key] = fut
        try:
            value = await load(key)            # the one real database call
            fut.set_result(value)
            return value
        except Exception as e:
            fut.set_exception(e)               # waiters get the error too, not a hang
            raise
        finally:
            del _inflight[key]

    Per process only: 8 servers can still send 8 queries. Route each key to one server (consistent hashing) or coalesce in the shared cache (a short lock key with SET key NX PX 3000, as the lease of section 3 does) to go further.

    One expiry, four defences: only the unprotected cache sends 60 queries for one key

    served fresh from cachemissed and queried the databasewaited for another request's rebuildserved the old value

    The model (ported from Capacity planning and performance's model.py, stampede, plus a serve-stale mode): one key read 200 times a second, expiring at t = 1 s, rebuilt by a 300 ms database query; XFetch with β = 1 and Δ = 300 ms on a seeded random draw (seed 5) illustrative rates. The counts (60, 1, 1, 1 database queries) are checked in recompute.py.

    8. Postgres's own caches: pages yes, results no, and three tools in between

    Postgres caches pages (the buffer pool over the operating system's page cache: Storage engines and indexes, section 2), query plans for prepared statements, and catalog data. It does not cache query results: run the same aggregate twice and it is computed twice, from cached pages. MySQL had a query result cache and removed it in 8.0, because invalidating every cached result that touched a table on every write to it scaled badly under concurrency (MySQL Server blog, 2017). Before reaching for Redis, three tools inside the database.

    A materialised view, for expensive aggregates

    A materialised view is a query whose result Postgres stores as a real table, with its own indexes. A view of daily token usage per user and model on the root's chat data (10 million messages) measured:

    CREATE MATERIALIZED VIEW daily_usage AS
      SELECT c.user_id, m.created_at::date AS day, m.model, sum(m.tokens) AS tokens, count(*) AS n
      FROM messages m JOIN chats c ON c.id = m.chat_id GROUP BY 1, 2, 3;
    CREATE UNIQUE INDEX daily_usage_key ON daily_usage(user_id, day, model);   -- needed for CONCURRENTLY

    The catch is the one this page keeps returning to: the view is a copy. After a new message was inserted, the view still showed user 1's old total (2,414,930 tokens against 2,415,707 in the live tables) until REFRESH MATERIALIZED VIEW recomputed it from scratch in 14.8 s. A plain refresh takes a lock that blocks readers: a query on the view issued one second into the refresh waited 13,809 ms. REFRESH MATERIALIZED VIEW CONCURRENTLY builds the new result beside the old one and applies the difference, "without locking out concurrent selects" (Postgres docs); it needs a unique index, took 90.3 s, and the same reader waited only 3.9 ms.

    When to use it: dashboards and reports that tolerate staleness you can state ("usage as of the last 10-minute refresh"), refreshed by a scheduler (cron, pg_cron).

    When not, and what to use instead (depth)

    When not: data a user expects to see change immediately, or a base table so large that a full recompute every few minutes costs more than it saves; then maintain a summary table incrementally (a trigger or the application adds each new message to its day's row), or use a system that maintains views incrementally (ClickHouse materialised views run on every insert; Materialize is built around it). Postgres itself has no incremental materialised views.

    pg_prewarm, for the cold start after a restart

    A restart empties shared_buffers, so the database is slowest exactly when traffic returns; measured here, the first lookups after a restart read their blocks at SSD speed, and pg_prewarm (or its autoprewarm worker) made them run at the warm speed from the first request. The same holds for a restarted Redis.

    pg_prewarm measured: 20,000 lookups after a restart (depth)

    A restart empties shared_buffers, and on a real server, whose OS page cache a reboot also empties, every first miss is an SSD read: the database is slowest exactly when traffic returns. pg_prewarm loads a table or index into the buffer pool on demand, and with shared_preload_libraries = 'pg_prewarm' a background worker "periodically records the contents of shared buffers in a file called autoprewarm.blocks and will, using 2 background workers, reload those same blocks after a restart" (pg_prewarm docs). 20,000 random chat lookups after a restart measured:

    With track_io_timing = on, the first pass read 10,247 blocks in 870 ms, about 85 microseconds each, which is SSD speed: those blocks were in neither cache. After pg_prewarm or an autoprewarm restart, the same lookups ran at the warm speed from the first request. The same holds for Redis: a restarted cache is empty, and the database must survive the miss rate until it refills (Facebook's cold clusters fill from a warm cluster first, "in a few hours instead of a few days").

    Memoize, a cache inside one query, measured (depth)

    Since Postgres 14 the planner can put a Memoize node above the inner side of a nested-loop join: when the same lookup value comes back (many messages of the same chat), the cached inner result is reused instead of probing the index again; "less commonly looked up results may be evicted" when its memory (work_mem times hash_mem_multiplier) fills (enable_memoize). On a query that looks up the owner of every chat belonging to the 30 heaviest users (6,250 chats, 30 distinct owners) measured:

    SELECT u.plan, count(*) FROM chats c JOIN users u ON u.id = c.user_id WHERE c.user_id <= 30 GROUP BY 1;

    When it runs, the cache works as designed: 30 index probes instead of 6,250. And the planner did not choose it: it built a hash table of all 100,000 users instead, 8.5 times slower here, because its cost model did not foresee that so few owners repeat so often (Memoize only appeared with hash and merge joins disabled, done here only to show the node). You cannot request Memoize directly; recognising it, and its absence, in an EXPLAIN plan is the skill, taught on Query planning and performance, and the usual fix for a misestimate is better statistics, not switching join methods off in production.

    9. HTTP caching and CDNs: the copies outside your servers

    Every HTTP response can say who may cache it and for how long, and browsers, reverse proxies (nginx, Varnish, Envoy) and CDNs obey the same headers (RFC 9111; MDN's HTTP caching guide is the readable version; header semantics are owned by HTTP). A CDN is a cache run for you in hundreds of cities: it serves static files and any public response marked cacheable, and its hit ratio is what you pay for, because every miss crosses the world to your servers (about 20 ms to an edge against 78 ms across the Atlantic on the ladder of section 2). CDNs collapse concurrent misses for the same URL into one request to you (the coalescing of section 7) and support stale-while-revalidate and stale-if-error. A reverse proxy in your own data centre can also be told to drop entries (Varnish has purging and banning); it spares the app servers on anonymous traffic and helps little once every response is personalised. The system-level decision is which response gets which policy; for the chat product:

    ResponseHeaderMeaning
    The app's JavaScript bundle, named by its content hash (app.3f9a1c.js)Cache-Control: public, max-age=31536000, immutableAnyone may cache it for a year and need not even revalidate (RFC 8246); a new release gets a new name, which is the only invalidation that reaches every browser
    The public model listCache-Control: public, max-age=60, stale-while-revalidate=300Fresh for 60 s; for 5 minutes after that a cache may serve the old copy while it fetches a new one in the background (RFC 5861)
    A user's conversation listCache-Control: private, no-cache plus ETag: "v7"Only the user's browser may store it, and must ask before each use; the browser sends If-None-Match: "v7" and gets 304 Not Modified (no body) if nothing changed
    A password reset pageCache-Control: no-storeNobody keeps a copy

    Three mistakes cause most HTTP caching incidents: a personalised response cached by a shared cache because it lacked private (one user sees another's page); a cache key that ignores a header the response depends on (fix with Vary, for example Vary: Accept-Encoding); and a long max-age on a URL whose content changes, which no purge can recall from browsers. s-maxage sets a lifetime for shared caches only. An ETag is a versioned key by another name: the server's version of the resource, compared on each request. For the chat assistant the CDN carries the app and static assets; conversations are personal and uncacheable at the edge.

    10. The LLM caches, first: the KV cache and prefix caching

    An LLM product has three caches a web product does not, and they differ in the property that matters most: can a hit return a wrong answer? The KV cache and prompt caching never change the answer; a semantic cache can.

    A transformer generates one token (a word piece) at a time, and every layer's attention needs a key and a value vector for each earlier token; servers keep those in GPU memory instead of recomputing them: the KV cache. It is never stale (the keys and values of a given prefix under a given model are fixed); its problem is size, which is why KV memory, not compute, usually caps how many conversations one GPU serves. Because attention is causal, two requests that start with the same tokens share those keys and values, so a server can keep them and skip that part of the prefill (the first pass over the prompt, which dominates time to first token): prefix caching, exact by construction. How big the cache is (bytes per token from a model's config, Llama 3.1 70B's 320 KiB per token, why decode is memory-bound) is taught from zero in sections 4 and 2 of Topic: inference-and-serving; how vLLM's hashed blocks (design doc) and SGLang's RadixAttention (LMSYS blog, January 2024) find a shared prefix, and which blocks to evict on a day of real traffic, in section 3 of Batching, KV cache and scheduling in depth, which replays the policies on a real trace.

    What a cache engineer takes from it: prefix caching dictates prompt layout. Stable content first (system prompt, tool definitions, documents), anything that changes per request last; one timestamp at the top of a system prompt makes every request a miss. ML system design animates one conversation under both layouts (section 6 there) and lists an LLM service's four caches (section 7); routing requests to the replica that holds their prefix is measured on real replicas in LLM serving in production, section 1.

    Owned elsewhere and linked: PagedAttention, KV quantisation (FP8 KV halves the bytes per token), offloading cold prefixes to CPU memory or SSD (LMCache, Mooncake, NVIDIA Dynamo) and cache-aware routing (Topic: inference-and-serving and its child Batching, KV cache and scheduling, sections 2 to 4); architectures that shrink the entry itself, such as DeepSeek-V3's multi-head latent attention, one 576-number vector per layer (68.6 KiB per token), on the DeepSeek page.

    11. Provider prompt caching: the same idea, sold by the token

    When you call a hosted model, the provider runs prefix caching for you and passes on part of the saving: input tokens read from its cache are billed at a fraction of the normal price, and the answer never changes. It is an ordinary cache with two twists. It lives on individual machines, so a hit needs the request to reach the machine holding the prefix: OpenAI's guide says cached states "live on individual machines, where traffic above 15 requests per minute can lead to overflow routing", and on models before GPT-5.6 a stable prompt_cache_key "helps optimize cache routing" for requests sharing a prefix (busy groups should "aim for about 15 requests per minute in total" per key and split higher volume across keys). It is scoped: "Caches are not shared across organizations" (OpenAI prompt caching, read 2026-10-05), which also closes the timing side channel a shared prefix cache would open.

    The rules that decide whether a request hits (Anthropic's tools, system, messages order and what invalidates each level, breakpoints and the 20-block lookback, minimum lengths, lifetimes, the usage fields that report a hit, and OpenAI's and Gemini's versions) are owned by Context engineering, section 2; Anthropic's prices and what caching does to a Claude agent's bill by the Anthropic provider page. This section keeps the arithmetic that holds for every provider.

    Break-even: does caching pay?

    With a write multiplier w (what writing a prefix costs, relative to sending it normally) and a read multiplier r, a prefix used n times costs w + r(n − 1) with caching against n without. Caching pays once

    n > 1 + (w − 1) / (1 − r)
    Correction to the old page
    The old page said Anthropic's caching breaks even at "roughly 1.3 reads inside the TTL". With w = 1.25 and r = 0.1 the break-even is n = 1 + 0.25 / 0.9 = 1.28 total uses: one write plus a single read (2 uses: 1.35 against 2.00) already saves 32.5%. OpenAI's own guide gives the same arithmetic: "writing a prefix once and fully reusing it once costs 1.35× its ordinary input cost, compared with 2×". The old page also said OpenAI has no write surcharge: true for models before GPT-5.6, but GPT-5.6 and later charge 1.25× for writes. And the read multiplier is no longer 0.1× everywhere: Anthropic bills reads at 0.05× on Claude Opus 5.5 and 0.025× on Fable 5.1 and Mythos 5.1; OpenAI at 0.05× on GPT-6.1 Sol.

    A longer lifetime raises w: Anthropic's 1-hour entries cost 2× to write, so with r = 0.1 the break-even is n = 1 + 1 / 0.9 = 2.11 uses, one write plus two reads (the 5-minute entry pays after one read). Batch APIs cut the price again and the discounts multiply: Anthropic's batch rate is "50% of the standard API prices" and stacks with prompt caching (Anthropic batch processing).

    The cost-weighted hit ratio of section 6 has an exact form here: the share of the input bill removed is h × (1 − r), less the write premium, so 90% of input tokens read from cache at 0.1× removes 0.9 × 0.9 = 81% of the input bill before writes. Verify, never assume: every response reports what it read from cache (field names per provider in Context engineering, section 2).

    Dated price table and a break-even calculator for each model (read 5 October 2026) (volatile)

    Prices as of 5 October 2026, from each provider's documentation. They change often: the Anthropic provider page records that Sonnet 5.5's cache reads were halved to $0.10 on 7 October, after this table was read.

    Input cost of the cached prefix only (the uncached suffix and the output cost the same either way). Gemini explicit caching adds a storage charge per million tokens per hour, shown for one hour. Prices from the table above; formula checked in recompute.py.

    12. Semantic caching: the only cache that can be wrong

    An exact cache matches keys byte for byte, which almost never fires on natural language: "What is your refund policy?" and "How do refunds work?" are the same question in different bytes. A semantic cache turns each incoming prompt into an embedding (a vector of a few hundred numbers from a small model, such that texts with similar meaning point in similar directions), finds the most similar stored prompt, and returns its stored answer if the cosine similarity (the cosine of the angle between the two vectors; 1 means the same direction) is above a threshold; otherwise it calls the model and stores the new pair. GPTCache made the design popular (repository; its README warns "you may encounter false positives during cache hits"); LiteLLM ships it as a proxy option (type: "redis-semantic" with similarity_threshold: 0.8, LiteLLM docs); Redis sells it as a service (LangCache, Redis, spring 2025 release). Every other cache on this page is exact, so a hit is provably the right answer; a semantic hit is a guess that two different questions deserve the same answer. That makes it a model-quality change disguised as an infrastructure change. Where it sits in an LLM gateway, beside exact response caching, is on Gateways and routing; this section owns how often it is wrong.

    Measured: hits against wrong answers as the threshold moves

    Two real labelled datasets and two small open embedding models, on the laptop's CPU measured: Quora Question Pairs (the GLUE validation split: 40,430 pairs of real user questions, 37% labelled duplicates by people; dataset), whose non-duplicates are hard on purpose (same topic, different answer: exactly the near misses a cache must refuse); and PAWS (8,000 pairs built by swapping or copying words, so almost every pair shares nearly all its words; 44% are paraphrases; dataset). Models: all-MiniLM-L6-v2 (22.7 million parameters, 6.6 ms to embed one query on two CPU threads) and BAAI bge-small-en-v1.5 (33.4 million, 15.1 ms). For each pair the cache holds the first question and the second arrives as a query: served if their similarity reaches the threshold, and right only for a duplicate. True-hit rate: the share of duplicates served; false-hit rate: the share of non-duplicates served.

    Predict: on Quora pairs with MiniLM, is there a threshold that serves most true duplicates while serving almost no wrong answers? Move the threshold; then set the share of questions that truly repeat to your own traffic's.

    • No safe and useful threshold on these models. MiniLM at 0.90 serves 42% of true duplicates and 6% of the hard non-duplicates; at 0.95 the false hits fall to 2% but only 21% of duplicates hit.
    • Thresholds do not transfer between models. bge-small scores everything higher: its false-hit rate at 0.90 is 11%, against MiniLM's 6%. A threshold copied from a blog post written for another model means nothing.
    • Word swaps defeat both. On PAWS, where the non-paraphrases use the same words in a different order, MiniLM at 0.95 serves 77% of the pairs whose meaning differs: these models encode which words appear far more than how they relate.
    • Against a full store, the picture holds: with 10,000 Quora questions stored (MiniLM, 0.90), 25% of queries were served: 14% by their own labelled duplicate (right), 4% by their own labelled non-duplicate (wrong), 7% by another stored question with no label. Most unlabelled matches are the same question asked twice on Quora (examples in the 10,000-entry view above), so labelled numbers understate correct hits a little; the wrong share remains.

    No threshold is both safe and useful on these models, and the wrong share grows as true repeats get rarer

    true-hit rate (duplicates served)false-hit rate (non-duplicates served)share of served answers that are wrong, at your traffic mix
    served, rightserved, wrongnot served: model called
    Put a price on it: the cost of a model call and of a wrong answer (optional)

    Value per 1,000 queries = 1,000 × (served × call cost − wrong × wrong-answer cost), ignoring the embedding and lookup cost (6.6 ms with MiniLM and 15.1 ms with bge-small per query here). Costs are yours to set illustrative.

    A real cache looks up the nearest of many entries: the 10,000-entry view at this threshold (depth)

    The first questions of 10,000 Quora pairs stored, every second question looked up against all of them (top 1), at the threshold above:

    Formulas: served = p × TPR + (1 − p) × FPR; wrong = (1 − p) × FPR, with p the true-match share you set and TPR, FPR the measured pair rates at the threshold (every threshold from 0.50 to 1.00 in steps of 0.01, measure/m_sem.py, inputs/sem.json). Mixing measured rates with a chosen p is a model of traffic, not a measurement of it. The default p = 37% is Quora's own duplicate share.

    Hand-written pairs illustrative inputs, similarity measured with all-MiniLM-L6-v2: one or two changed tokens flip the answer while the cosine barely moves

    The pattern is structural, not a tuning problem: negation ("safe" against "unsafe"), direction ("from New York to Paris" against "from Paris to New York"), quantifiers ("under" against "over 100 dollars") and qualifiers ("after it has shipped") change the answer while changing one or two tokens, and contribute little to an averaged sentence vector, while two genuinely equivalent phrasings with different words can score lower. A threshold cannot separate them. The same failure inside a retrieval system, where claims with opposite verdicts are more similar to each other than claims that agree, is measured in section 8 of RAG in production.

    On other traffic the curve can look far kinder (published sweeps below): it is a property of your traffic and your model, so measure your own.

    What published measurements say: AWS, a 97% study, vCache, and a correction (depth)

    On other traffic the curve can look far kinder, which is the lesson: it is a property of your traffic and your model. AWS's test on chatbot queries (Claude 3 Haiku answers, Titan embeddings), as reported by Portkey (Portkey, semantic caching thresholds): threshold 0.99, 23.5% hits at 92.1% accuracy; 0.95, 56.0% at 92.6%; 0.90, 74.5% at 92.3%; 0.80, 87.6% at 91.8%; 0.75, 90.3% at 91.2%: accuracy barely moved. One study of a semantic cache for LLM queries reports hit rates of 61.6 to 68.8% with "positive hit rates exceeding 97%", roughly 3% of hits wrong (GPT Semantic Cache, arXiv 2411.05276). Portkey's advice is to start between 0.90 and 0.95, build a validation set with "queries that look similar but should produce different answers", and treat a false-positive rate above roughly 3 to 5% as the limit of the embedding model, not of the threshold. Research systems learn the threshold instead: vCache finds a single static threshold gives "unexpected error rates", learns one per cached prompt, and reports "up to 12.5× higher cache hit and 26× lower error rates" (arXiv 2502.03771).

    Correction to the old page
    The old page attributed "start near 0.95" to Portkey; its current post says "Start with a threshold between 0.90 and 0.95". The AWS figures it quoted are confirmed in Portkey's post (a secondary report of AWS's test).

    How to run one safely, if you must

    It works best on high-volume, low-variance, factual traffic (FAQ-style support questions, documentation lookups, classification prompts) and badly on open-ended generation, agent steps, or anything where users expect a fresh answer.

    1. Try the exact caches first: prompt caching (section 11), an exact-match cache on the normalised request (tenant, model, full prompt, temperature, tools), caching retrieval results and embeddings of repeated documents.
    2. Scope the key: tenant, user where answers are personal, model and prompt version, and the retrieved context. "What is my balance?" from two users is the same text with different answers, and a cache shared across tenants can hand one customer another's answer. Never cache answers that depend on live state (stock, balances, order status) or on time ("current pricing").
    3. Verify before serving: require extracted entities, numbers and dates to match exactly; or re-rank the top few candidates with a cross-encoder or a small judge model instead of trusting one cosine score.
    4. Measure your own curve: a few thousand real queries with a no-cache baseline, replayed through the cache, judged; plus a deliberate slice of near-miss pairs from your domain, which the natural distribution under-represents.
    5. In production: log the similarity of every hit, audit a sample of hits, alert on the false-hit rate as a service level objective, and keep a kill switch. When the knowledge behind the answers changes, version the cache namespace (a reindex invalidates everything at once) or tag entries with the documents they came from.

    Choosing: which cache, in which order

    For the chat product, from cheapest and safest to riskiest; each step is worth doing before the next.

    1. Make the database fast without a cache. Indexes, fewer queries per request (no N+1), enough RAM for the working set (Query planning and performance). A missing index is not a caching problem, and every cache you do not add is an invalidation bug you do not have.
    2. Cache what never changes, far out. Static assets with content-hashed names and a year-long max-age on a CDN (section 9).
    3. Use provider prompt caching, always. Put the stable prompt first, check the cached-token fields, and remember that one reuse already pays (section 11). In your own serving stack, prefix caching is on by default in vLLM and SGLang (section 10).
    4. Add a shared cache for expensive, read-heavy, shared results: Redis or Valkey with maxmemory and maxmemory-policy set on purpose (allkeys-lfu or allkeys-lru), the hit ratio watched next to the eviction count; a TTL on everything that states the staleness you accept, in seconds, even where explicit invalidation exists; delete after the commit, never before, and never update the cache on write; leases or versioned keys where a stale value would hurt (sections 3 to 5). Weigh by cost: skip cheap primary-key lookups (section 6). Jitter TTLs and coalesce rebuilds of hot keys (section 7).
    5. Precompute heavy aggregates in a materialised view or a summary table instead of caching each answer (section 8).
    6. An in-process cache in front of the shared one only for a few very hot keys, with a short TTL (section 2).
    7. A semantic cache last, and only after an evaluation on your traffic, scoped per tenant and user, with its false-hit rate monitored (section 12).

    Throughout: the system must stay correct with the cache empty, and the database must survive the load of a cold cache (warm it, or ramp traffic: sections 6 and 8).

    What teams run in production (October 2026) (reference)
    • Python services: redis-py (8.x) or valkey-py clients with connection pools and timeouts of tens of milliseconds, so a slow cache degrades into misses rather than stalling requests; cachetools (TTLCache) for in-process caches; TTL jitter (a random extra 0 to 10%) so keys written together do not expire together.
    • Java services: Caffeine (W-TinyLFU) in process, Redis or Memcached behind it.
    • Managed: Amazon ElastiCache (Valkey, Redis OSS or Memcached), Google Memorystore; replicas for availability, not for correctness.
    • Invalidation at scale: deletes driven by the database's change stream (Debezium reading Postgres logical replication, or an outbox), Facebook-style, with TTLs underneath.
    • LLM products: prompt layout reviewed like an API (stable prefix, append-only history), cache-hit rate and cached-token cost on the main dashboard, exact-match caching of deterministic calls, semantic caching rarely and narrowly.

    Common mistakes

    Each is a real failure mode; the measured ones were run on this page.

    Caching to hide a slow query
    The miss path stays slow, the p99 is the miss path, and a cold cache brings the whole load back. Fix the query or the index first.
    Deleting the cache key before the commit
    A reader between the delete and the commit refills the old row for the whole TTL. Commit, then delete (in an after-commit hook if you use an ORM).
    Updating the cache on write instead of deleting
    Two writers can land in the cache in the opposite order from the database. Measured: 36% of trials ended wrong.
    No TTL because "we invalidate explicitly"
    Some path will forget (a script, a migration, a new service). The TTL is the upper bound on how long that bug lasts.
    Leaving Redis at its defaults
    maxmemory 0 grows until the machine swaps or the process is killed; with a limit, noeviction turns a full cache into write errors (measured: 781,318 failed SETs in one run).
    A volatile-* policy with keys that have no TTL
    Nothing is eligible, so it behaves like noeviction: measured, 1,328,877 failed SETs, against 0 once every key had a TTL.
    Choosing allkeys-lrm for a read-through cache
    LRM only notices writes, and cache-aside writes a key once, when it is filled; so LRM evicts by fill time, like FIFO, ignoring how often the key is read. Measured, it did no better than random eviction.
    Letting requests for missing keys through every time
    A key that does not exist in the database is never cached, so every request for it reaches the database (cache penetration, often a bot probing ids). Cache the "not found" answer with a short TTL, or keep a Bloom filter of keys that exist.
    One hot key on one shard
    A cluster spreads keys, not load: one celebrity chat or one shared prompt key lives on one Redis primary, which saturates while the rest idle. Put the few hottest keys in an in-process cache in front, or copy one key under several names (key:0 to key:7) and read a random copy, which multiplies the writes. Find them first: redis-cli --hotkeys (it needs an LFU policy).
    Reading the hit ratio alone
    Weight hits by what the miss costs (section 6), and watch evictions, expiries and latency on the miss path.
    Filling the cache from a replica right after a write
    Milliseconds of replication lag become a TTL of staleness. Fill from the primary for keys just written, or route the writer's reads to the primary briefly.
    Caching personalised responses in a shared cache
    A CDN or reverse proxy serves user A's page to user B. Mark them Cache-Control: private, and put user and tenant in every application cache key that depends on them.
    A timestamp at the top of the prompt
    Every request differs from the first token, so provider prompt caching never hits and the bill does not fall. Volatile content goes last.
    Copying a semantic-cache threshold
    Measured here, the same 0.90 meant 6% false hits with one model and 11% with another. Fit it on your own labelled traffic.
    Benchmarking with a warm cache and quoting the result as typical
    Report cold and warm runs separately, and say which; the root's Query plans tab shows the difference on real plans.
    Glossary: every term this page defines, linked to where it is explained (reference)
    Measured on 5 October 2026 on an Apple M1 Pro laptop (16 GB, macOS) with Redis 8.8.0 (conda-forge, in a scratch directory), PostgreSQL 16.2 (the pgserver wheel's build with the pg_buffercache and pg_prewarm modules compiled against it) on a copy of the root's 10-million-message chat database, sentence-transformers with all-MiniLM-L6-v2 and bge-small-en-v1.5 on CPU, and public data (Wikimedia pageviews of 15 September 2026; GLUE QQP and PAWS). Each measurement script runs in under 10 minutes; the scripts and raw outputs are in the page's src/measure and src/inputs folders. Prices and limits are from the providers' documentation read on 5 October 2026 and change often: check before budgeting.