Synthesis and Self-Test

Synthesis

Single Thread ↔ Persistence: the fork pause is another blocked-thread event

The Single-Threaded Execution part: one thread executes everything — latency is bounded only if every command is fast. The Persistence: RDB and AOF part: persistence forks, and fork() blocks that same thread while the kernel copies page tables.

Your p99 is determined by both your slowest command and your fork pause — and the fork pause scales with dataset size. A 50 GB instance with heavy writes can freeze the executor for 100 ms+ at every BGSAVE, during which no command runs — indistinguishable to a client or Sentinel from a slow KEYS *. The mitigation is identical in both sections: keep instances small (shard via Cluster), disable THP, keep slow commands off the executor.

Atomicity ↔ Cluster: Cluster quietly revokes single-node atomicity

The Single-Threaded Execution part: every command / MULTI/EXEC / Lua script is atomic and isolated — a single-keyspace property. Cluster shatters it two ways:

Spatially — atomicity only holds for keys in the same slot, hence CROSSSLOT and hash tags. Temporally — async replication means an acknowledged OK can evaporate in a failover.

The mental model "Redis is atomic and my write is safe once I get OK" is true on one node and false in a cluster. This is also exactly why the Lua-based rate limiters in the rate-limiting chapter tolerate a brief over-limit window during failover instead of pretending to be exact.

Memory → Persistence: RDB and AOF → Single-Threaded Execution → High Availability and Streams: memory layout is the hidden driver of every other failure

Memory and the Allocator's ~90-byte-per-key overhead isn't a memory footnote — it sets the dataset size, which drives everything downstream:

encoding choices
   → dataset size
      → fork/COW cost
         → executor latency
            → (in Cluster) failover frequency
               → write-loss exposure

Choosing hashes over thousands of top-level keys can shrink a dataset 10×, shrinking the page table, fork time, COW spike, and RDB/AOF-rewrite cost all at once. Fragmentation (mem_fragmentation_ratio > 1.3) eats the headroom the COW spike needs — so a fragmentation problem surfaces as OOM-during-BGSAVE.

Replication + Redis Cluster + High Availability and Streams: consensus ≠ durability

Both Sentinel and Cluster automate failover. Neither makes it lossless. They solve two separate problems:

ProblemSolved by
"Who decides the master is dead, and who promotes?"Sentinel quorum/leader-election; Cluster epoch-voting
"What about the writes the dead master acked but never shipped?"Not solved. This is the async replication window.

You can have flawless, fast failover and still lose acknowledged writes. Consensus is about topology, not bytes in the replication backlog.

Internals → rate limiting: every rate-limiter design decision is an internals decision

