Application caching
Handling cache misses
An online shop has a page listing products that cost less than GBP 21.00. To build it, the application asks PostgreSQL for the matching products and assembles the result. That takes about 150 milliseconds. The home page links to the list, so lots of people ask for the same answer.
The shop keeps a copy in Redis for 30 seconds. While that copy is usable, a request can return it without running the query again. When it expires, the next request goes back to PostgreSQL and stores a replacement.
That sounds like one query every 30 seconds. But rebuilding the list takes time, and customers keep arriving while it happens. What do those requests find in the cache?
One expiry can start many reads
The first request finds no list and starts computing one. The next request arrives before that computation finishes. It also finds no list. Redis has no record that someone is already working on the answer, so this request starts another computation.
Our example list receives 400 requests a second, roughly one every 2.5 milliseconds. The first result takes 150 milliseconds to arrive. During that gap, about 60 requests can each start the same work:
400 requests/second × 0.15 seconds = 60 computations
This burst of callers rebuilding one missing answer is a cache stampede, also called a thundering herd or dog-pile. The database has been asked the same question about 60 times before it can finish answering the first.
Figure as text
Computations of the list started after its entry expires, at 400 requests a second with no protection. The count climbs by one every 2.5 ms until the first fill lands: 60 at 150 ms, or 240 when the computation takes 600 ms. A dashed line marks the fleet’s 40 fill slots, and both counts pass it.
Those computations share processors, memory and disks with other queries. If the extra load makes each computation take 600 milliseconds, four times as many requests arrive before the first answer. The estimate becomes 240 computations. A slower database gives the stampede more time to grow.
A small experiment made the overlap visible. A disposable PostgreSQL query used pg_sleep to stand in for the list's computation. With a 150-millisecond delay, 61 queries started before the first result was cached. Increasing the chosen delay to 600 milliseconds produced 241. These runs demonstrate the overlapping requests; the sleep does not measure the cost of a real list query.
About 0.6 seconds into the slower run, PostgreSQL showed 233 active copies of the statement:
select wait_event, count(*), min(clock_timestamp() - query_start) as newest,
max(clock_timestamp() - query_start) as oldest, left(query, 40) as query
from pg_stat_activity
where backend_type = 'client backend' and state = 'active' and pid <> pg_backend_pid()
group by 1, 5 order by 2 desc;
wait_event | count | newest | oldest | query
------------+-------+-----------------+-----------------+------------------------------------------
PgSleep | 233 | 00:00:00.003088 | 00:00:00.584587 | select name || ':' || price_pence /*card The copies started at different times and accumulated while earlier copies were still running. That is what to look for when diagnosing a stampede. Here they were waiting on PgSleep because of the experiment. In a service, inspect whether the copies are using CPU, waiting for storage or blocking on a lock.
The burst can hide behind an excellent hit ratio. At 400 requests a second, the list receives about 12,000 requests in 30 seconds. If only 60 miss, the hit ratio is about 99.5%. Almost every request hits, yet the misses arrive in one expensive group.
The shop also caches individual product cards. Its blue mug, product P7, receives about 250 requests a second and takes 20 milliseconds to fill. The same estimate gives about five overlapping loads. A few duplicates may be acceptable where 60 expensive list computations are not. The rate and the fill time tell us which keys deserve coordination.
Share the work for one key
The callers need a way to discover work already in progress. Give each application server a map of active loads, indexed by cache key. The first request to miss registers a load. Later requests for that key join it and wait for the same result. When the load finishes, its waiters receive the result or error, and the map entry is removed.
This is request coalescing, also called request collapsing or singleflight. Within one process, it can turn those 60 list computations into one. Go provides singleflight; Caffeine provides atomic loading with cache.get(key, loader). A map of promises or futures can serve the same purpose.
Checking the map and registering a load must happen atomically, so two callers cannot both become the first. The loader then checks Redis again before querying PostgreSQL: another process may have filled the cache while this request was getting ready.
The map also needs the complete cache key. A product identifier alone is insufficient if the answer depends on the shop, language or currency. Sharing a load for two different answers can give one caller another caller's data. Cache keys develops that identity.
A failed load shares its error too. A database timeout must not become a cached “product not found”: the query did not establish whether the product exists. A short, separately identified failure entry can stop immediate repeat attempts, if that fits the service's recovery policy.
Let each caller stop waiting
Sharing work means its callers may have different deadlines. Suppose A starts a card load at 0 milliseconds but can wait only 50 milliseconds. B joins at 20 milliseconds and C at 40; each has 150 milliseconds to wait. The load would finish at 100 milliseconds.
If the load inherits A's deadline, it is cancelled at 50 milliseconds. B and C lose an answer that would have arrived in time for them. Instead, give the shared load its own budget, here 120 milliseconds, and let each caller wait only as long as its own request permits. A can leave at 50 milliseconds while B and C continue waiting.
Decide what A receives when it leaves. An older card can be useful, but only while the service's freshness rules still permit it. To keep such a card available during refresh, store two times: a soft limit, when to try replacing it, and a hard limit, after which it cannot be served.
Between those limits, a lookup can return the old card and mark it as due for refresh. After the hard limit, it is a miss. In this example, the hard limit is 30 seconds after the source observation, so a slow fill uses some of the allowance before the card even enters Redis. Store the remaining lifetime as Redis's expiry; copying the card into another cache must not restart it.
A caller that runs out of time returns a still-permitted older card, if it has one, or an error. It does not start another query. Otherwise every impatient waiter would recreate the stampede.
In Go, context.WithoutCancel detaches the shared load from the first caller's cancellation. A new timeout bounds that load, and DoChan lets each caller select between its own deadline and the result:
type Card string // a rendered product card
// Group shares one source load per key among the callers waiting for it.
type Group struct {
sf singleflight.Group
Load func(ctx context.Context, key string) (Card, error) // recheck cache, read source, fill
Stale func(key string) (Card, bool) // a copy freshness still permits
}
func (g *Group) Get(ctx context.Context, key string) (Card, error) {
ch := g.sf.DoChan(key, func() (any, error) {
// Detach from the first caller, then give the shared load its own budget.
lctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 120*time.Millisecond)
defer cancel()
return g.Load(lctx, key)
})
select {
case r := <-ch:
if r.Err != nil {
return "", r.Err
}
return r.Val.(Card), nil
case <-ctx.Done(): // this caller's deadline: leave without starting another read
if c, ok := g.Stale(key); ok {
return c, nil
}
return "", ctx.Err()
}
} The Load function rechecks the cache, obtains permission to use the source, reads it and stores the result. Stale returns a copy only if its hard limit still allows serving it. The wrapper shows how to share a load; caps on active keys, waiters and source work belong around it.
In the recorded experiment, A left at 50 milliseconds. B and C received the card at about 102–104 milliseconds from one source query. With the load attached to A's deadline, all three failed at 50 milliseconds.
Figure as text
Caller A misses P7’s card at 0 ms and can wait 50 ms; B joins at 20 ms and C at 40 ms, each able to wait 150 ms. With its own 120 ms budget, the load fills at 100 ms, and B and C receive the card from one source read after A has left with an error. Tied to A’s deadline, the load is cancelled at 50 ms and all three receive an error.
Check the timeout behaviour of a library before relying on it. For example, nginx's proxy_cache_lock_timeout allows a waiter whose lock wait expires to contact the origin itself. That is a valid policy, but it needs a source limit if many waiters can time out together.
The load's timeout also needs cooperation from the database. Cancelling a client context asks for work to stop; it does not prove that the query has stopped. In a separate experiment, killing a client one second into an eight-second query left PostgreSQL working until the query finished.
Use PostgreSQL's statement_timeout for the fill role or statement, sized to end the query within the loader's remaining budget. A load containing several statements must fit all of them into that budget. client_connection_check_interval can additionally detect a closed client connection during a query. Both settings default to disabled in PostgreSQL 16; connection checks depend on the operating system detecting the closure.
A timed-out caller must not free a source slot while its abandoned query keeps running and a replacement takes its place. Keep track of actual source work as well as callers still waiting. We will put limits on that work shortly.
Across application servers
The shop has 20 application-server instances. Each has its own map, so per-process coalescing can still allow 20 copies of the list query. In the experiment, distributing the callers among 20 groups produced 20 list computations for one expiry.
That may be enough. P7's roughly 250 requests a second are spread across the fleet, giving each server about 12 a second. Few arrive on the same server during a 20-millisecond fill. Coordinating the entire fleet to save a handful of card reads may cost more than it saves.
The list is a stronger candidate. Twenty copies each spend about 150 milliseconds in the database. The shop's example capacity budget permits roughly 40 card fills at once, so this one expired list can occupy half those places. A refresh lease lets the servers choose one owner to do the work.
In Redis, SET lease:<key> <token> NX PX 200 attempts to create a 200-millisecond lease. NX means “only if this key does not exist”; the token identifies this particular attempt. The winner starts the load. A loser can wait within its deadline, serve an older answer that is still permitted, or return its defined fallback. Expiry lets another server take over if the owner crashes.
Expiry also lets another server take over if the owner is merely slow. Suppose Server A gets the lease at 0 milliseconds, then its query stalls for 900 milliseconds. B tries at 10 milliseconds, finds A's lease and serves the older list. At 200 milliseconds the lease expires. B tries again at 210 milliseconds, wins, and finishes its own 150-millisecond computation at 360 milliseconds.
From 210 to 360 milliseconds, both queries are running. Redis has expired A's permission, but PostgreSQL has not been told to stop A's work.
Figure as text
Server A takes a 200 ms lease on the list and starts its query, and at 10 ms Server B finds the lease and serves the older list. A’s query stalls until 900 ms, but its lease expires at 200 ms, so B takes a new lease at 210 ms and publishes at 360 ms while both computations run. At 900 ms A’s owner-checked publish and release are refused, and the cache keeps B’s list. With a 180 ms statement timeout, A’s query is cancelled at 181 ms and B computes alone.
Now let A finish at 900 milliseconds. Its older result must not replace B's, and its cleanup must not delete a lease belonging to a later owner. Both publication and release need an atomic check that the stored token is still A's.
An experiment with no older list to serve reproduced the lease race. B waited after its first acquisition failed. The condensed trace shows both of A's late operations being rejected:
0 ms A SET lease:list:… tokA NX PX 200 -> OK
11 ms B SET lease:list:… tokB NX PX 200 -> (nil)
212 ms B SET lease:list:… tokB NX PX 200 -> OK
364 ms B owner-checked publish, release -> 1, 1
902 ms A owner-checked publish, release -> 0, 0 cache keeps B’s list Redis can perform the publication check and write in one Lua script:
-- KEYS[1] lease, KEYS[2] list; ARGV[1] token, ARGV[2] list, ARGV[3] ms to the hard limit
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('SET', KEYS[2], ARGV[2], 'PX', ARGV[3])
return 1
end
return 0 The caller supplies a positive remaining lifetime to the hard limit; if none remains, it discards the result. Release uses the same token check before deleting the lease. Redis 8.4 also provides DELEX key IFEQ token for conditional deletion. On Redis Cluster, the lease and cached value need a common hash tag so the script's keys share a slot.
These checks reject an expired owner in this scheme. They do not establish that a result includes the latest product edit; Versioned cache fills explains that separate problem. The lease reduces duplicate work, so occasional overlap is an efficiency cost. A lock protecting a correctness requirement would need the protected resource to reject obsolete owners too.
To bound the overlapping query, put a timeout at the source. With a 180-millisecond statement timeout, the experiment cancelled A's query at 181 milliseconds, before B's replacement began. The token check is still needed because A could pause after its query and before publication.
The short times make the race easy to see; they would be poor settings for a list that sometimes takes 600 milliseconds. Size the statement timeout, whole-load budget and lease from observed tail latency with headroom. If the list's 99th percentile were about 450 milliseconds, one possible starting point would be a 1-second statement timeout, a 1.2-second load budget and a 2-second lease. Test the combination under load. Callers retain their shorter deadlines and need not wait for all of it.
If Redis cannot grant leases, fall back to per-process coalescing through the source limit. An unavailable lease service must not give every caller permission to query the database.
Some caches provide this coordination directly. Memcached's meta protocol can create a placeholder on a miss with N. Its response gives one client W, the right to rebuild, and tells later clients with Z that someone already has it. A compare-and-swap (CAS) value lets the client publish only if the entry has not changed. Its R flag can also choose a refresher while the old value remains available. Check these facilities before building a separate lease protocol.
Refresh before the answer expires
So far, a request discovers that an answer needs replacing and waits for it. With a soft and hard limit, the application can start earlier. One request triggers a refresh while others keep receiving the current answer, still inside its serving allowance.
A successful refresh stores a new observation with its own lifetime. A failed refresh leaves the old observation exactly as old as before. If its hard limit arrives before a replacement, callers must wait for a usable result or receive a fallback. The HTTP mechanism stale-while-revalidate uses this general idea of serving an allowed older response during revalidation; the product's allowance is explained in Freshness and invalidation.
Figure as text
The list was read at 0 s and may be served until its hard limit at 30 s. A refresh reads the source at 29.3 s and takes 150 ms. If it succeeds, later requests receive the new list, which may be served until 59.3 s, and no request waits. If it fails, requests receive the older list until 30 s and then miss.
A fixed refresh point needs the same protection as an expiry. If every request after 25 seconds can start a refresh, the list's next 150 milliseconds contain another 60 callers. Coalesce them, and use a lease if the remaining duplicates across servers are too expensive.
Another approach lets each request make a random decision. Far from expiry, a refresh is unlikely. As expiry approaches it becomes more likely, so a busy key usually refreshes before its copy disappears. Unused keys do no work. This is probabilistic early expiration; XFetch is a published algorithm for it.
XFetch stores the previous computation time, Δ, with the cached value. On each request it chooses a random number strictly between 0 and 1 and refreshes when:
now − Δ · β · ln(rand()) ≥ expiry
The logarithm is negative, so subtracting it moves the test forward in time. Most draws move it a little; a few move it much further. Longer computations get more head start. The factor β controls how early refreshes are attempted, with 1 as the usual starting value.
In 2,000 simulated expiries, each list computation took 150 milliseconds and 400 requests arrived per second. The first refresh began about 0.7 seconds early on average. More requests could start refreshes before that one finished: the simulation averaged 2.8 refreshes per expiry, with 11 at the 99th percentile.
That is much less work than 60 computations, but it is still duplicate work. Per-process coalescing may remove little when the attempts land on different servers. Use a lease as well if the remaining overlap exceeds the source budget.
Spread different keys out too
There is another way for refreshes to arrive together. If a warm-up stores thousands of entries at once, they can all reach their refresh point together. Randomly spread those points, perhaps between 22 and 26 seconds after the source read, while keeping the 30-second hard limit. This variation is called jitter.
Jitter spreads work across keys. It does not coordinate the callers of one popular key. For cheap fills such as P7's, a fixed refresh point with jitter and whatever coalescing is justified may be sufficient. XFetch is useful when one key attracts enough overlapping work to warrant a more careful refresh decision.
Neither technique helps an empty cache. There is no stored answer, refresh point or previous computation time to work with. We need a limit that applies to all source work, whatever caused it.
Limit the work reaching the database
At peak, the example shop receives 20,000 card requests a second across its 20 servers. With about 94% cache hits, roughly 1,200 requests a second need a fill. Suppose capacity testing gives card fills an allowance of 2,000 a second, leaving room for checkout and other database work.
A useful way to enforce that allowance is to limit concurrency: the number of fills executing at once. For a simple calculation, let a fill take 20 milliseconds. Two thousand fills a second then keep about 40 fills in progress:
2,000 fills/second × 0.02 seconds/fill = 40 fills
This relation is Little's law, and it uses the mean duration. The shop's 20-millisecond figure is a median, so the arithmetic is only a starting estimate. A real limit needs the measured mean and a load test of the actual mix of queries. Here we use an illustrative 40-place limit; expensive list queries occupy a place for longer.
Across 20 servers, that gives each server two executing places. When both are occupied, allow at most one more request to wait. When a place opens, check that waiting request's deadline again. If too little time remains for a useful result, refuse it. If the waiting place is already occupied, refuse the new request immediately. Choosing whether work may start is admission control.
Every refusal needs a response the product can accept. Try a cached copy that is still within its hard limit, including a local copy if Redis is unavailable. If the page already has a usable name and picture, show them with the price marked temporarily unavailable.
Without usable data, fail quickly with an explicit error such as HTTP 503. The fallback must fit what is already available without another source read. Do not turn missing capacity into a zero price or “product not found”. Checkout still checks the authoritative price.
A short queue absorbs a small burst. A long queue can spend a caller's entire budget before its query starts. In this example, a request rejected in a millisecond has a chance to take another path; one rejected after 140 milliseconds has almost no time left.
Concurrency also responds to a slowdown. If the 40 fills each take 40 milliseconds, the fleet completes about 1,000 a second. At 200 milliseconds it completes about 200. The limit allows less new work while old work takes longer. A rate limit admitting 2,000 starts a second would instead accumulate about 400 concurrent fills at 200 milliseconds.
Count demand loads, early refreshes, warm-up reads and retries against the same source budget. Limit their total work where it runs, including queries whose callers have gone away.
Recalculate per-server limits when the fleet changes. Thirty servers with two places each permit 60 fills at once, not 40. Give each one place and accept some unused allowance, distribute the remaining places explicitly, or enforce a shared limit at the source. Adding application servers does not add database capacity.
Choose connection limits separately
A connection pool of 50 on each of the 20 servers permits 1,000 connections. It is a much larger allowance than the 40 executing fills we intended.
At the normal miss rate of 1,200 a second, increasing fill duration from 20 to 200 milliseconds raises the work in progress from about 24 to 240 fills. That is only 12 per application server, so a pool of 50 would not make those requests wait. The database can be overloaded before any individual pool is full.
With PostgreSQL 16's usual default of 100 total connections and three reserved for superusers, an ordinary fill role reaches the database's limit first. In the isolated test, with the other ordinary slots occupied, its 98th connection was refused:
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute Other clients or reservation settings can make refusal happen earlier. The failure is a connection error, not our planned short queue and fallback. Raising max_connections may remove that error while admitting still more work than the database can handle.
Put admission before obtaining a connection. Size the pool for the admitted fills and the server's other database uses, and give connection acquisition its own bounded wait. A suitably small pool can be part of the protection, but it must fit the fleet-wide budget and the caller's deadline.
Batch different missing keys
Coalescing shares one answer. It cannot combine requests for different cards, but a page can fetch several missing cards together. If eight of a page's 24 cards are missing, a query using WHERE id = ANY($1) can fetch those eight in one round trip. This is the DataLoader pattern. Charge the batch for its expected source cost; combining eight reads into one query does not necessarily make it cost as little as one card.
When Redis is unavailable
A missing key is an answer from Redis. A timeout is a failure to get an answer, and it has already used some of the request's time. With a 150-millisecond request budget and a 10-millisecond cache timeout, any fallback work has at most 140 milliseconds left. Bound cache calls and the number waiting on them, so a stalled cache cannot hold the whole application.
The source limit must remain in force through that failure. If every failed lookup goes straight to PostgreSQL, its 1,200 card fills a second become 20,000 attempted fills a second. The increase is about seventeenfold: the source previously saw 6% of requests and now sees all of them.
Coalescing helps only when callers want the same answer at the same time. In a simulation with 50,000 cards and the shop's skewed popularity, per-process coalescing joined about 2,300 requests a second to existing work. That still left about 17,700 fills a second, nearly nine times the allowance.
With two executing places and one waiting place per server, admitted work stayed near 2,000 fills a second. Those fills directly served about 10% of requests. Callers that joined them added about two percentage points, so roughly 12% received a full card. The remaining callers needed the defined fallback. Keeping the database healthy does not mean every request succeeds.
Small local caches can improve that result. In our popularity model, the 1,000 most requested cards account for about two thirds of requests. Keeping those copies on 20 servers and replacing each every 30 seconds would require about 20 × 1,000 ÷ 30, or 670 fills a second. Those refreshes must come out of the same 2,000-fill allowance.
A simulation with those local copies served 65.7% of requests locally and another 6.7% through demand fills, about 72% in total. That assumes the copies are available and maintained within their age limits. A local cache that starts empty, loses its copies or extends their lifetimes cannot promise that result.
After repeated Redis failures, a server can stop making normal cache calls and send occasional probes to detect recovery. This circuit breaker saves the cache timeout on every request, but the bypass path still needs admission control. Test entering and leaving that mode as well as ordinary cache misses.
If only one cache shard fails, moving its keys onto healthy shards can move its overload too. A popular key may overwhelm its new host. Facebook's memcache design instead sends failed-server requests to a small reserve cache called Gutter. A miss there still needs a source fill, but later requests can reuse it. That buys capacity for a few failed servers; it cannot absorb an unlimited outage. Reserve fills still need the source budget, and short-lived entries must respect the serving allowance.
Count every retry
Now suppose the loader, database client and edge proxy each allow three attempts. One proxy request can call the loader three times. Each loader call can call the database client three times, and each client call can try the query three times. One request has become as many as 3 × 3 × 3 = 27 source attempts.
Choose one layer to retry, usually the loader that knows the operation's remaining deadline. Disable independent retries at the other layers for this path. Each attempt goes through the same coalescing and admission checks, and a caller that has left starts no new attempt.
A per-request limit is still insufficient if every request fails. Give retries a shared allowance too: for example, permit retries to consume at most 10% of the request volume over a chosen interval. A token bucket can spend tokens on retries and replenish them as work succeeds. Stop when the budget is spent, the deadline is too close, or the failure is an explicit overload refusal. Backoff and jitter spread attempts out; they do not create room for more work.
Refill a cold cache
An unreachable cache cannot accept replacements. A restarted, empty Redis can. Every admitted fill now helps two groups: the callers waiting for it and later callers who find its answer cached.
That makes popularity useful. In the shop's simulation, the first few popular cards were requested and filled quickly. With source work capped at 2,000 fills a second, the hit ratio reached about 61% after one second, 70% after two and 80% after five.
The 1,000 most requested cards serve about two thirds of requests. Filling all of them needs at least half a second at the full allowance, but demand does not request them in perfect order. The simulation had 500 back within 0.8 seconds, 900 within 2.6 seconds and all 1,000 by about eight seconds.
Figure as text
With fills held at 2,000 a second, the demand simulation reaches 61% cache hits after one second, about 80% after five and 94% after about twenty. The prewarm line is calculated, not simulated. It assumes catalogue order is independent of popularity: filling 10,000 of 50,000 cards after five seconds covers 20% of requests on average. Popular-first ordering would recover more demand sooner.
Prewarming the whole catalogue first spends work differently. Fifty thousand cards at 2,000 fills a second take at least 25 seconds. After five seconds, 10,000 cards are ready. If their order is independent of popularity, that is 20% of the catalogue and, on average, 20% of requests. This is a calculated expectation; the demand-fill simulation reached about 80% in that time.
The order matters. Warming yesterday's 2,000 most popular cards is more useful than starting at an arbitrary catalogue position: roughly one second of work can cover about 70% of demand.
Give warm-up only a share of the source budget and let current demand take priority. The recovery simulation omitted expiry; a real cache also needs to spread the refresh points of entries filled together, or their next refresh can become another burst.
Increase traffic in steps while watching source fill latency and admitted work in progress. Latency should remain near the example's normal 20-millisecond median and 60-millisecond 99th percentile, with work within the 40-place limit. If latency rises sharply or the limit stays saturated with persistent refusals, hold or reduce traffic. The hit ratio alone cannot tell you whether the database is keeping up.
Slack's account of its February 2022 incident describes having to raise traffic in smaller increments after a larger step overloaded the database again. Restoring the cache is only part of restoring the service; fills need enough capacity to finish.
When recovery gets stuck
Imagine that ten minutes after a failover, the hit ratio is stuck at 31% and database CPU is at 100%. PostgreSQL lists 90 active copies of a card query, the oldest running for 4.8 seconds. Application requests time out after one second, almost no fills succeed, and the loader averages 2.7 source attempts per request.
The cache is available again, but the system cannot refill it. Most requests miss, so too much work reaches the database. Queries slow beyond the callers' deadlines, leaving few useful answers to store. Retries add work, and abandoned queries keep using capacity.
This is a metastable failure: a temporary disturbance has pushed the system into a state that sustains its own overload. Traffic returning to its old level may not help, because that level depended on a warm cache.
First stop the amplification. Disable retries outside the loader, enforce its retry budget, and put the admission limit before the source. If the application has no working limiter, shedding traffic at the edge can provide emergency relief. Reduce demand far enough that admitted queries can finish and populate the cache.
Then stop abandoned work at the source. Set a suitable statement timeout within the application's load budget and verify that timed-out work actually ends. Request logs showing failures are not enough while database backends remain busy. As fills begin succeeding, increase traffic gradually while watching the same latency and concurrency measurements.
Test the failure paths
A warm-cache test mostly exercises hits. Test the paths that determine whether the service survives losing them:
| Change | What to check |
|---|---|
| Slow one popular key | Callers share work, leave at their own deadlines and do not start replacement reads. Source timeouts end abandoned work. |
| Let a lease expire during a query | The old owner cannot publish or release a later owner's lease. Overlapping source work remains within the budget. |
| Fail a refresh | The older answer remains usable only until its original hard limit. |
| Miss on many different keys | Admission bounds executing work and queued callers. Excess requests receive their defined fallback quickly. |
| Make Redis unreachable | Cache timeouts consume a bounded part of the request deadline. Losing leases leaves source protection in place. |
| Restart Redis empty | Useful fills complete, hits return and warm-up competes within the same source budget. |
Instrument the application as well as the cache. Count callers entering coalescing, loads started, source attempts and successful cache fills separately. Sixty callers might share one load, which then retries and makes two source attempts. Redis sees individual lookups, including the loader's recheck; its hit and miss counters cannot tell you how much source work was saved.
Record queue delay, admission refusals and work still executing. Compare the application's counts with active statements in pg_stat_activity and completed calls in pg_stat_statements. A started load may fail before completing a query or storing a value, so those counts need not match.
Count full answers, permitted older answers, reduced responses and refusals separately, alongside actual source work. Fast failures can make a latency graph look better while fewer customers get useful pages.
Where the numbers come from
The shop, its traffic and its capacity allowance are an illustrative model, not measurements of a production service. Its product cards have a modelled 20-millisecond median fill time; calculations using a constant 20 milliseconds simplify that distribution. The capacity limit must be measured for a real workload.
The execution examples were recorded on 6 November 2026 using disposable PostgreSQL 16.15, Redis 7.0.15 and Go 1.24.7. Queries used pg_sleep to represent chosen work durations. Query counts, states, errors and returned values were observed; the durations do not benchmark a real catalogue query.
The early-refresh results come from 2,000 simulated expiries. Outage and recovery results use the example's 50,000-card catalogue and roughly Zipf-like popularity: a small number of cards receive most requests. They show what happens under those assumptions, including idealised local-copy maintenance and a recovery run without expiry. They are not forecasts for another service.
Sources and further reading
- Vattani, Chierichetti and Lowenstein, Optimal Probabilistic Cache Stampede Prevention, PVLDB 8(8), 2015: stampede size, XFetch and its parameter β.
- Go, singleflight and context.WithoutCancel.
- Caffeine, Refresh:
refreshAfterWriteand atomic loading per key. - Memcached, Meta Text Protocol: miss ownership, early recache and conditional publication.
- Nishtala et al., Scaling Memcache at Facebook, NSDI 2013, §3.3: Gutter and the risk of moving hot keys onto surviving servers.
- nginx, proxy_cache_lock_timeout: what a cache lock does with waiters when it times out.
- Redis, Distributed locks with Redis, and the SET and DELEX commands: single-instance leases, owner-checked release and the 8.4 conditional options.
- Martin Kleppmann, How to do distributed locking, 2016: efficiency and correctness locks.
- PostgreSQL, client connection defaults (
statement_timeout) and connections (client_connection_check_interval,max_connections,superuser_reserved_connections). - PostgreSQL, pg_stat_activity and pg_stat_statements: running statements and accumulated query statistics.
- Netflix, concurrency-limits: concurrency limits from Little’s law and measured latency.
- Google, Site Reliability Engineering, Handling Overload and Addressing Cascading Failures: retry budgets, queue sizes and deadlines. The latter cites Maurer’s “Fail at Scale” for Facebook’s adaptive queues.
- Amazon Builders’ Library: Caching challenges and strategies, Using load shedding to avoid overload and Timeouts, retries, and backoff with jitter.
- Bronson, Aghayev, Charapko and Zhu, Metastable Failures in Distributed Systems, HotOS 2021; Huang et al., Metastable Failures in the Wild, OSDI 2022.
- Slack, Slack’s Incident on 2-22-22.
- On this site: Freshness and invalidation for serving allowances, Versioned cache fills for conditional publication, Caching with Redis for client deadlines, and Operating a cache for rollouts and diagnosis.