A cache is the one component whose failure mode is a crowd. A database slows down gradually as load rises; a cache does not slow down at all until the moment a hot key expires, and then every request that was being served from memory turns around and asks the same question at the same instant. The queue that forms is not a queue of packets. It is a queue of identical work, and the database behind it was never sized for the aggregate. This article is about the three structures that decide whether that moment is a blip or an outage: how a miss is filled, how a lock is released, and how the instance behaves when it runs out of memory.
Every number below came from a probe executed on this machine: CPython 3.12.16, the redis client 8.1.0, a real Redis 7.0.15 binary talking TCP on loopback, on 2 vCPUs. The probes are in the same directory as the article’s own build, each one starts its own server instance, and each one writes the numbers it measured into a JSON file that the build reads. Nothing in the tables was typed in by hand, and no number in the prose exists without a token that resolves to a measured value; if a figure had not been measured, the page would refuse to build rather than estimate it.
1. The failure that looks like a database problem
The four incidents in the first table have almost nothing in common at the infrastructure level. One is a query storm, one is a consistency bug, one is a memory panic, one is a socket leak. They share a cause: Redis was treated as a key-value store with no concurrency semantics, when it is actually the coordination point for a whole tier of workers. Once you accept that framing, each failure has a small, testable mechanism and a small, testable fix.
| What the on-call engineer sees | Mechanism | What the probes measured here | Fix |
|---|---|---|---|
Database CPU pinned, application latency p99 in seconds, Redis CPU flat | One hot key expired and every in-flight request missed at once | With no defence, 321 database calls for one key in a 4 s window, 64 of them concurrent | Single-flight fill; XFetch early refresh |
| A job ran twice, or a balance was decremented twice, despite the lock | A holder outlived its lease and released somebody else’s key | A plain DEL removed another holder’s lock in all 30 trials of the constructed interleaving | Compare-and-delete release, watchdog, fencing token |
Writes fail with OOM command not allowed in the middle of the night | The instance reached maxmemory with a policy that cannot evict anything it is allowed to evict | 4,722 of 12,000 writes refused per round with noeviction, and 3,632 in a single fill with volatile-lru on a keyspace without TTLs | Choose the policy for the key classes you actually store |
| Random failures under load, no pattern, no slow query | The client’s connection pool is smaller than the concurrency and it raises instead of queueing | The shared default pool answered 200 of 400 requests and raised 200 times | A bounded pool that waits, sized to the concurrency you run |
The last row is the one that wastes the most engineering time, because it presents as flakiness. An application that raises a fraction of its requests under load looks like a race condition in business logic, and teams spend days in their own code before they read the client library’s default. Section 11 is about that default; it is worth arriving there with the measurement in hand.
Production SRE Note: None of these four is a Redis bug. Every one of them is a default: a TTL without a refresh strategy, a lock without an owner check, a memory policy chosen for the wrong key class, a pool size chosen by a library. The fixes are small. Finding them at three in the morning is not.
2. What was measured, and what was not
The entire set of measurements runs against one Redis instance per experiment, started on a free loopback port for that experiment alone and shut down afterwards. That isolation matters more than it sounds. Reuse one server across four pool variants and the sample carries the previous variant’s sockets: a pool capped at 50 then reports a peak of 101 connections anyway. The published numbers come from one server per variant, and the difference is exactly the kind of contamination that makes benchmarks flattering and useless.
| Component | Value | Why it is recorded |
|---|---|---|
| Python | 3.12.16 (CPython) | asyncio scheduling and GIL behaviour |
| Redis server | 7.0.15 | Lua, lease semantics, eviction sampling |
| Allocator | jemalloc-5.3.0 | memory per key and fragmentation |
| redis client | 8.1.0 | pool defaults and retry behaviour |
| Machine | x86_64, 2 vCPU, Linux 6.12.8+ | concurrency has a ceiling here |
| Default policy | noeviction | what an unconfigured instance does |
| Memory at rest | 685,760 bytes | baseline for every memory delta |
What this machine cannot tell you is equally important. There is one server, not a primary and a replica, so the failover behaviour that fencing tokens exist to survive is described from the protocol’s semantics, not re-enacted. There is no cluster mode, so hash-slot redirects are out of scope. There is no swap pressure and no cgroup memory limit around the server, so the eviction measurements show a policy reaching its ceiling, not a host OOM killer taking the process. And the network is loopback: the round-trip numbers in section 12 are the cost of the protocol on this machine, and a real network adds its own latency on top of every one of them. Section 17 lists the rest.
One design decision applies to all of the scripts: every strategy is compared against another strategy under identical conditions, in the same process, against the same server shape, with the same simulated database latency. The database is a function that sleeps for 20 ms and increments a counter, which makes the interesting quantity – how many times the downstream store is asked – a number the probe can state exactly instead of inferring from CPU graphs. The shape of the stampede probe is worth showing, because every conclusion in sections 3 to 5 comes out of it.
"""One hot key, many readers, three ways to survive its expiry."""
import asyncio
import json
import secrets
import time
TTL_MS = 500 # the key the whole probe revolves around
DB_LATENCY_S = 0.020 # what the downstream store costs per read
READERS = 64 # concurrent readers hammering the same key
KEY = "product:hot:42"
RELEASE_IF_OWNER = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
end
return 0
"""
async def naive(client, db, counter):
"""Read through, fill on a miss, no coordination at all."""
raw = await client.get(KEY)
if raw is not None:
return json.loads(raw)
counter.enter()
try:
row = await asyncio.to_thread(db.read, KEY) # the 20 ms stand-in
finally:
counter.exit()
await client.set(KEY, json.dumps(row), px=TTL_MS)
return row
async def single_flight(client, db, counter):
"""One reader fills; the others wait for its result instead of repeating the query."""
raw = await client.get(KEY)
if raw is not None:
return json.loads(raw)
token = secrets.token_hex(16)
won = await client.set(f"lock:{KEY}", token, nx=True, px=TTL_MS * 4)
if won:
try:
counter.enter()
try:
row = await asyncio.to_thread(db.read, KEY)
finally:
counter.exit()
await client.set(KEY, json.dumps(row), px=TTL_MS)
return row
finally:
# A plain DEL here is the bug in section 7: delete only your own key.
await client.eval(RELEASE_IF_OWNER, 1, f"lock:{KEY}", token)
deadline = time.monotonic() + 2.0
while time.monotonic() < deadline:
await asyncio.sleep(0.002)
raw = await client.get(KEY)
if raw is not None:
return json.loads(raw)
return await asyncio.to_thread(db.read, KEY) # the winner died; never hang
The third strategy, XFetch, is the same reader loop with one extra decision before returning: whether to refresh the value in the background now, while it is still valid. That decision is section 5. The point of showing the first two together is that they differ by four lines and by one entire category of production incident.
3. One expired key, sixty-four readers
The probe holds one hot key with a 500 ms TTL and drives 64 concurrent readers at it for 4 seconds, three times per strategy. Every reader runs the loop as fast as it can, so the offered load is set by the strategy’s own latency rather than by an artificial sleep. The counter around the simulated database call records both the total number of calls and the peak number in flight at the same time; the second number is what actually hurts, because that is the concurrency the database has to absorb.
| Strategy | Database calls (median of 3) | Peak concurrent calls | Requests served | p50 latency | p99 latency |
|---|---|---|---|---|---|
| Read-through, no coordination | 321 | 64 | 49,832 | 4.835 ms | 7.567 ms |
| Single flight on a miss | 8 | 1 | 49,340 | 4.839 ms | 31.619 ms |
| XFetch early refresh | 11 | 1 | 50,768 | 5.005 ms | 5.714 ms |
Read the first row as a multiplier rather than a number. One key, expiring every half second, produced 321 database calls in four seconds, and at the moment of each expiry every one of the 64 readers was inside the same query. The database did not see one slow query; it saw a burst of identical ones. Scaling that from one hot key to the few hundred that any real catalogue has is how a cache turns into a load amplifier at exactly the traffic level where the cache was supposed to help.
Single flight removes the multiplier. The same window produced 8 calls, which is one per expiry cycle, and the peak concurrency fell to 1. That is the number to put in front of a database team: not an average, a ceiling. XFetch produced 11 calls, slightly more, because a probabilistic refresh occasionally fires when the value is still comfortable; the difference between 8 and 11 calls over four seconds is not a reason to choose either one.
The reason to choose between them is in the latency column, and it is the opposite of what the database numbers suggest. Single flight is cheap for the database because it makes readers wait: a reader that loses the race polls until the winner has finished, so its latency includes the winner’s 20 ms query. XFetch does not make anybody wait, because the refresh happens before the key is gone, which is why its tail stays near the cost of a cache hit while the single-flight tail carries the cost of a fill.
| Strategy | p50 | p90 | p99 | Worst p99 of the 3 rounds | Worst single request |
|---|---|---|---|---|---|
| Read-through, no coordination | 4.835 ms | 5.193 ms | 7.567 ms | 7.816 ms | 234.665 ms |
| Single flight on a miss | 4.839 ms | 5.204 ms | 31.619 ms | 33.416 ms | 60.292 ms |
| XFetch early refresh | 5.005 ms | 5.168 ms | 5.714 ms | 6.287 ms | 49.439 ms |
The uncoordinated row is a trap for anyone reading only percentiles. Its 7.567 ms tail is the tail of the requests that hit the cache, because most requests do: the expiry happens twice a second and the rest of the window is a hit. The requests that paid for the stampede are in the maximum column, at 234.665 ms, not in the percentile. A stampede this small – one key out of a large keyspace – barely moves p99; it moves the database, and the database drags everything else with it a few seconds later. That is why the database call count, not the application latency, is the metric that catches this failure early.
Production SRE Note: If you take one number away from this section, take the peak concurrency: 64 simultaneous identical queries against 1 with a single-flight fill. That ratio, not the average call count, is what your database’s connection pool and its plan cache have to survive.
4. Single flight: one fill, and what the waiters pay
A single-flight fill is a lock with a very short life and a value attached. The first caller to miss takes a key with SET NX PX, loads the value, stores it and releases; everyone else polls the cache key until it appears. The pattern is old, and the details that decide whether it works in production are all in the failure paths: what a waiter does when the winner dies, what happens when the winner’s lease expires mid-query, and how long a waiter is allowed to wait before it gives up and does the work itself.
The probe’s single-flight variant had none of the refinements and still reduced the query count by a factor of 40.1 – 321 calls against 8 – with a wait loop of two milliseconds and a two-second ceiling. The ceiling is the important part: without it, a winner that dies between taking the lock and storing the value leaves every waiter parked until its own timeout, and the cache turns a fast failure into a slow one. The production version in section 6 falls back to loading the value itself after the deadline, which is a worse outcome for the database than one fill and a far better outcome than a hang.
There is a second cost that the numbers make visible and that most implementations forget: the lock itself is a write to the same Redis instance that is serving the reads. Each miss now costs a GET, a SET NX, a GET loop and a compare-and-delete instead of a GET and a SET. On a cache serving hundreds of thousands of operations per second, the miss path is rare enough that this is free; on a cache with a high miss rate, the coordination traffic can become the load. The measurement to watch is the ratio of misses to reads, which is why the cache object in section 6 counts hits, misses, waits and early refreshes separately rather than exposing a single hit-rate number that hides all four.
Fairness is the last property single flight does not give you. The winner is whoever arrives first, and under a burst of simultaneous misses that is decided by the event loop, not by any queue. For a cache fill this is acceptable: the value is the same for everyone and the wait is one query. For a lock that guards a write, the same sentence is a livelock, and section 10 measures what happens when the losers retry badly.
5. XFetch: refresh the key before it dies
The alternative to making readers wait is to never let them arrive at an empty key. The idea behind probabilistic early expiration is that the moment of expiry is arbitrary – it is a number some engineer typed – while the cost of recomputing the value is a property of the workload. If a value takes 20 ms to compute, there is no reason for it to be recomputed at the instant it expires rather than a few milliseconds before, while the old value is still being served.
The rule is one line. Each reader, on a hit, draws a uniform number and asks whether the value should be refreshed now: now - delta * beta * ln(u) > expiry, with delta the measured compute time of the value, beta an aggressiveness factor and u uniform in the open interval from zero to one. Because -ln(u) is exponential with mean one, the probability that a reader at remaining seconds before expiry decides to refresh is exactly exp(-remaining / (delta * beta)). As the key approaches its expiry that probability rises smoothly from zero to one, and the refresh is a background task rather than something the current reader waits for.
That closed form is easy to get wrong in a blog post and easy to check with a loop, so it was checked: 200,000 draws per ratio, comparing the measured frequency of the trigger against the prediction. The ratios are expressed in units of delta, so the table reads the same for a value that takes microseconds and one that takes a second.
| Remaining TTL | Seconds before expiry | Measured trigger rate | Predicted exp(-r / delta) | Absolute error |
|---|---|---|---|---|
| 0.1x delta | 2 ms | 0.905 | 0.905 | 0.00024 |
| 0.25x delta | 5 ms | 0.780 | 0.779 | 0.00111 |
| 0.5x delta | 10 ms | 0.608 | 0.607 | 0.00112 |
| 1x delta | 20 ms | 0.368 | 0.368 | 0.0001 |
| 2x delta | 40 ms | 0.135 | 0.135 | 9e-05 |
| 4x delta | 80 ms | 0.019 | 0.018 | 0.00047 |
The largest disagreement in any row is 0.00112, which is sampling noise at this number of draws rather than a modelling difference. The practical consequence is that beta has a predictable meaning: with beta at 1, a reader starts refreshing when it is one compute-time away from expiry with probability about a third, and this is what makes the strategy tunable instead of magical. Raising beta moves the refresh earlier and costs more redundant recomputes; lowering it moves the refresh later and lets more readers reach the expired key together.
The second half of the calibration is the time at which the refresh actually fires. The mean of that lead time has to equal delta * beta if the algebra is right, and it does: 20 ms against a delta of 20 ms. The distribution is the exponential one, which is why the mean is a misleading summary on its own: for one read, half of the draws leave less than 14 ms of runway and the slowest tenth fire more than 46 ms early, with a tail that reaches 92 ms in the ninety-ninth percentile and 263 ms at the maximum. The early tail is the useful part – it is a refresh that costs nothing but a duplicate query – while the late tail is where a stampede still gets through.
| Statistic | Lead time before expiry | What it means for the refresh |
|---|---|---|
| Minimum | 0 ms | fires on the edge of expiry |
| Median | 14 ms | half of the decisions are later than this |
| 90th percentile | 46 ms | one decision in ten is this early |
| 99th percentile | 92 ms | the early tail starts here |
| Maximum | 263 ms | an outlier that still triggered |
| Mean | 20 ms | equals delta times beta, as it must |
That distinction is the one this table is easy to misread on. A single draw leaves the median 14 ms of runway; a key read 10,000 times a second gets that many independent draws, and the chance that none of them fires at r seconds before expiry is exp(-N * r / delta). The first trigger of the second therefore arrives about delta * ln(N) before expiry – 184.2 ms at this delta and read rate, an order of magnitude earlier than the single-draw median. A hot key is refreshed early because it is read often, not because any one read is brave, and the arithmetic that predicts it is the same closed form as Table 5 (a derivation, not a separate measurement).
One implementation detail is worth its own paragraph because it is a real crash rather than a style point: math.log(0) raises, and a client that calls random.random() inline inside the logarithm is one draw away from a ValueError: math domain error inside a cache read, which is a 500 on the request that happened to draw zero. The draw is a multiple of a power of two, so zero is possible with probability about one in nine quadrillion – small, but not zero, and the cost of closing it is one comparison. Clamping the draw (u = max(random.random(), 1e-12)) before the logarithm removes the failure entirely, and shifting the distribution by that epsilon does not move any probability the calibration can see.
from __future__ import annotations
import json
import random
from dataclasses import dataclass
ENVELOPE_VERSION = 1
@dataclass(frozen=True)
class Envelope:
value: object
delta_s: float
expires_at: float
def encode(self) -> str:
return json.dumps({"v": ENVELOPE_VERSION, "value": self.value,
"delta": self.delta_s, "expiry": self.expires_at})
@classmethod
def decode(cls, raw: str) -> "Envelope":
payload = json.loads(raw)
if payload.get("v") != ENVELOPE_VERSION:
raise ValueError(f"unknown envelope version {payload.get('v')!r}")
return cls(payload["value"], float(payload["delta"]), float(payload["expiry"]))
def should_refresh(now: float, envelope: Envelope, beta: float = 1.0,
rng: random.Random | None = None) -> bool:
"""XFetch: refresh early with probability exp(-remaining / (delta * beta))."""
import math
source = rng or random
uniform = max(source.random(), 1e-12) # log(0) is not a valid draw
return now - envelope.delta_s * beta * math.log(uniform) > envelope.expires_at
The envelope is the other half of the deal. XFetch needs to know two things that a plain SET key value EX 300 throws away: how long the value took to compute, and when it will expire. Storing them beside the value is not free – section 13 measures what the extra bytes cost – but without them a reader can only compare against the Redis TTL, and the TTL is measured from the write, not from the compute. An envelope also makes the refresh decision independent of clock agreement between the reader and the writer, because both numbers travel with the value.
Production SRE Note: XFetch and single flight are not alternatives, they are layers. XFetch keeps the key warm and makes the stampede unlikely; single flight handles the case where XFetch lost a race, the key was evicted, or the value was never cached at all. A cache with only XFetch still has a cold-start stampede; a cache with only single flight still pays a fill on every expiry.
6. The two defences in one cache object
The module that ships with this article combines them in one read path: hit, decide whether to refresh, return. On a miss, one caller fills under a short Redis lock and the rest wait for its value. The path is short enough to read in one screen, which matters because it is the code that will be in the request path of every endpoint that uses the cache.
from __future__ import annotations
import time
from typing import Any, Awaitable, Callable
from rediskit.keys import Envelope, should_refresh
Loader = Callable[[], Awaitable[Any]]
class Cache:
async def get_or_load(self, name: str, loader: Loader, ttl_s: float | None = None) -> Any:
"""Return the cached value, filling or refreshing it once for all callers."""
full = self.name(name)
raw = await self.client.get(full)
if raw is not None:
self.hits += 1
envelope = Envelope.decode(raw)
if should_refresh(time.time(), envelope, self.beta, self.rng):
self._schedule_refresh(full, loader, ttl_s)
return envelope.value
self.misses += 1
return await self._fill_once(full, loader, ttl_s)
Three details in those lines carry the weight of the measurements. The first is that a hit is returned before any refresh decision is awaited: the refresh is scheduled with create_task and the reader leaves with the value it already had, so the 5.714 ms tail in Table 4 is the tail of a cache hit and not the tail of a database query. The second is that a refresh is deduplicated twice, once in process by the task dictionary and once across processes by the same SET NX lock that the miss path uses, so a hundred workers cannot all decide to refresh the same key at the same moment. The third is that the envelope is the only thing stored: no separate TTL key, no metadata key to keep in step, one GET per read.
The miss path is where the single-flight property lives.
from __future__ import annotations
import asyncio
import secrets
import time
from typing import Any, Awaitable, Callable
from rediskit.keys import Envelope
Loader = Callable[[], Awaitable[Any]]
RELEASE_IF_OWNER = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
end
return 0
"""
class Cache:
async def _fill_once(self, full: str, loader: Loader, ttl_s: float | None) -> Any:
"""Fill under a cluster-wide lock; waiters read the result instead of recomputing."""
lock_key = full + ":lock"
token = secrets.token_hex(16)
lease_ms = max(self.wait_ms * 2, 1000)
won = await self.client.set(lock_key, token, nx=True, px=lease_ms)
if not won:
self.waited += 1
deadline = time.monotonic() + self.wait_ms / 1000
while time.monotonic() < deadline:
await asyncio.sleep(0.002)
raw = await self.client.get(full)
if raw is not None:
return Envelope.decode(raw).value
return await loader() # the holder died; a second fill beats a hang
try:
return await self._store(full, loader, ttl_s)
finally:
await self.client.eval(RELEASE_IF_OWNER, 1, lock_key, token)
The fallback after the deadline is a deliberate choice against purity. A strict single-flight implementation waits until the winner publishes or gives up, which in the presence of a crashed holder means waiting for the lock’s own lease to expire. Loading the value after a bounded wait lets a second query through in a rare failure case, and keeps the request path from inheriting another process’s death. The wait is bounded by wait_ms, the poll interval is two milliseconds, and both are constructor arguments because the right values depend on how long the loader takes rather than on the cache.
TTL jitter belongs in the same object, and for a related reason. A batch job that warms ten thousand keys in one loop writes ten thousand TTLs that are all a few milliseconds apart, and they will all expire within the same few milliseconds. The probe’s stampede is one key; a synchronised batch is thousands of keys stampeding their own fills at once, which is the same failure at a scale the database cannot absorb. Spreading each TTL by up to 20 ms of randomness is enough to break the synchronisation, and the cache applies a ratio to every write it makes.
What the object does not do is also a design decision. It does not negative-cache a loader that raises, so a failing dependency is retried on the next request instead of being frozen into a cached exception. It does not serve a stale value when the refresh fails, because a stale value past its expiry is indistinguishable from a wrong one at the call site. And it does not compress, because compression trades a measurable amount of CPU for a measurable amount of memory, and that trade belongs to the value type rather than to the cache.
7. A lock is two operations, and the release is the dangerous one
Acquiring a lock is one atomic command: SET key token NX PX lease. Every language’s documentation says so, and every naive implementation gets it right. Releasing a lock is where they go wrong, because releasing is not one operation. The holder deletes the key, and between the decision to delete and the delete itself the lease can expire and another worker can take the lock. What follows is the classic three-worker interleaving, and it is worth walking through slowly because the timing is what makes it invisible in testing.
- Worker A takes the lock with a 250 ms lease, plans 400 ms of work, and is descheduled or blocked on an external call for longer than the lease.
- The lease expires. Worker B, which has been retrying since 260 ms, takes the lock and begins its own critical section.
- Worker A finishes its work and releases the lock. If the release is a plain
DEL, it deletes the key that now belongs to B. - Worker C, retrying since 420 ms, takes the free lock and enters the critical section while B is still inside it.
The probe re-enacts exactly that, with a counter incremented by every worker that believes it holds the lock, so the overlap is recorded rather than argued about. Worker B stays inside its critical section for 200 ms, comfortably inside its own lease, so any overlap between B and C is caused by the release and by nothing else. Thirty trials per mode, real threads, real sleeps, one Redis. The timing is arranged so that the interleaving is reached every time: what the table reports is whether the release can lose that race, not how often a production system would lose it.
| Release mode | Trials where the release deleted another holder’s key | Trials where two holders overlapped | Time C was admitted (median) | Value the release script returned |
|---|---|---|---|---|
Plain DEL | 30 | 30 | 421.1 ms | DEL always succeeds |
| Lua compare-and-delete | 0 | 0 | 463.2 ms | 0 (not the owner) |
The timing column is the whole story. With a plain delete, C was inside the lock at 421.1 ms – about 260 ms plus the work A never finished – while B was still working until roughly 260 ms plus 200 ms. With the compare-and-delete release, C could not enter until B released its own key at 463.2 ms, and the overlap count is zero across every trial. The release script also reports the difference honestly: it returned 0 in every Lua trial because A no longer owned the key, while the plain delete had no way to know and said nothing.
"""Acquire atomically, release only what you still own."""
RELEASE_IF_OWNER = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
end
return 0
"""
EXTEND_IF_OWNER = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('pexpire', KEYS[1], ARGV[2])
end
return 0
"""
async def acquire(client, key, token, lease_ms):
"""SET NX PX is one round trip and cannot be interleaved."""
return await client.set(key, token, nx=True, px=lease_ms)
async def release(client, key, token):
"""Delete the key only if we still hold it; the check and the delete are one command."""
return bool(await client.eval(RELEASE_IF_OWNER, 1, key, token))
Two properties of that script matter and are easy to lose. The comparison and the deletion happen inside one Lua invocation, which Redis executes atomically, so there is no window between them; a GET followed by a conditional DEL from the client has exactly the window the script removes. And the token has to be unique per acquisition, not per worker, because a worker that acquires the same lock twice must not be able to release the second acquisition with the first one’s identity. A 128-bit random value per acquisition – secrets.token_hex(16) in the module, the same amount of randomness as a UUID – is the simplest thing that satisfies both, and the obvious cheap alternative does not: a token built from the process id and the object’s address is copied verbatim into a forked worker, so two processes can present the same identity to the same lock.
The measured consequence of getting this wrong is not a lost lock. It is a lost transaction: two workers inside the same critical section is precisely the condition the lock existed to prevent, and it arrives silently, in the small percentage of requests where a lease expires under load. That is the shape of every double-charge and every duplicate-email story in the incident archives: not a bug in the payment code, but a release that could not tell whose key it was deleting.
8. The watchdog: a lease that renews while the holder is alive
The release race is one half of the lost-lock problem. The other half is the holder that simply takes too long: a lease exists because a crashed worker must not block a queue forever, and the same lease will expire under a worker that is alive but slow. Garbage collection, a database call that hit a lock wait, a container that got throttled, a debugger – any of these can stretch a critical section past the number somebody typed when they wrote the lease.
The probe sets the two numbers in opposition on purpose: a lease of 300 ms against 1200 ms of work, with a competitor that begins retrying at 350 ms and keeps going until 1400 ms. One mode runs a watchdog that renews the lease every 100 ms, which is a third of the lease; the other mode does not.
| Mode | Trials where the lock was stolen | Extensions issued | Least lease left just before a renewal | Time of theft (median) |
|---|---|---|---|---|
| No watchdog | 10 of 10 | 0 | expired before the work ended | 350.927 ms |
| Watchdog renewing every 100 ms | 0 of 10 | 12 | 199 ms | never entered |
Without the watchdog the lock was taken in every trial, at 350.927 ms – one lease length plus the poll interval. With it, the competitor polled for the whole window and never got in: at each renewal the probe read the remaining lease before renewing it, and the smallest value it ever saw was 199 ms. The extension count, 12 for 1200 ms of work, is exactly what the interval predicts, and it is also the number to watch in production: a critical section that suddenly needs ten times as many extensions is a performance problem that will become a correctness problem the moment one renewal misses its deadline.
The reserve at each renewal is the number that decides how much jitter the loop can absorb, and it is smaller than it looks. With a lease of 300 ms and a renewal every 100 ms, each renewal happens with about 199 ms left: two thirds of the lease, measured, not the full lease the extension then restores. One missed renewal carries the holder to the next slot with about a third of the lease (100 ms) in hand, which is survivable. Two consecutive misses put the next attempt at the expiry boundary itself – the third slot is 300 ms after the last extension – and from there the outcome is a race between the renewal and the key’s own expiry. So the loop tolerates one lost renewal, not two, and a scheduler hiccup long enough to lose two is a lost lease no matter how the interval is tuned.
from __future__ import annotations
import asyncio
from typing import Final
EXTEND_IF_OWNER: Final = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('pexpire', KEYS[1], ARGV[2])
end
return 0
"""
class DistributedLock:
async def extend(self) -> bool:
"""Renew the lease once; returns False when the key is no longer ours."""
result = int(await self.client.eval(EXTEND_IF_OWNER, 1, self.key, self.token,
self.lease_ms))
if result:
self.extensions += 1
return True
self.lost.set()
return False
async def _renew(self) -> None:
interval = self.lease_ms / 3000.0
while not self.lost.is_set():
await asyncio.sleep(interval)
if not await self.extend():
return
async def _stop_watchdog(self) -> None:
task = self._watchdog
self._watchdog = None
if task is None or task.done():
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
The renewal is the same compare-and-extend as the release is a compare-and-delete, for the same reason: a worker whose lease already expired must not extend somebody else’s lock. Two properties of the loop are not obvious from the code. It sleeps a third of the lease rather than half, which leaves a reserve of about 199 ms at every renewal: enough to absorb one scheduling hiccup, not two. And it stops on the first failed extension rather than retrying: if the key is gone, the holder is already outside its lease and the only correct thing to do is tell the application, which is what the lost event is for.
That event is the part most implementations omit, and it is the part that makes the watchdog honest. Extending a lease does not make a long critical section safe; it makes it likely to stay safe. When the extension fails, the critical section is already running with no protection, and the code inside it has to decide whether to abort, to re-check its invariants, or to finish and reconcile. A watchdog without a lost signal is a watchdog that converts a detectable problem into a silent one.
Production SRE Note: Renew at a third of the lease, stop on the first failure, and surface the failure to the critical section. Those three rules come from the arithmetic above: a lease of 300 ms renewed every 100 ms leaves about 199 ms at each renewal, survives one missed renewal with about 100 ms to spare, and loses the lease when two renewals in a row miss.
9. Fencing: the write that arrives late must not win
Everything so far assumes the lock holds. A single Redis instance with a lease, a watchdog and an atomic release does hold, as long as the holder can talk to it and the process is scheduled. The interesting failure is the one no client-side protocol can rule out: the holder is paused for longer than the lease, the lock legitimately moves to another worker, and then the paused worker wakes up and writes. Its lock check happened before the pause; its write happens after. Nothing in the client can detect the gap, because from the client’s point of view no time passed.
Fencing moves the check to the resource, but the check is not a version comparison. Each acquisition takes a monotonically increasing token together with the lease, the write carries that token, and the record keeps the last token it accepted and refuses anything that is not strictly greater. A version column compared with the value the writer read is optimistic concurrency control: it rejects a lost update only if the writer read the row and the compare happens in the same statement, and it says nothing about who is allowed to write. A fence token comes from the lock, so the writer needs no read at all, and the record rejects a write whose lease has already been replaced. In the probe the record is a Redis hash holding balance and last_token, updated by a Lua script; in PostgreSQL the same rule is an UPDATE ... WHERE last_token < ? on a column the write sets to its own token.
| Mode | Lost updates | Stale writes rejected | Final balance | Last accepted token |
|---|---|---|---|---|
| Lock only, no token | 20 of 20 | 0 | 950 | 1 |
| Lock plus fencing token | 0 of 20 | 20 | 900 | 2 |
The probe makes the interleaving deterministic on purpose – a 250 ms lease, a 400 ms slow worker, a fast worker that arrives at 260 ms – so the outcome repeats in every trial. That repetition is not a frequency estimate; it is what a constructed race looks like when it runs. The point of the table is the direction: the fast worker wrote 900 from the current state, the slow worker, which had read the state before the fast worker existed, wrote 950 afterwards and won by arriving later. The balance after both writes is 950, the value the stale writer computed. The lock was not held by two workers at the same time; it stopped being a lock the moment the lease expired, and the write path had no way to know.
With the token, the stale write is refused 20 times out of 20, the final balance is the correct 900, and the record’s last accepted token stays at the fast worker’s fence, 2. The cost is one extra integer per write and one comparison in the update statement. The cost of not having it is that every write path has to be trusted to be the only writer, which is exactly the assumption a lease invalidates.
"""Fence every acquisition, and make the writer of record reject a stale token."""
TAKE_LOCK = """
if redis.call('set', KEYS[1], ARGV[1], 'nx', 'px', ARGV[2]) then
return redis.call('incr', KEYS[2])
end
return 0
"""
FENCED_WRITE = """
local last = tonumber(redis.call('hget', KEYS[1], 'last_token') or '0')
if tonumber(ARGV[1]) > last then
redis.call('hset', KEYS[1], ARGV[3], ARGV[2], 'last_token', ARGV[1])
return 1
end
return 0
"""
async def take_lock(client, key, token, lease_ms, fence_key=None):
"""The lease and its token are granted in the same script, in the same order."""
fence = fence_key or f"{key}:fence"
result = int(await client.eval(TAKE_LOCK, 2, key, fence, token, lease_ms))
return result or None
async def fenced_write(client, key, fence, value, field="balance"):
"""True when the store accepted the write; False when a newer token got there first."""
result = int(await client.eval(FENCED_WRITE, 1, key, fence, value, field))
return bool(result)
The one-script acquisition exists because two commands would break the only property fencing needs. With SET NX PX followed by a separate INCR, a holder paused between the two commands holds a lease and no token; the lease can expire, a second holder can take it and receive the lower token, and the paused holder can then wake up and receive a higher one – even though it no longer holds the lock. The tokens would no longer follow the order in which the leases were granted, and the stale write with the higher token would be the one the record accepts. One EVAL removes the window; it is also why a failed acquisition consumes no token, so the sequence stays gap-free and meaningful.
The monotonically increasing counter has one requirement that is easy to miss: it must come from the same place the lock comes from, and it must never go backwards across a failover. On a single instance INCR is enough. Across a promoted replica, a counter that was replicated lazily can go backwards, which is why Kleppmann’s argument about locks and fencing ends at the storage layer rather than at the cache: the token must be ordered by whoever arbitrates the write, not by the cache that hands out leases. When the cache and the store are the same Redis, the question does not arise; when they are not, the counter belongs in the database sequence, and Redis only distributes the lease.
For the same reason, a fencing token is not a substitute for an idempotency key. Fencing stops an old writer from overwriting a new one; it does not stop the same writer from applying its write twice, because a retry after a timeout is indistinguishable from a first attempt unless the write carries its own identity. The two mechanisms answer different questions – who is allowed to write, and whether this write already happened – and a payment path needs both.
The shortest path is often the client’s own lock. client.lock(name, timeout=..., blocking_timeout=...) returns redis.lock.Lock in the sync client and redis.asyncio.lock.Lock in the async one: acquisition is SET NX PX with a uuid.uuid1().hex token, release is the same compare-and-delete Lua script shown above, and extend() and reacquire() renew the lease without releasing it.
What the built-in lock does not carry is the part this section measured. There is no background watchdog, so renewal is a call the caller has to schedule. There is no fencing token: acquire() returns a boolean, the token stays private to the lock object, and a write path cannot order itself against a lease it has already lost. And with the default timeout=None the key never expires at all, which is the deadlock the class’s own documentation leaves to the application.
The blocking acquisition is a polling loop with a sleep interval, which is the fixed-delay policy measured in section 10. So the built-in is the right tool for a short critical section, or a flag where a lost lock only costs duplicate work and the caller can renew on its own schedule. The Lua in this article earns its place when the section can outlive the lease (watchdog), when the write has to be ordered by a monotonic token (fencing), when the lease and its token must be granted atomically, or when the lock shares an instance whose memory policy can evict it (section 14).
10. Contention: the backoff that makes it worse
A lock that is correct can still be slow enough to cause an outage, and the mechanism is the retry loop. Twenty-four workers contending for one lock, each doing forty acquisitions of 5 ms of work, is a small queue with a fixed service time: the theoretical throughput is one acquisition per hold, so a well-behaved set of workers should finish the 960 acquisitions in about 4.8 seconds of pure hold time. The fixed 20 ms delay came closest, at 5.361 s. Full jitter took 5.796 s, and spin took 9.944 s.
Three retry policies were measured against that shape: spin, which retries immediately; a fixed delay of 20 ms; and full jitter, which sleeps a uniform random amount below a ceiling that doubles per attempt up to 400 ms. The acquire timeout was 3 s and the lease 1000 ms in all three.
| Retry policy | Total SET NX attempts | Attempts per acquisition | Failed attempts within 2 ms of another | p50 wait | p99 wait | Acquisitions completed | Throughput |
|---|---|---|---|---|---|---|---|
| Spin | 103,689 | 108.01 | 100% | 147.398 ms | 1046.19 ms | 960 of 960 | 96.5/s |
| Fixed 20 ms | 5,566 | 5.8 | 92.4% | 0.109 ms | 1660.66 ms | 957 of 960 | 178.5/s |
| Full jitter | 1,463 | 1.52 | 34.4% | 0.114 ms | 1817.64 ms | 950 of 960 | 163.9/s |
Two figures in the fixed-delay row describe opposite halves of the same distribution. Its p50 wait is 0.109 ms, because more than half of its 957 completed acquisitions took the lock on the first SET NX and never waited at all; the 5.8 attempts per acquisition in that same row are carried by the minority that lost the draw again and again – the worst acquisition there needed 149 attempts and the row’s p99 wait is 1660.66 ms. The mean of a retry loop is a property of its tail, not of the typical acquisition, which is why the attempt count has to be read beside the percentiles rather than instead of them.
Spin is the disaster the table is built to show. It produced 103,689 attempts for 960 acquisitions, 108.01 per acquisition, and it was slower in wall-clock terms than either alternative: 9.944 s for the whole run against 5.361 s with a fixed delay. The mechanism is not subtle – the retry loop competes with the work for the same Redis instance and the same CPU – but it is invisible in staging, because a single worker never spins.
Full jitter is not the fastest policy in that table, and pretending otherwise is the usual mistake in retry write-ups. The fixed delay finished the run in 5.361 s against 5.796 s for jitter, at 178.5 acquisitions per second against 163.9, completed 957 of 960 acquisitions against 950, and left 3 at the acquire timeout against 10. What jitter buys is the work the retry loop generates and the shape of it. Every count in the attempt column is a total, the successful acquisition included: the fixed delay’s 5,566 attempts are 957 takes plus 4,609 refusals, and jitter’s 1,463 are 950 takes plus 513 refusals. Jitter cut that total by a factor of 3.80 against the fixed delay and 70.9 against spin, and it desynchronised the refusals so that only 34.4% of them landed within two milliseconds of another one, against 100% for spin and 92.4% for the fixed delay. A refusal is a command the server still executes and then discards, so the convoy is the load this table measures, and the trade between the two rows is explicit: the fixed delay finishes sooner and leaves fewer acquisitions at the timeout, while jitter spends that time to keep the instance out of the convoy.
It also exposed the cost nobody mentions: full jitter starved workers. 10 acquisitions hit the acquire timeout and were never completed, against 3 with the fixed delay, and the unluckiest worker spent 5580.2 ms inside the run against 5147.4 ms. Randomising the wait removes the convoy but also removes the rough ordering that a fixed delay accidentally provides, so a worker can lose the lottery several times in a row. Redis locks have no queue and no fairness; a fixed delay is not a queue either, but it behaves like a rougher one.
from __future__ import annotations
import random
def full_jitter(attempt: int, base_s: float = 0.02, cap_s: float = 0.4,
rng: random.Random | None = None) -> float:
"""Sleep a uniform amount between 0 and an exponentially growing ceiling."""
ceiling = min(cap_s, base_s * (2 ** max(attempt - 1, 0)))
source = rng or random
return source.uniform(0.0, ceiling)
The practical rule that comes out of the table is to cap the retry budget in time rather than in attempts. With a fixed delay every waiter gets a turn roughly every 20 ms, which is fine when the hold time is 5 ms and disastrous when it is seconds; with jitter the number of attempts is small enough to be cheap when the hold time is short. Neither policy knows the hold time, so the timeout is the only parameter that adapts to it. If the queue itself matters – and for a lock guarding a user-visible action it usually does – then the right answer is not a retry policy at all but a queue: a list, a stream, or a database row that workers claim in order.
Production SRE Note: Three numbers decide whether the retry loop is the problem: attempts per acquisition, the fraction of failed attempts that cluster, and the worst worker’s total wait. Spin scored 108.01 attempts and 100% clustering; full jitter scored 1.52 attempts and 34.4% but left 10 acquisitions unfinished. Pick the failure you can observe.
11. The connection pool default that fails requests
The connection pool is the least interesting part of a Redis client until the day it is the reason for random failures. Both clients build the default pool from the same expression: redis.connection.ConnectionPool.__init__ for the sync client and redis.asyncio.connection.ConnectionPool.__init__ for the async one each carry max_connections = max_connections or 100 in the installed 8.1.0, and the ceiling is enforced when a connection is acquired, which raises MaxConnectionsError rather than waiting. Both halves of that sentence are surprising. The default is not unlimited, and the behaviour at the limit is an exception rather than a queue. Until 8.0.0 the same line defaulted to two to the thirty-first – effectively no ceiling at all – and the 8.0.0 release notes list the reduction to 100 under breaking changes, applied across both the sync and the async connection paths. That is why the module and the class are worth naming: application code writes redis.Redis(host=..., port=...), the client constructs the pool on its behalf, and an application that changed only the pinned version can start failing a fraction of its requests without a code change. The client does ship the alternative – BlockingConnectionPool, whose own defaults are smaller and whose acquisition waits for a free connection before it raises – and that is the class behind the blocking row of the table below.
The same release moved the rest of the connection defaults, under the same breaking-changes heading (#4082). socket_timeout and socket_connect_timeout now default to 5 seconds – DEFAULT_SOCKET_TIMEOUT in the client’s own redis/_defaults.py, assigned to both parameters in Connection.__init__ and Redis.__init__ – where 7.4.0 passed None and could wait on a silent peer indefinitely; the default retry went from three retries to 10 on a 10 ms base instead of a one-second one, with a 1 s cap; and retry_on_timeout stays False and is deprecated, because the default retry’s supported errors already include TimeoutError. The socket timeout is the one to notice in a service that also blocks: it applies to blocking commands too, so a BLPOP that waits longer than the socket timeout raises TimeoutError before the command’s own timeout can expire.
The default retry is also a layer, and two layers multiply. Every connection the pool hands out carries that Retry(..., retries=10), so a command that fails is re-sent inside the client before the caller ever sees the exception; the call_with_retry(attempts=3) helper in section 17 sits above it. Stacked, one logical failure can become 10 x 3 = 30 command attempts, each layer sleeping on its own schedule, and the delay the request waits out is the sum of both: the outer helper’s 3 attempts each pay for the inner retry’s 10 before the exception reaches them. Neither layer is wrong on its own; that is simply what two retries do when nobody counted them. In production one layer should own the budget. Either switch the client’s default off and retry only in application code (redis.Redis(..., retry=None), or Retry(NoBackoff(), 0), both of which leave the connection with zero retries in 8.1.0), or keep the client default and call the operation without a helper. What not to do is leave both on and reason about the retry count from one of them.
Four ways to reach the same server from 200 concurrent requests were measured, each against its own instance, 400 requests in total, one GET per request. The server’s own connected_clients was sampled every two milliseconds during the run, so the connection counts are the server’s view and not the client’s.
| Variant | Answered | Errors | Peak server connections | p50 | p99 | Wall clock |
|---|---|---|---|---|---|---|
| A client per request | 400 of 400 | 0 | 201 | 292.501 ms | 523.97 ms | 1.013 s |
| Shared pool, library default | 200 of 400 | 200 | 101 | 39.406 ms | 56.869 ms | 0.06 s |
| Blocking pool, 50 connections | 400 of 400 | 0 | 51 | 28.772 ms | 108.799 ms | 0.149 s |
| Bounded pool, 50 connections | 100 of 400 | 300 | 51 | 26.983 ms | 114.484 ms | 0.122 s |
The first row is what an application looks like when it builds a client per request, which is what a surprising number of dependency-injection setups do. It answered every request, at a p50 of 292.501 ms, because every request paid for a TCP connect and a Redis handshake. The peak connection count, 201, is one per in-flight request plus the sampler’s own connection, because nothing was reused. It is slow and expensive, but it is at least predictable.
The second row is the failure that produces bug reports nobody can reproduce. The pool capped at 100 connections, the load needed more, and 200 requests failed with MaxConnectionsError in 0.06 seconds. The requests that did get a connection were fast – a p50 of 39.406 ms – so the shape of the incident is a low-latency application that fails a fraction of its traffic under peak load, which looks like anything but a pool limit. Note the peak: 101 connections for a ceiling of 100, because the sampler sees the probe’s own connections alongside the pool’s.
The third row is the same ceiling with the queue restored. A blocking pool answered all 400 requests, held 51 connections, and paid for it in latency: p50 28.772 ms and p99 108.799 ms against 523.97 ms for the client-per-request variant. That is the trade you are actually making: a bounded number of connections, a bounded queue, and a latency that degrades instead of failing. The fourth row shows the same ceiling without the queue, and 300 failures.
from __future__ import annotations
import redis.asyncio as aioredis
DEFAULT_POOL_SIZE = 32
def make_pool(host: str = "127.0.0.1", port: int = 6379, *, db: int = 0,
max_connections: int = DEFAULT_POOL_SIZE, wait: bool = True,
socket_timeout: float = 1.0, socket_connect_timeout: float = 1.0,
health_check_interval: int = 30,
decode_responses: bool = True) -> aioredis.ConnectionPool:
"""Build a pool that waits for a free connection instead of raising.
``wait=True`` uses ``BlockingConnectionPool``: a caller waits at most ``timeout``
seconds for a connection and only then gets an error. ``wait=False`` keeps the
default raising behaviour but with a size you chose rather than 100.
"""
common = dict(host=host, port=port, db=db, socket_timeout=socket_timeout,
socket_connect_timeout=socket_connect_timeout,
health_check_interval=health_check_interval,
decode_responses=decode_responses)
if wait:
return aioredis.BlockingConnectionPool(max_connections=max_connections,
timeout=max(1.0, socket_timeout * 5), **common)
return aioredis.ConnectionPool(max_connections=max_connections, **common)
def make_client(host: str = "127.0.0.1", port: int = 6379, *, db: int = 0,
max_connections: int = DEFAULT_POOL_SIZE, wait: bool = True,
decode_responses: bool = True, **kwargs) -> aioredis.Redis:
"""A client that shares one bounded pool for the life of the process."""
pool = make_pool(host, port, db=db, max_connections=max_connections, wait=wait,
decode_responses=decode_responses, **kwargs)
return aioredis.Redis(connection_pool=pool)
Three settings in that factory are worth arguing for. The socket timeout is set explicitly to one second, which is a tightening of the 5-second default the 8.x client already carries rather than a rescue from a disabled one: the value to avoid is None, which is what 7.4.0 passed and which lets a call wait on a silent peer for as long as the network wants. A second is generous for a call that should take milliseconds, and a Redis call that hangs is worse than one that fails, because the failure is visible and the request can be retried while the hang consumes a worker. health_check_interval is set so that a pooled connection that died in the gap between requests is discovered on checkout instead of on use. And the pool size has a default that is a decision rather than a library’s accident – the right number is a function of the workers per process and the queues behind them, not of the server’s capacity, which is why the default here is smaller than the library’s own. The factory is asynchronous (redis.asyncio) for the same reason the rest of this article is: a synchronous pool called from an event loop blocks every other request while it waits for a connection.
12. A cache read is a round trip before it is anything else
The cheapest improvement available to a Python service that talks to Redis is not a better data structure. It is asking for fewer things separately. Every command is a request and a response on a socket, and on loopback that costs a fixed amount of work in the kernel and the client library regardless of what the command does. The probe measured that fixed cost on its own, with a thousand PINGs: a p50 of 87.652 microseconds and a p99 of 126.484 microseconds, with a mean of 84.072. Everything a real command costs sits on top of that floor.
To see the floor in context, the same 2000 keys of 200 bytes were fetched three ways, each timed three times with the fastest run reported: one GET per key, batches of 100 in a pipeline, and batches of 100 in a single MGET.
| Method | Wall clock for 2000 keys | Per key | Keys per second | Speed-up over sequential |
|---|---|---|---|---|
One GET per key | 0.192 s | 96 us | 10,416 | 1x |
| Pipelined, 100 per batch | 0.014 s | 7.01 us | 142,588 | 13.71x |
MGET, 100 keys per call | 0.0056 s | 2.82 us | 354,781 | 34.29x |
The per-key cost of the sequential path, 96 microseconds, is close to the bare PING round trip, which is the whole point: the time is not spent in Redis, it is spent asking. Pipelining cut it to 7.01 microseconds and MGET to 2.82, because both amortise one round trip over many keys. On a real network with a fraction of a millisecond of latency, the difference is not a speed-up measured in percent – it is the difference between a cache that can serve a page in one round trip and one that needs twenty.
This matters for the cache design in section 6 more than it matters for bulk jobs. A page that reads forty cached fragments and asks for them one at a time pays forty round trips and forty event-loop scheduling decisions to serve one request; the same page with a pipeline pays one. That is also why the envelope in section 5 is a single key rather than a value key plus a metadata key: metadata stored separately doubles the round trips of every read, and the second read buys nothing that the envelope could not carry.
"""Same keys, three call shapes; run against any reachable server."""
import os
import time
import redis
URL = os.environ.get("REDIS_URL", "redis://127.0.0.1:6379/0")
client = redis.Redis.from_url(URL)
BATCH = 100
def seed(count: int) -> None:
pipe = client.pipeline(transaction=False)
for index in range(count):
pipe.set(f"item:{index}", "x" * 200)
pipe.execute()
def sequential(count: int) -> float:
started = time.perf_counter()
for index in range(count):
client.get(f"item:{index}")
return time.perf_counter() - started
def pipelined(count: int) -> float:
started = time.perf_counter()
for start in range(0, count, BATCH):
pipe = client.pipeline(transaction=False)
for index in range(start, min(start + BATCH, count)):
pipe.get(f"item:{index}")
pipe.execute()
return time.perf_counter() - started
def batched(count: int) -> float:
started = time.perf_counter()
for start in range(0, count, BATCH):
client.mget([f"item:{index}" for index in range(start, min(start + BATCH, count))])
return time.perf_counter() - started
if __name__ == "__main__":
seed(200)
for name, fn in (("get", sequential), ("pipeline", pipelined), ("mget", batched)):
print(f"{name:9s} {fn(200) * 1000:.1f} ms for 200 keys")
13. What a cached value actually costs
Capacity planning for a cache goes wrong in a specific way: someone multiplies the number of keys by the size of the values, buys memory for that number, and then watches the instance fill at roughly twice the predicted rate. The gap is the per-key overhead, and it is not a constant – it depends on the allocator’s size classes and on how the value is encoded.
MEMORY USAGE answers the question for one key, including the hash table entry, the key string, the object header and the allocator’s rounding. Measured across seven payload sizes from sixteen bytes to a hundred kilobytes, the overhead is roughly fixed for small values and roughly proportional for large ones:
| Payload | MEMORY USAGE | Overhead | Bytes stored per payload byte |
|---|---|---|---|
| 16 B | 88 B | 72 B | 5.5 |
| 64 B | 136 B | 72 B | 2.125 |
| 100 B | 168 B | 68 B | 1.68 |
| 256 B | 376 B | 120 B | 1.469 |
| 1,024 B | 1,336 B | 312 B | 1.305 |
| 10,240 B | 12,344 B | 2,104 B | 1.205 |
| 102,400 B | 114,744 B | 12,344 B | 1.121 |
A sixteen-byte value occupies 88 bytes, five and a half times its payload, because the key, the object and the allocator’s minimum block are all larger than the value. A hundred-byte value, the shape of a small JSON fragment, occupies 168 bytes. The practical version of the table is the aggregate: ten thousand keys of 100 bytes each consumed 1,915,696 bytes of memory, which is 191.57 bytes per key rather than 100. A cache sized by payload is undersized by a factor that grows as the values get smaller, and small values are exactly what a fragment cache stores.
The second half of the memory story is encoding, and it is a step function rather than a slope. A hash with few short fields is stored as a listpack – one contiguous blob with no per-field overhead – and the same hash beyond the configured limits becomes a real hash table with an entry per field. Redis defaults to 512 entries and 64 bytes per value, and both limits bite:
| Fields | Bytes per field value | Encoding | Total MEMORY USAGE | Bytes per field |
|---|---|---|---|---|
| 100 | 10 B | listpack | 1,848 B | 18.48 |
| 512 | 10 B | listpack | 10,296 B | 20.11 |
| 600 | 10 B | hashtable | 37,104 B | 61.84 |
| 100 | 80 B | hashtable | 13,936 B | 139.36 |
The jump from 20.11 to 61.84 bytes per field – one extra field crossing the entry limit – triples the cost of the object. The last row shows the other limit: the same hundred fields with eighty-byte values are stored as a hash table from the start, at 139.36 bytes per field, because a single value exceeded the value limit. If a cache stores per-user records as hashes, this is the difference between a session store that fits and one that does not, and it is decided by whether one field in the schema occasionally holds a long string.
Production SRE Note: Two rules that follow from the table: size a cache by measured bytes per key, not by payload, and keep the field values of stored hashes below the listpack limit – a long field converts the whole object, not just that field.
14. maxmemory and the policy that eats your locks
The default configuration of a Redis server has no memory limit at all: maxmemory is zero, and the process grows until the operating system decides otherwise. The probe’s fresh instances started with a policy of noeviction, which is the policy that refuses writes rather than evicting. Both defaults are defensible for a primary data store and wrong for a cache that also holds locks.
To measure what a full instance does, twelve thousand keys of 200 bytes were written into a 3mb instance and then read with a Zipf-distributed workload of 30,000 reads, six rounds per policy, each round with its own read order, median reported. Every key carries a one-hour TTL, the way a cache key should, and every refused write is counted individually rather than per batch, so the eviction column and the refusal column describe the same twelve thousand writes. The read orders are identical across policies, so the differences come from eviction rather than from a luckier access pattern.
| Policy | Hit rate (median) | Hit rate range | Hot-set hit rate (median) | Keys evicted (median per round) | Writes refused (median per round) |
|---|---|---|---|---|---|
noeviction | 97.41% | 97.32% to 97.44% | 100% | 0 | 4,722 |
allkeys-lru | 67.39% | 51.62% to 72.63% | 69.95% | 4,863 | 0 |
allkeys-lfu | 62.93% | 26.93% to 76.15% | 64.15% | 4,863 | 0 |
volatile-lru | 71.76% | 34.31% to 73.82% | 75.06% | 4,863 | 0 |
The hit rates are less tidy than a marketing table would be, and the range column is there on purpose. Eviction samples a handful of keys and picks a victim from them, so which of the hot keys survives a fill is partly luck; one allkeys-lru round finished at 51.62% and another at 72.63% with identical keys and identical read orders. That variance is itself the finding: a cache sitting close to its memory limit has a hit rate with a wide distribution, and capacity plans that assume the median are surprised by the low tail. What the table does establish is the ordering of the mechanisms: no eviction keeps everything and refuses the writes that would need space, the allkeys policies evict from the whole keyspace, and the volatile policy evicts only among keys that carry a TTL – with an expiry on every key, which is the state a cache should be in, it lands in the same band as allkeys-lru, and the gap between 67.39% and 71.76% is sampling noise rather than policy: both sit well inside the range either policy produced with identical keys and identical read orders.
The write-refusal column is where a cache becomes an incident, and it is also where the two columns can finally be compared. noeviction refused 4,722 of 12,000 writes per round: the instance was full, so every key that did not fit became an error the application has to handle. allkeys-lru and allkeys-lfu refused none and evicted 4,863 instead – within a few percent of the number noeviction refused, the same pressure seen from the other side. volatile-lru refused none here either, because every key in this run carried a TTL. The same fill against a keyspace without TTLs, under volatile-lru, refused 3,632, the same failure with a smaller number for a physical reason: the TTL itself costs memory, so 7,278 keys fit with an expiry where 8,368 fit without one, and the TTL-free fill had more room before it hit the wall. A volatile policy on a keyspace without TTLs fails exactly like no policy at all, only a little later.
Then there is the question the hit rate does not answer: what happens to a lock key. A lock is taken with SET NX PX, so it has a TTL, and a lease without a TTL is not a lease – its whole purpose is to disappear if the holder dies. That makes a lock exactly the kind of key a volatile policy is allowed to evict, which is the opposite of the folklore. The real question is not whether volatile-* protects a lock, but whether any policy that also stores cache entries can. A hundred trials per policy, each taking a lease and a TTL-free fence key and then writing enough cache keys to force evictions:
| Policy | Trials where the lease vanished | Trials where the fence key vanished | Trials where the lease write itself was refused |
|---|---|---|---|
noeviction | 0 of 100 | 0 of 100 | 100 of 100 |
allkeys-lru | 1 of 100 | 1 of 100 | 0 of 100 |
allkeys-lfu | 2 of 100 | 1 of 100 | 0 of 100 |
volatile-lru | 0 of 100 | 0 of 100 | 0 of 100 |
Two instances: cache allkeys-lru, locks noeviction (16mb) | 0 of 100 | 0 of 100 | 0 of 100 |
The honest reading is narrower than a warning label and worse than a reassurance. Under allkeys-lru the lease was evicted in 1 of 100 trials and the fence key in 1; under allkeys-lfu in 2 and 1; under volatile-lru neither key was evicted in 100 trials. Those numbers are small, and they are the finding rather than a footnote: an eviction-enabled policy treats a lease as a candidate, because a lease is a key with a TTL, and whether the sampler picks it depends on the sample. The volatile result is the easiest row to misread in either direction. It does not make volatile-lru safe: that policy’s candidate set is exactly the keys that carry a TTL, and a lease is one of them by construction, so the hazard there is structural, and a zero in 100 trials is a statement about those trials rather than about the next 100. Nor does it rank the policies against each other: nothing in the mechanism reports which key it chose, so what the table establishes is that a lock key is in play, not how often a given policy will pick it. A lock whose survival is a matter of sampling is not a lock: one eviction is one second holder, and the failure does not announce itself. The fence key is not protected either – it vanished once under each allkeys policy – and noeviction on a shared instance does not help: the lease could not be taken at all in 100 of 100 trials, because the cache had filled the instance and the write was refused.
What survives the table is not a policy but a second instance. The last row is the shape to ship: a cache instance with allkeys-lru, a real maxmemory and a headroom alert, and a coordination instance with noeviction that holds nothing but leases and fence keys. Its 0 of 100 is structural rather than lucky – the churn cannot evict a key on a server it never connected to – and the measurement that sizes it is the memory per lease: ten thousand lease-and-fence pairs occupied 220.2 bytes each, so the instance is sized by the peak number of concurrent locks rather than by traffic. noeviction there is a feature: when it is full, taking a lock fails loudly, which is a bug in the lease count, instead of evicting a lease that somebody is holding. A cache and a coordination store have opposite failure modes, and the only reliable way to give each the one it needs is to stop putting them on one server.
from __future__ import annotations
from dataclasses import dataclass, field
import redis
DEFAULT_SAMPLE_RESERVE_RATIO = 0.25
@dataclass(frozen=True)
class Finding:
code: str
severity: str
message: str
@dataclass
class Audit:
maxmemory_bytes: int
policy: str
used_memory_bytes: int
findings: list[Finding] = field(default_factory=list)
@property
def headroom_ratio(self) -> float:
if self.maxmemory_bytes <= 0:
return 0.0
return 1.0 - self.used_memory_bytes / self.maxmemory_bytes
def audit_memory(client: redis.Redis, *, uses_locks: bool = True) -> Audit:
"""Read the instance's own configuration and report what it implies."""
config = client.config_get("maxmemory")
policy = client.config_get("maxmemory-policy")["maxmemory-policy"]
limit = int(config["maxmemory"])
used = int(client.info("memory")["used_memory"])
result = Audit(maxmemory_bytes=limit, policy=policy, used_memory_bytes=used)
if limit == 0:
result.findings.append(Finding(
"no_limit", "critical",
"maxmemory is 0: the instance grows until the host's OOM killer acts instead"))
elif used / limit > 1 - DEFAULT_SAMPLE_RESERVE_RATIO:
result.findings.append(Finding(
"no_headroom", "warning",
f"used memory is {100 * used / limit:.0f}% of the limit: normal traffic will evict"))
if policy.startswith("allkeys") and uses_locks:
result.findings.append(Finding(
"allkeys_policy", "critical",
"an allkeys-* policy may evict lock and fencing keys, which is a correctness bug"))
if policy.startswith("volatile") and uses_locks:
result.findings.append(Finding(
"volatile_policy", "warning",
"a lease lock carries a TTL, so volatile-* makes it a candidate for eviction; no trial "
"in the probe lost one, but that is sampling rather than protection, so locks belong "
"on a separate noeviction instance"))
elif policy.startswith("volatile"):
result.findings.append(Finding(
"volatile_policy", "warning",
"volatile-* evicts only keys with a TTL: writes fail once the TTL-free set fills memory"))
if policy == "noeviction":
result.findings.append(Finding(
"noeviction", "warning",
"noeviction refuses writes at the limit; fine for a bounded lock instance, an "
"incident for a cache"))
return result
The audit function is the runtime version of the argument in this section, and it reports the configurations that were measured rather than a general opinion: a missing limit, an allkeys policy on an instance that also holds locks, a volatile policy on an instance that holds leases (a lease has a TTL, so that policy can evict it), and an instance already close enough to its ceiling that ordinary traffic will start evicting. The severities follow the measurements rather than the folklore: an allkeys policy that shares an instance with locks is critical because the probe lost leases there, a volatile policy is a warning because the probe did not and the risk is architectural, and a missing limit is critical while a thin reserve is a warning. Each finding names the consequence, because “allkeys-lru on a shared instance” means nothing to the person who wrote the cache code and “may evict lock keys” does.
15. TTL accuracy, and the memory that outlives the key
Two properties of expiry matter to a cache and are routinely assumed rather than measured. The first is accuracy: a TTL is not a scheduler, it is a comparison against a clock, and the key does not disappear at the instant the TTL says – it disappears at the next moment something looks at it or the active cycle notices it. The second is memory: a key that is logically gone may still occupy bytes for a while, which is why an instance whose keys have all expired does not immediately show its baseline memory.
| Requested TTL | Measured lifetime (p50) | Median overshoot | Largest overshoot | Keys measured |
|---|---|---|---|---|
| 200 ms | 201.016 ms | 1.02 ms | 2.43 ms | 100 |
| 1000 ms | 1000.99 ms | 0.99 ms | 1.51 ms | 30 |
PX, polled every 0.5 ms.The overshoot is about a millisecond at both scales, which is smaller than the poll interval and therefore mostly an artefact of how the probe measures. The useful conclusion is the negative one: a TTL is accurate enough that a refresh strategy built on it does not need a safety margin of hundreds of milliseconds, and an XFetch refresh scheduled a few milliseconds before expiry lands where the arithmetic says. What the TTL does not do is fire an event by itself: with keyspace notifications enabled Redis publishes an expired event, but it is best-effort, and the event can arrive after the passive and active expiry cycles have already removed the key, or not arrive at all if the notification class is not configured. A cache that needs to act on expiry therefore needs a consumer listening to that stream or a scheduled sweep, not just a shorter TTL. The passive path is the one the probe measures: nothing happens at expiry except that the key stops being found.
The memory side is where the surprise lives. Five thousand keys of 100 bytes with a 500 ms TTL raised used_memory by 1,227,728 bytes for 500,000 bytes of payload. After the TTL passed, the logical state and the memory state disagreed for a while:
| Time after the last TTL | Keys still in the keyspace | used_memory above baseline |
|---|---|---|
| 50 ms | 61 | 103,920 B |
| 100 ms | 61 | 128,608 B |
| 200 ms | 61 | 64,096 B |
| 500 ms | 0 | 50,464 B |
| 1000 ms | 0 | 50,464 B |
| 2000 ms | 0 | 50,464 B |
Keys answer EXISTS with zero the instant their TTL passes, but 61 of them were still in the keyspace at 50 ms and the instance was still 103,920 bytes above its baseline. The active expire cycle is what actually removes them, and it runs on its own schedule; by 500 ms the keyspace was empty, and the byte count settled at 50,464 bytes above baseline rather than at it, because the allocator keeps freed pages. Two consequences for operations: an instance can be at its memory limit with a keyspace that reports almost nothing in it, and a metric that samples used_memory on a short interval will show exactly the sawtooth that operators learn to ignore instead of the leak they should be looking for.
"""How late does a TTL fire, and when does the memory come back?"""
import os
import time
import redis
URL = os.environ.get("REDIS_URL", "redis://127.0.0.1:6379/0")
client = redis.Redis.from_url(URL)
def lifetime_ms(ttl_ms: int, keys: int) -> list[float]:
"""Set each key, then poll until EXISTS says it is gone."""
measured = []
for index in range(keys):
key = f"ttl:{ttl_ms}:{index}"
started = time.perf_counter()
client.psetex(key, ttl_ms, "x")
while client.exists(key):
time.sleep(0.0005)
measured.append((time.perf_counter() - started) * 1000)
return measured
def memory_after_expiry(keys: int, ttl_ms: int, payload: int) -> list[dict]:
"""Logical expiry happens at the TTL; the bytes come back later."""
client.flushall()
baseline = client.info("memory")["used_memory"]
pipe = client.pipeline(transaction=False)
for index in range(keys):
pipe.psetex(f"lag:{index}", ttl_ms, "z" * payload)
pipe.execute()
time.sleep(ttl_ms / 1000 + 0.05)
samples = []
started = time.perf_counter()
for mark in (50, 200, 500):
remaining = mark / 1000 - (time.perf_counter() - started)
if remaining > 0:
time.sleep(remaining)
samples.append({"ms_after_ttl": mark, "dbsize": client.dbsize(),
"over_baseline": client.info("memory")["used_memory"] - baseline})
return samples
if __name__ == "__main__":
print("median lifetime:", sorted(lifetime_ms(200, 20))[10])
The distinction between logical and physical expiry also explains a class of confusing metric: a cache whose keys all have TTLs can report a keyspace of almost nothing and a memory figure close to its limit in the same scrape. Neither number is wrong. The keyspace counts keys, the memory counts pages, and the pages are released by a cycle that nobody scheduled.
16. The configuration this article would ship
Every recommendation below is a consequence of a measurement in an earlier section, and every value is a starting point rather than a law: the cache TTL belongs to the data, the lease belongs to the critical section, and the pool size belongs to the process. What is not negotiable is that each of these settings exists explicitly in configuration rather than as a library default nobody read.
| Setting | Value to start from | Why that value | Evidence |
|---|---|---|---|
| Cache TTL | per endpoint, with a jitter ratio | a fixed TTL synchronises every key written by the same job | Table 3 |
Refresh aggressiveness (beta) | 1 | one compute-time of runway at roughly a third trigger probability | Table 5 |
| Envelope fields | value, compute time, expiry | early refresh needs both numbers, and one key keeps reads to one round trip | Table 12 |
| Lock lease | at least twice the measured worst-case critical section | a 300 ms lease lost a 1200 ms section in every trial | Table 8 |
| Watchdog interval | a third of the lease | a single missed renewal leaves a third of the lease; two in a row put the next attempt at expiry | Table 8 |
| Release | Lua compare-and-delete on a per-acquisition token | a plain delete removed another holder’s key in all 30 trials of the constructed interleaving, and a compare-and-delete in none | Table 7 |
| Fencing | monotonic token checked by the writer of record | without the check the stale write overwrote the newer one in 20 of 20 constructed interleavings, which is what a lease can produce in production | Table 9 |
| Retry | full jitter, ceiling capped, budget in seconds | jitter cut total attempts 3.80x against the fixed delay (5,566 to 1,463 attempts) and clustered only 34.4% of refusals against 92.4% | Table 10 |
| Pool | bounded and waiting, per process | the library default raised 200 errors in 0.06 s | Table 11 |
| Socket timeout | about a second, set explicitly | 8.x already defaults to 5 s; tighten it to a second rather than set it to none, which is what the 7.4.0 client defaulted to – a hung call consumes a worker, a failed one can be retried | Table 11 |
maxmemory | a number, not zero | an unconfigured instance grows until the host decides | Table 15 |
| Eviction policy | allkeys-lru on the cache instance | a lease carries a TTL, so every eviction-enabled policy may evict it; the losses are in Table 16, and a cache-only instance has no lock to lose | Table 16 |
| Lock instance | separate server, noeviction, sized by peak concurrent leases | ten thousand lease pairs measured 220.2 bytes each; a full instance then refuses the lease instead of evicting one that is held | Table 16 |
| TTL discipline | checked in CI, not by memory | volatile-* refused 3,632 writes on a TTL-free keyspace | Table 15 |
Two entries deserve a note because they are the ones teams argue about. The lock lease should be derived from a measured worst case rather than a round number: the probe’s 300 ms against 1200 ms is not a warning about 300 milliseconds in particular, it is the ratio that matters. And the fencing requirement is not limited to financial systems – any write whose loss is silent needs it, and “silent” describes most updates that carry neither a version nor a token.
17. What this machine cannot tell you
The measurements above are real, and they are narrower than they look. Every one of them ran against a single Redis instance on loopback, with one Python process, on 2 vCPUs, with no replication, no cluster, no persistence enabled and no network between the client and the server. Each of those absences bounds a claim.
- Replication and failover: a lock that is lost during promotion is the case fencing exists for, and it was reasoned about from the protocol rather than re-enacted. The token mechanism was measured; the failover was not.
- Network latency: the sequential read in Table 12 costs 96 microseconds on loopback. Across a network it costs the round-trip time plus that, and every statement about pipelining becomes more true rather than less.
- Persistence: an instance with append-only file syncing enabled spends time on disk that these instances never spent, and a lease measured here is optimistic for that configuration.
- Host memory pressure: the eviction measurements show a policy reaching its own ceiling. They say nothing about a cgroup limit or an out-of-memory killer picking the Redis process.
- Client versions: the pool default is a property of
redis8.1.0. The 7.4.0 and 6.4.0 clients default to an effectively unlimited pool and fail differently, so the section that quotes the source is the one to re-check after an upgrade.
The module carries 51 tests that run against a real server started by the test session, and they pass in 3.16 s on this machine. The tests are the part of the work that can be handed to somebody else without an argument about methodology, because they assert the properties rather than the numbers: one fill for twenty-five concurrent readers, a watchdog that keeps a lease alive across three lease lengths, a release that refuses a key it does not own, a computed probability that matches its closed form to within a couple of percent.
| Test file | Tests | What it pins down |
|---|---|---|
test_keys.py | 11 | key naming, TTL jitter window, envelope round trip, the XFetch probability against its closed form, the zero-draw guard |
test_cache.py | 11 | one fill per cold key across twenty-five readers, one refresh per hot key, waiter fallback, jittered TTL, version rejection |
test_locks.py | 15 | acquire and release, timeout, release refusal, watchdog survival, lost-lease detection, monotonic fences, rejection of a stale token |
test_pool_audit_retry.py | 14 | pool types and limits, the memory audit findings, retry exhaustion and non-retryable errors, jitter ceilings |
The test that pins the refresh decision is the one worth copying, because it asserts a distribution rather than a value: twenty thousand draws per remaining-TTL ratio, each compared with the closed form, with a tolerance of two percentage points. A refactor that turns the exponential draw into a uniform one still compiles, still returns a value, and fails this test on the first row.
"""The refresh probability is checked against its closed form, not asserted by eye."""
import math
import random
from rediskit.keys import Envelope, should_refresh
TOLERANCE = 0.02
TRIALS = 20_000
def test_probability_matches_the_closed_form():
rng = random.Random(11)
for remaining in (0.005, 0.02, 0.08):
envelope = Envelope("v", delta_s=0.02, expires_at=500.0 + remaining)
hits = sum(should_refresh(500.0, envelope, 1.0, rng) for _ in range(TRIALS))
expected = math.exp(-remaining / 0.02)
assert abs(hits / TRIALS - expected) < TOLERANCE
from __future__ import annotations
import asyncio
import random
from typing import Awaitable, Callable, TypeVar
import redis
T = TypeVar("T")
RETRYABLE = (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError,
redis.exceptions.BusyLoadingError)
def full_jitter(attempt: int, base_s: float = 0.02, cap_s: float = 0.4,
rng: random.Random | None = None) -> float:
ceiling = min(cap_s, base_s * (2 ** max(attempt - 1, 0)))
source = rng or random
return source.uniform(0.0, ceiling)
async def call_with_retry(operation: Callable[[], Awaitable[T]], *, attempts: int = 3,
base_s: float = 0.02, cap_s: float = 0.4,
rng: random.Random | None = None,
retry_on: tuple[type[BaseException], ...] = RETRYABLE) -> T:
"""Run ``operation`` up to ``attempts`` times, sleeping full jitter between tries."""
if attempts < 1:
raise ValueError("attempts must be at least 1")
last: BaseException | None = None
for attempt in range(1, attempts + 1):
try:
return await operation()
except retry_on as exc:
last = exc
if attempt == attempts:
break
await asyncio.sleep(full_jitter(attempt, base_s, cap_s, rng))
assert last is not None
raise last
The retry helper is deliberately small and deliberately not automatic. Wrapping every call in a retry is how a cache turns a failing dependency into a slow one: 3 attempts with a capped backoff multiply the worst-case latency by 3, and on a client that still carries the 10-retry default from section 11 they multiply it by 10 again, so one of the two layers has to be switched off before either budget means anything. At the moment the store is failing, that is exactly when the extra latency hurts. Retry belongs on the call that can tolerate a second attempt, with a budget the caller chose, and it belongs with a cap that is smaller than the caller’s own timeout.
18. The runbook, in the order to do it
For a service that already has Redis and is about to have an incident, the order matters more than the individual steps, because each one changes what the next one will look like in the metrics.
- Decide what each key class is: a cache entry with a TTL, a lock with a lease, or state that must not be evicted – and put the lock class on its own
noevictioninstance. Nothing downstream works until this split exists, because every eviction-enabled policy can evict a lease. - Put a TTL on every cache write and check it in CI. A volatile policy with a TTL-free keyspace refused 3,632 writes in the probe; the production version of that is a full instance that cannot evict.
- Set
maxmemoryand read the policy back at start-up, the wayaudit_memorydoes, so a wrong policy is a failed deploy rather than a page nobody wants at night. - Add a single-flight fill to every read-through path, with a bounded wait and a fallback load, and count waits and fills separately from hits and misses.
- Add XFetch to the keys that are hot enough to stampede an expiry. The decision rule needs the compute time in the envelope; adding it retroactively is a change to the value format, so do it once.
- Take every lock with a lease and a fence token in one script, release it with a compare-and-delete, and check the token in the write that lands. This is the change with the best ratio of risk removed to lines edited.
- Add a watchdog only where the critical section can outlive the lease, and wire its lost event to something that aborts or reconciles. A watchdog without a handler is worse than none, because it silently converts an expiry into a longer window.
- Add a fence token to every write whose double application would be invisible: an acquisition-ordered token, and a last-accepted-token column in the store the write lands in, not in the cache.
- Bound the connection pool, make it wait rather than raise, and set a socket timeout. Then load test at the concurrency you actually run, because the library’s default is 100 and it raises.
- Measure the three numbers that decide whether the next incident is a cache incident: database calls per expired key, attempts per lock acquisition, and evicted keys per minute.
The order is not arbitrary. Steps one to three decide whether the instance can be trusted with coordination at all; four to six decide whether a cold or expiring key is a query storm; seven to nine decide whether a long critical section is a duplicate write; and the last one is what tells you, months later, which of the earlier steps has drifted.
If this article had to be one sentence, it would be the one the measurements keep producing: a cache is not a store that happens to be fast, it is a coordination mechanism, and every property that makes it useful – shared state, expiring entries, a lease that survives a crash – is a property that fails in a specific, measurable way. The probes in this article exist so that the failure is measured once, in a directory, rather than discovered per incident.
The rest of this series follows the same thread through the parts of a Python service that fail under load: the overall stack and its tooling choices, the asyncio concurrency model that a cache read lives inside, memory retention in long-lived workers, the database that a stampede actually hits, container architecture for these services, pod resources and OOMKilled, task queues that share the same Redis, worker deadlocks under a cache outage, connection pools at the database layer, retry storms in the HTTP client, test isolation for async code, process pools that hang, and schema validation at the edge. Each one was written the same way: a probe, a table, and the runbook that follows from the numbers.
Frequently asked questions
Does a cache need both single-flight fills and early refresh?
They solve different halves. Single flight bounds the work a cold key causes – 8 database calls instead of 321 in the probe – but its waiters pay the fill latency, with a p99 of 31.619 ms against 5.714 ms for early refresh. Early refresh keeps a hot key from ever being cold, and single flight handles the cold case it cannot prevent.
What value should beta have in an XFetch cache?
Start at 1, where the refresh trigger probability is about a third when one compute-time of TTL remains, and raise it only if the store can absorb redundant recomputes. The measured lead time has a mean of 20 ms at that setting for a 20 ms value, with a tail that fires 46 ms early in the ninetieth percentile.
Is a Redis lock safe if the instance fails over?
A lease taken on a primary that is replaced can exist on both sides for a moment, so no client-side protocol makes the lock linearizable. What makes the failure survivable is a fence token checked by the writer of record: in the constructed interleaving a stale write overwrote the newer one in all 20 trials without a token, and the record rejected it in all 20 with one.
How long should a lock lease be?
Long enough that the measured worst-case critical section fits with room to spare, and renewed by a watchdog at a third of the lease. A lease of 300 ms around 1200 ms of work was taken by a competing worker in all 10 trials without a heartbeat and in none of 10 with one.
Why is a plain DEL on release dangerous if the token is never checked?
Because the holder cannot see whose key it is deleting. In the constructed interleaving the release removed another holder’s key in all 30 trials and admitted a third worker 30 times while the second was still inside; the compare-and-delete release admitted it zero times.
Should cache entries and locks share one Redis instance?
Not if the lock is a lease. A lease is taken with SET NX PX, so the lock key has a TTL, and every eviction-enabled policy is therefore allowed to evict it: under allkeys-lru the lease was evicted in 1 of 100 trials, under allkeys-lfu in 2 of 100, and under volatile-lru in none of 100 – which is what a sampler does rather than a guarantee, because the lease carries exactly the TTL that policy evicts by. Meanwhile noeviction on the shared instance refused to take the lease at all in 100 of 100. Put leases and fence keys on their own noeviction instance, sized by the peak number of concurrent locks.
Which eviction policy should a cache use?
allkeys-lru for a cache that holds nothing else. The measured medians were close enough to be unhelpful – 67.39% for allkeys-lru, 62.93% for allkeys-lfu, 71.76% for volatile-lru – while the spread within one policy ran from 51.62% to 72.63%. Choose on correctness: an allkeys policy cannot silently stop evicting, a volatile policy can, and it refused 3,632 writes when the TTL was missing.
Is a connection pool enough, or is pipelining needed too?
Both, for different reasons. The pool bounds sockets and removes connect cost: 201 connections for a client per request against 51 for a bounded pool. Pipelining removes round trips: 7.01 microseconds per key against 96 for one GET per key, and 2.82 with MGET.
Production SRE Note: Every question above has a table behind it in sections 3 to 15, and every number in the answers is generated from the probe output rather than typed. The probes are described here as printed code rather than published as a package, so the way to check a claim on your own hardware is to run that block against a local server; the sections named in each answer are the ones to rebuild first.