The rate limiters in the rate-limiting chapter are not a separate topic — they are the internals chapter applied. Lua atomicity works because of the single-threaded executor (#1), which is also why a long script freezes the whole server. EXPIRE-based cleanup works because of active expiry in serverCron (#1). Hash tags are mandatory for a multi-key limiter because of the 16,384-slot model (#5). And the reason "allowing 105 requests instead of 100 during a failover blip" is the right engineering answer is precisely the async-replication window of #4.

Self-Test

Question 1

Redis 6 introduced io-threads. A colleague says "great, now Redis runs my commands in parallel, so a slow SUNION won't block other clients." Correct them precisely: what runs on the I/O threads, what still runs on one thread, and is the colleague right or wrong about the SUNION?

Show answer

The colleague is wrong about the SUNION. io-threads parallelizes only socket I/O: reading raw bytes off client sockets, parsing RESP into command objects, and encoding/writing reply buffers back out. Command execution — the actual SUNION, the keyspace mutation — still runs on the single main thread, serially. A slow SUNION blocks the executor for its entire O(N) duration regardless of io-threads. Every other client waits. io-threads helps high-connection-count / large-payload workloads, not workloads bottlenecked on slow commands.

Question 2

You run SET session:abc "x" where "x" is a 5-byte string. Roughly how much RAM does this consume, and name the four-or-five distinct allocations? Then explain why SET counter 100 costs almost nothing by comparison.

Show answer

~88 bytes. The allocations: (1) dictEntry — 24 bytes raw, rounded to 32, plus ~8 bytes amortized bucket share; (2) key SDS — header + chars + null, rounded up; (3) value redisObject — 16 bytes; (4) value SDS — 3 header + 5 data + 1 null = 9 bytes, rounded to 16.

SET counter 100 is cheap because 100 uses int encoding — stored directly in robj's pointer field with no separate SDS allocation. Furthermore, integers 0–9999 are shared cached objects pre-allocated at startup, so no new redisObject is allocated at all. The key SDS still costs ~16–24 bytes, but the value overhead vanishes entirely.

Question 3

During BGSAVE on a write-heavy 30 GB instance, RSS climbs toward 55 GB and Redis is OOM-killed. Explain the mechanism (two layers: COW behavior and THP), and give two specific OS/config mitigations.

Show answer

Layer 1 — COW: fork() shares pages read-only with the child. Every page the parent writes during the save faults and is copied (4 KB per write) so the child keeps a consistent snapshot. Under write-heavy load many pages get dirtied → parent RSS grows toward 2× dataset.

Layer 2 — THP: with 2 MB huge pages, a single small write forces a 2 MB COW copy instead of 4 KB (512× worse), massively amplifying the spike.

Mitigations: (a) echo never > /sys/kernel/mm/transparent_hugepage/enabled; (b) sysctl vm.overcommit_memory=1 and provision RAM for ~2× dataset — or shard via Cluster to keep instances small. Check with INFO stats → latest_fork_usec.

Question 4

Explain why AOF rewrite uses fork() and a separate rewrite buffer instead of editing the live AOF in place. What does the rewrite buffer guarantee, and what changed in Redis 7.0?

Show answer

The current dataset in memory is the source of truth — regenerating a minimal AOF from it is far simpler than computing which historical commands are now redundant. Redis forks to get a consistent COW snapshot the child can serialize to a temp file; an atomic rename swaps it in on success, leaving the old valid AOF intact if the rewrite fails.

The AOF rewrite buffer captures every write that arrives while the child is rewriting. When the child finishes, the parent appends the buffer before swapping — guaranteeing no write during the rewrite is lost and none is double-counted. Without it, any write that arrived after fork() but before the rename would be missing.

Redis 7.0 replaced this with multi-part AOF: base (compacted snapshot) + incr (writes since the rewrite) + manifest. New writes go directly to the incr file — no in-memory buffer pipe needed.

Question 5

A client does SET balance:user1 500 against Redis Cluster and gets OK. Thirty seconds later, after a failover, a read returns the old balance. (a) How was an acknowledged write lost? (b) Why doesn't single-node Redis have this problem? (c) What two mitigations narrow the window, and why don't they eliminate it?

Show answer

(a) The master replied OK before its replica acknowledged the write — replication is asynchronous. The master crashed/partitioned before streaming that write. Cluster promoted the replica (which never saw it) via epoch voting; when the old master rejoined it saw the new master's higher configEpoch and discarded its own version to sync.

(b) Single-node Redis has one keyspace and no async hop between ack and durability — once OK returns, the write is applied and visible everywhere, with no replica lag or failover path that could surface a divergent view.

(c) WAIT 1 100 blocks until ≥1 replica ACKs (narrows the window); min-replicas-to-write / min-replicas-max-lag refuse writes when not enough caught-up replicas exist (trades availability for safety). Neither eliminates loss: WAIT doesn't roll back on timeout, and a failover can still lose a write acked only by a replica that then itself goes down.

Question 6

A colleague ships a rate limiter as a Redis pipeline: ZREMRANGEBYSCORE → ZCARD → decide in Go → ZADD. Under load the limit leaks by a few percent, and blocked clients stay locked out far longer than the window. Diagnose both symptoms and give one fix that solves them together.

Show answer

Symptom 1 — the leak is a read-modify-write race. A pipeline is not atomic: two goroutines can both run ZCARD, both see 99, both decide "allow," and both ZADD → 101 entries against a limit of 100. Nothing in the pipeline serializes the decision.

Symptom 2 — the unconditional ZADD. Because the decision happens in Go after Exec(), the pipeline adds the timestamp even for requests it then rejects. A client retrying 100×/sec keeps refilling its own window, so the set never drains below the limit and the client locks itself out far past the nominal 60 s.

One fix for both: move trim → count → conditional add into a single Lua script. It runs as one uninterruptible step on the single-threaded executor (no race), and because the read result is available in a variable server-side, the ZADD happens only when the request is under the limit. Caveats: keep it under ~100 µs since it blocks the whole server, and on Cluster the keys must share a hash slot ({user_id}).

Question 7

"We wrapped the debit and the credit in MULTI/EXEC, so a failover can't half-commit us." Is that right? Explain what MULTI/EXEC does and does not guarantee, the two realistic ways the books still end up wrong, and why WAIT isn't the fix.

Show answer

Half right, and dangerously so. MULTI/EXEC gives execution atomicity on the primary, in memory: no other client's command interleaves, and the block runs as one unit. It gives zero durability guarantee across a failover, because replication is asynchronous and happens after the client already received OK. (It also isn't rollback-on-error — if a queued command fails at runtime, the rest still execute.)

Two realistic bad outcomes: (1) if debit and credit are separate writes, the replica can have the debit and never receive the credit — money vanishes; (2) even if the whole transaction is lost as a unit, the real world already acted on the OK — the user saw "Transfer complete," a downstream API was called, an email went out. Reality and the ledger disagree either way.

Why WAIT isn't the fix: it's best-effort and after-the-fact — EXEC already committed and replied before you call it; on timeout you learn the write might be unsafe but can't un-commit it; and a replica ack means "received," not "fsync'd." The real answer for money is Postgres + synchronous replication, where COMMIT doesn't return until the WAL record is flushed on both primary and replica disk — atomicity and durability bound into the same acknowledgment.