Single-Threaded Execution
Why Single-Threaded?
The instinct is "more threads = more speed." That's only true for CPU-bound work. Redis operations touch a handful of memory locations — the bottleneck is network I/O and memory bandwidth, not compute.
| Myth | Reality |
|---|---|
| More threads = more throughput | Only for CPU-bound work. Redis's bottleneck is network I/O + memory bandwidth. |
| Single thread wastes cores | Extra cores have nothing useful to do here — adding threads only adds lock overhead. |
| Concurrent access needs locks | With one thread there's nothing to lock. Every mutation is trivially safe. |
The Event Loop — One Full Iteration
Instead of one thread per client (10,000 clients = 10,000 mostly-blocked threads), Redis uses one thread + I/O multiplexing: register all sockets with the OS, park, wake only when something needs attention. In plain English: execute commands → run housekeeping → flush everything in batch → sleep → repeat.
How epoll_wait Works
The naive approach polls every socket on every tick — O(total sockets), wasting time on 9,999 idle ones. epoll_wait inverts this: Redis registers all sockets with the kernel once, parks, and the kernel wakes it only when data arrives — handing back only the ready fds. That's O(ready events), so it scales to 100k+ connections without penalty.
| OS | Multiplexing syscall (aeApiPoll picks per OS) |
|---|---|
| Linux | epoll_wait |
| macOS / BSD | kqueue |
| Solaris | evport |
| Fallback | select / poll |
Why epoll_wait returns multiple events at once
epoll_wait returns immediately when at least one fd is ready — there's no deliberate batching. Yet it routinely returns 3, 50, or 100 events. The reason: while Redis was processing the previous batch, the kernel kept accumulating newly-ready fds in the background.
Redis busy processing batch N kernel: fd3 becomes ready
kernel: fd7 becomes ready
kernel: fd22 becomes ready
epoll_wait() called ───────────► returns immediately with all 3Low load: typically 1 event per call. High load: many — fewer syscalls per event processed. Redis passes maxevents = 10000, so it can drain up to 10k ready fds per call.
When Redis actually blocks
Only when there is nothing to do. The timeout passed to epoll_wait is derived from the nearest scheduled timer (expiry scan, replication heartbeat…):
processFileEvents() // handle ready sockets
processTimeEvents() // run any due timers
beforeSleep() // flush AOF, sync replicas
epoll_wait(timeout=next_timer) // ← ONLY blocking point- Busy server —
epoll_waitreturns immediately every iteration; Redis never really sleeps. - Idle server — next timer in 100 ms; Redis parks for 100 ms, runs the timer, parks again.
- Completely idle — blocks indefinitely until a client connects.
"Blocking" here means the CPU is parked cheaply in the kernel — zero CPU burn. The instant any fd is ready or the timeout fires, Redis is running again.
beforeSleep — why flush here, not after each command?
beforeSleep literally means "run this right before we go to sleep." It's where Redis batches all the I/O accumulated during the tick.
✗ If Redis flushed per command — 100 syscalls
SET a → write()
SET b → write()
SET c → write()
...✓ Deferred to beforeSleep — 1 syscall
SET a → aof_buf
SET b → aof_buf
SET c → aof_buf
...
beforeSleep → write(aof_buf)Same data reaches the kernel — 100× fewer syscalls. Replica sync is identical: everything from the tick ships in one burst instead of per-command. This batching is a key reason Redis sustains 100k+ ops/sec.
Tracing one SET from arrival to disk
Iteration N:
processFileEvents:
parse "SET balance 500"
execute → update in-memory hashmap ← data is live NOW
append to aof_buf ← in-memory buffer only
queue "+OK" → client receives OK
beforeSleep → write(aof_buf) → kernel page cache
your SET is in the kernel, NOT yet on physical disk
Background thread (~every second, appendfsync=everysec):
fsync() → page cache → physical disk
your SET survives a power failure only after thisTime Events and serverCron
processTimeEvents() fires when a scheduled timer is due. The most important one is serverCron, scheduled every 1000/hz ms — default hz=10 → every 100 ms.
| Task each tick | Why |
|---|---|
| Active key expiry | Samples keys with TTLs, deletes expired ones |
| Ping replicas | Master sends PING; replicas treat silence as master failure |
| Client timeout check | Disconnects idle clients past the timeout threshold |
| Memory stats update | used_memory, mem_fragmentation_ratio, … |
| Incremental dict rehash | Background resize of the keyspace hash table (see Memory and the Allocator) |
| Cluster gossip | Sends heartbeats to peer nodes |
| AOF rewrite trigger | Checks size thresholds; starts BGREWRITEAOF if needed |
Where the client struct lives
Every connected client is a client struct (~200+ bytes) held in a doubly-linked list inside the global redisServer struct:
struct redisServer {
list *clients; // linked list of ALL connected clients
rax *clients_index; // radix tree for O(1) lookup by client ID
int numclients; // current count
...
};Each client struct tracks:
| Field | What it tracks |
|---|---|
fd | The socket file descriptor |
name | CLIENT SETNAME value |
querybuf | The raw bytes received (the input buffer) |
reply list | Queued replies waiting to be written |
argv / argc | Parsed command arguments |
db | Currently selected database |
ctime | Connection time (for timeout checks) |
When freeClient() runs during the serverCron timeout check, it tears down all five layers in order:
- Unlink from
server.clients— the list node is removed - Remove from
server.clients_index— the radix tree entry is deleted aeDeleteFileEvent— removed from the epoll set, kernel stops watching this fdclose(fd)— TCP FIN sent, kernel socket buffers releasedzfree(c)— theclientstruct memory returned to jemalloc
The key: each active connection is a heap allocation pinned in a globally-scoped linked list that serverCron walks every 100ms. No garbage collector, no reference counting — just explicit alloc and free on the same struct lifetime.
Memory layout: where the bytes actually go
The client struct doesn't sit directly inside the linked list — the list holds nodes that point to it:
server.clients (linked list)
│
├── listNode A (2 ptrs: prev=16B, next=16B)
│ └── *val ──→ client struct (heap, ~200B, jemalloc 256B size class)
│
├── listNode B
│ └── *val ──→ client struct (heap, ~200B)
│
└── listNode C
└── *val ──→ client struct (heap, ~200B)So each connection costs: 32 bytes (list node + pointer) + ~200 bytes (the client struct itself, rounded to 256 by jemalloc) + the querybuf and reply buffers (which can be much larger for slow consumers). On a server with 10,000 idle connections, that's roughly ~3 MB just for the structs and list — plus whatever is sitting in their buffers.
The radix tree (server.clients_index) adds a second path to the same struct for CLIENT ID / CLIENT KILL ID lookups — it stores another pointer to the same client allocation, not a copy.
Two allocators, two lifetimes
When freeClient() runs, it touches two completely separate allocators:
| What | Allocated by | Released by | Size class |
|---|---|---|---|
| Kernel socket buffers + TCP state | Linux kernel (on accept()) | close(fd) | Variable (kernel managed) |
client struct + buffers | jemalloc (on createClient()) | zfree() | ~256B (jemalloc slab) |
These are independent allocators with no shared bookkeeping. The kernel doesn't know jemalloc freed a struct; jemalloc doesn't know the kernel closed a socket. Redis has to call both — skipping close() leaks the kernel resources, skipping zfree() leaks the userspace memory. The full five-step teardown above is the only way to clean up both sides.
What happens when ticks are missed
serverCron runs inside the event loop — it can only fire between command executions. A slow command holds the executor for its entire duration; the loop never returns to processTimeEvents. If KEYS * takes 2 seconds on 10M keys, 20 consecutive ticks are skipped.
| Subsystem | Impact during the blocked window |
|---|---|
| Active expiry | Expired keys accumulate unreclaimed; lazy expiry on access still works |
| Sentinel health checks | Master is stuck and can't reply → Sentinel sees it as unresponsive within down-after-milliseconds → SDOWN |
| Replication heartbeats | PING to replicas delayed; past repl-timeout (default 60 s) replicas disconnect and force a full resync |
| Client timeout | Idle clients that should've been disconnected stay alive |
| Memory stats | used_memory and fragmentation metrics go stale |
| Cluster gossip | Peer nodes see silence, may escalate PFAIL → FAIL |
Recovery does not catch up. When the slow command returns, processTimeEvents sees serverCron is overdue and runs it once. The next tick is scheduled from now + 100ms. Missed cycles are permanently lost.
The Dark Side: One Slow Command = Full Stop
There is no preemption. If a command takes 5 seconds, every client — readers, writers, health checks — waits 5 seconds.
| Dangerous Command | Why | Safe Alternative |
|---|---|---|
KEYS * | Scans the entire keyspace. 50M keys = multi-second block | SCAN (cursor-based, yields between iterations) |
SMEMBERS/SUNION/SINTER on huge sets | Materializes the whole result in one shot | SSCAN |
HGETALL / LRANGE 0 -1 on giant collections | O(N) serialization into the reply buffer | HSCAN / bounded ranges |
DEL of a 10M-element set | Freeing all allocations is O(N) and synchronous | UNLINK (frees on a background thread) |
FLUSHALL / FLUSHDB | Frees everything inline | FLUSHALL ASYNC |
| Unbounded Lua loop | Runs to completion, blocks all | SCAN-style iterative scripts |
Diagnose offenders
slowlog-log-slower-than 10000 # flag commands > 10ms
SLOWLOG GET
LATENCY HISTORY / LATENCY LATESTAtomicity: Built In, Not Bolted On
Atomicity in Redis is not implemented — it is a consequence of the model. Because one command runs to completion before the next, there is no interleaving to guard against.
| Construct | Atomic? | Note |
|---|---|---|
Any single command (INCR, LPUSH…) | ✓ always | — |
MULTI/EXEC block | ✓ | Whole batch runs uninterrupted |
Lua script (EVAL) | ✓ | Entire script = one event-loop tick |
Redis 7 Functions (FCALL) | ✓ | Same guarantee |
What Redis 6/7 Actually Made Multi-Threaded
Command execution is still single-threaded — non-negotiable, it's what makes lock-free atomicity possible. What Redis 6 parallelized is only socket I/O:
io-threads 4
io-threads-do-reads yesHelps: high connection count, large request/response payloads. Does nothing for: slow commands, hot-key contention.
Separately, background threads (bio.c) have always handled closing file descriptors, fsync of the AOF, and lazy-freeing large objects (UNLINK). These predate io-threads and never touch the keyspace either.