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
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.
| Question | Short 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 once | 1 |
| 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 invalidate | 2 |
| 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 0 | 3 |
| 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 fix | 4 |
| 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 cache | 5 |
| 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 query | 6 |
| 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 XFetch | 7 |
| 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 refresh | 8 |
| 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 answer | 10 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).
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.
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.
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.
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.
Four things change as you move outward:
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.
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 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).
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.
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).
| Pattern | On a read | On a write | Trade-off |
|---|---|---|---|
| Cache-aside (lazy loading) | App checks the cache; on a miss it reads the database and fills the cache | App writes the database, then deletes the cache entry | The default. Simple, caches only what is read; the first read after a change is slow |
| Read-through | The cache library loads missing entries from a function you give it | As cache-aside | Same behaviour, less app code; the loader is one place to add coalescing (section 7) |
| Write-through | As cache-aside | Write cache and database together, synchronously | Reads after writes are fresh; every write pays twice, and you cache data nobody may read |
| Write-behind (write-back) | From the cache | Write the cache now, flush to the database later in batches | Fast writes, absorbs bursts; a cache crash loses acknowledged writes. Rarely right for user data |
| Write-around | As cache-aside | Write the database only; let the entry expire | For 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 copyAda 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.
| Method | How it works | What it costs | When not to use it |
|---|---|---|---|
| TTL | Every 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 changed | Alone, for anything a user just changed and expects to see (read-your-writes) |
| Explicit delete | The code that writes Postgres deletes the cache key right after the commit | The 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-driven | Postgres's change stream (logical replication, read by a tool such as Debezium) or an outbox table feeds a consumer that deletes affected keys | A pipeline to run; at-least-once delivery and lag of its own; still needs a TTL | Small systems with one writer path: explicit delete is simpler |
| Versioned keys | The key contains a version (chat:42:v7); a write bumps it, so readers stop asking for the old key, which ages out | One extra lookup for the current version; old entries use memory until evicted | When 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).
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 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
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.
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()}"
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:
| Window | How it opens | How long it lasts | Fix |
|---|---|---|---|
| Between the commit and the delete | Readers between the writer's two steps get the old cached value | Microseconds to milliseconds | Accept 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 fills | The whole TTL | Always commit first, then delete; in an ORM, delete in an after-commit hook, not inside the transaction |
| Write-through before the commit | The writer sets the cache, then the transaction fails or rolls back | The whole TTL, for a value that never existed | Never 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 delete | The whole TTL | Leases or versioned keys |
| Fill from a lagging replica | The reader's miss goes to a read replica that has not yet received the write, and caches the old value | The whole TTL: the cache turns milliseconds of replication lag into minutes of staleness | Fill from the primary for keys just written, or mark "recently written" (Facebook's remote markers, below) |
| A lost or late invalidation | The delete is dropped (a crash between commit and delete) or the event pipeline lags | Until the TTL, or until the pipeline catches up | The TTL backstop; an outbox or change data capture makes the delete durable |
| Write-behind | Anything that reads Postgres directly (analytics, other services) sees old data; a cache crash loses acknowledged writes | Until the flush, or forever | Use 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 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.
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
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.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.
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.
| Policy | Victim | Use it when |
|---|---|---|
noeviction (default) | None: writes that need memory fail | Redis is a store of record (queues, counters you cannot lose), never for a cache |
allkeys-lru | Least recently used key, approximately | A pure cache; the docs call it "a good default option" |
allkeys-lfu | Least 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 timestamp | Data refreshed by writes, where an unwritten key is stale however often it is read; not for cache-aside |
allkeys-random | A random key | Every key equally likely to be read (rare); a baseline |
volatile-lru, volatile-lfu, volatile-lrm (8.6), volatile-random | As above, but only among keys that have a TTL | One Redis holding both cache keys (with TTLs) and keys that must stay; the docs suggest two instances instead |
volatile-ttl | The key whose TTL ends soonest | Your code sets short TTLs on keys that are good victims |
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.
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.
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.
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.6 | Redis 8 / Valkey 9 | |
|---|---|---|
| Values | Opaque bytes with an expiry; get, set, delete, increment, compare-and-swap | Strings plus hashes, lists, sets, sorted sets, streams; Redis 8 adds JSON, vector sets, search and time series |
| Threads | Multithreaded: "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) |
| Memory | A 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, replication | None in the server: a restart empties it | Optional snapshots and an append-only file; asynchronous replicas (acknowledged writes can be lost on failover: measured on NoSQL in practice) |
| Scaling out | Clients hash each key to a server; servers never talk to each other | Cluster mode: 16,384 hash slots spread over primaries |
| Licence | BSD 3-Clause | Redis: 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.
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.
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.
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:
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 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.
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:
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?
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.Cache-Control: stale-while-revalidate=30, RFC 5861). Cost: a few seconds of staleness.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.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.
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.
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 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: 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.
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.
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").
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.
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:
| Response | Header | Meaning |
|---|---|---|
The app's JavaScript bundle, named by its content hash (app.3f9a1c.js) | Cache-Control: public, max-age=31536000, immutable | Anyone 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 list | Cache-Control: public, max-age=60, stale-while-revalidate=300 | Fresh 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 list | Cache-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 page | Cache-Control: no-store | Nobody 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.
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.
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.
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
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).
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.
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.
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.
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.
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.
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.
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).
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.
For the chat product, from cheapest and safest to riskiest; each step is worth doing before the next.
max-age on a CDN (section 9).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).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).
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.Each is a real failure mode; the measured ones were run on this page.
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).noeviction: measured, 1,328,877 failed SETs, against 0 once every key had a TTL.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).Cache-Control: private, and put user and tenant in every application cache key that depends on them.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.Every number here comes from a real run: Redis 8.8 on a laptop replaying 2,000,000 cache-aside requests per run, hit ratio counted after 500,000 warm-up requests (section 5 of the Reading tab explains the setup). Policies marked "simulated" are exact algorithms run offline on the same requests for comparison; Redis does not offer them. The cost-weighted hit ratio uses the miss costs you set: one key in ten is expensive, chosen at random.
Try: the real hour at 50k keys, LRU against LFU; then Zipf α 1.1, where both hit about 85% and the gap almost closes; then GreedyDual, whose plain hit ratio is the worst of all and whose work saved is the best. Set both costs equal and the two ratios coincide.
Hit ratio by cache size for every policy on the chosen workload; the selected policy is drawn thick. Points are measured runs; dashed lines are exact simulations.
Bar: plain hit ratio; number on the right: hit ratio / cost-weighted hit ratio. Sources: inputs/evict.json (Redis runs), inputs/sim.json (simulations), inputs/pg.json (default miss costs: a primary-key lookup and a per-user usage aggregate on the chat database).
Every link opens in a new tab; times are estimates for a careful first read. Links checked on 5 October 2026; neighbouring pages updated 24 October 2026.
Pick a workload (real Wikipedia traffic or Zipf), a Redis policy and a memory size: the measured hit ratio, the exact LRU and OPT simulations beside it, and the cost-weighted hit ratio for miss costs you choose. It serves sections 5 and 6. About 10 minutes.
The root: the chat product's data from a file to a fleet. Its map places the cache among the families, and section 6 gives the price of a cache in two measured numbers; the Database atlas tab compares Redis, Valkey, Memcached and about 50 more with sources; Query plans measures warm against cold caches on real plans. About 27 minutes, plus the tabs.
Section 2: the buffer pool, its clock-sweep eviction, ring buffers and double buffering with the OS page cache, measured. Child page, about 42 minutes.
Fix the query before caching it: EXPLAIN, statistics, slow-query hunting. Child page, about 45 minutes.
Redis beyond caching (rate limits, leaderboards, streams), its persistence settings and the acknowledged writes a failover lost, measured. Child page, about 46 minutes.
Commits, isolation and visibility: what "after the commit" means for the delete. Child page, about 43 minutes.
Read replicas, replication lag and read-your-writes: the replica window of section 4. Child page, about 45 minutes.
Embeddings and approximate nearest-neighbour indexes, the machinery under a semantic cache. Child page, about 33 minutes.
Queries, joins, window functions, schema design, normalisation and migrations on the chat data, with graded exercises. Child page, about 48 minutes.
Backups, replication and failover, vacuum and wraparound, connection pooling, upgrades and monitoring. Child page, about 43 minutes.
Column stores, Parquet, DuckDB, ClickHouse, cloud warehouses, Iceberg and the lakehouse, and point-in-time joins for ML. Child page, about 46 minutes.
The cache in capacity terms: what an empty cache does to a database sized for the misses, queueing behind the hockey stick, load testing with a warm and a cold cache. Its stampede model is the one ported to section 7 here. About 38 minutes.
Section 6: prompt layout for prefix caching, with an animation of one conversation under two layouts and its bill; section 7: the four caches of an LLM service and tenant isolation. Prefix-aware routing, measured, is on LLM serving in production. About 23 minutes.
Where response and semantic caches sit in an LLM gateway, beside routing, fallbacks and budgets. Child page.
The protocol under section 9: methods, status codes, headers and the proxies between client and server. Child page.
Claude's prompt-caching prices and what caching does to an agent's bill, with a calculator. Provider page.
The outbox and change data capture: how invalidations become durable events. About 40 minutes.
Consistency models in full: what a cache gives up. About 46 minutes.
The KV cache from zero (section 2: bytes per token, why it caps concurrency), PagedAttention, KV offloading and cache-aware routing in model servers. Topic page.
Prefix caching and eviction in a model server (section 3): hashed blocks, radix trees and policies replayed on a day of real traffic. About 37 minutes.
Provider prompt-cache rules (section 2): Anthropic's order and breakpoints, minimums, lifetimes, OpenAI and Gemini, and one volatile line measured in three places. About 35 minutes.
Semantic caching in a retrieval system (section 8): every cache on the read path, and claim pairs with opposite verdicts that a semantic cache confuses. About 34 minutes.
The block allocator under vLLM's prefix cache, with its live toys. About 27 minutes.
The KV cache of every attention design recomputed from configs, MLA to V4.1-Flash's 890 bytes per token. About 26 minutes.
Embeddings, retrieval and caching retrieved results. Topic page.
Look-aside caching at billions of requests a second: leases, stale sets, mcsqueal invalidation from the commit log, pools, Gutter, cold clusters, remote markers. The reference production paper. (The old page's link, nsdi13-nishtala.pdf, now returns 404.) About 1 hour.
The policies including LRM, the sampled approximations, LFU tuning, the INFO fields to watch. About 15 minutes.
Why web requests follow a Zipf-like law and what that implies for hit ratios. About 40 minutes.
A self-tuning balance of recency and frequency using ghost lists of recently evicted keys. About 45 minutes.
Frequency-based admission with a compact sketch; the policy in Caffeine. With Caffeine's efficiency notes. About 1 hour.
GreedyDual-Size: eviction that weighs what a miss costs. About 40 minutes.
XFetch, the early-refresh rule. About 45 minutes.
The header semantics; MDN is the readable version. About 30 minutes for MDN.
The two Postgres tools of section 8. About 10 minutes.
Breakpoints, automatic caching, TTLs, prices, minimums, the 20-block lookback and the invalidation table. About 25 minutes.
Implicit and explicit breakpoints, retention, the write charge from GPT-5.6, the minimum-length cost trap with its formula. About 20 minutes.
Implicit caching by default, explicit caches with storage prices. About 15 minutes.
The two production designs for reusing KV across requests. About 20 minutes each.
The reference open-source semantic cache; its README names the parts (embedding, vector store, similarity evaluator, eviction) and warns of false positives. About 25 minutes.
AWS's threshold sweep and practical tuning advice. About 15 minutes.
A semantic cache that learns a threshold per entry with an error-rate guarantee. About 45 minutes.
Semantic caching as a proxy option and as a managed service. About 15 minutes each.
How adding a cache changes a service's failure modes, not just its latency. About 25 minutes.
A short taxonomy of the layers and patterns. About 20 minutes.
Caches as derived data, and why invalidation is a consistency problem. About 1.5 hours for the relevant chapters.
A global cache tier replicated across regions. About 20 minutes.
Memcached's segmented hot, warm and cold LRU, and why. About 15 minutes.
Dropped from the old page: the Canonical AI voice-caching post (canonical.chat did not respond on 5 October 2026).