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.

MythReality
More threads = more throughputOnly for CPU-bound work. Redis's bottleneck is network I/O + memory bandwidth.
Single thread wastes coresExtra cores have nothing useful to do here — adding threads only adds lock overhead.
Concurrent access needs locksWith 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.

Event loop — the single thread's infinite cycle
Event loop — the single thread's infinite cycle

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.

epoll_wait — O(ready events), not O(sockets)
epoll_wait — O(ready events), not O(sockets)
OSMultiplexing syscall (aeApiPoll picks per OS)
Linuxepoll_wait
macOS / BSDkqueue
Solarisevport
Fallbackselect / 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 3

Low 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_wait returns 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 this

Time 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 tickWhy
Active key expirySamples keys with TTLs, deletes expired ones
Ping replicasMaster sends PING; replicas treat silence as master failure
Client timeout checkDisconnects idle clients past the timeout threshold
Memory stats updateused_memory, mem_fragmentation_ratio, …
Incremental dict rehashBackground resize of the keyspace hash table (see Memory and the Allocator)
Cluster gossipSends heartbeats to peer nodes
AOF rewrite triggerChecks 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:

FieldWhat it tracks
fdThe socket file descriptor
nameCLIENT SETNAME value
querybufThe raw bytes received (the input buffer)
reply listQueued replies waiting to be written
argv / argcParsed command arguments
dbCurrently selected database
ctimeConnection time (for timeout checks)

When freeClient() runs during the serverCron timeout check, it tears down all five layers in order:

  1. Unlink from server.clients — the list node is removed
  2. Remove from server.clients_index — the radix tree entry is deleted
  3. aeDeleteFileEvent — removed from the epoll set, kernel stops watching this fd
  4. close(fd) — TCP FIN sent, kernel socket buffers released
  5. zfree(c) — the client struct 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:

WhatAllocated byReleased bySize class
Kernel socket buffers + TCP stateLinux kernel (on accept())close(fd)Variable (kernel managed)
client struct + buffersjemalloc (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.

SubsystemImpact during the blocked window
Active expiryExpired keys accumulate unreclaimed; lazy expiry on access still works
Sentinel health checksMaster is stuck and can't reply → Sentinel sees it as unresponsive within down-after-milliseconds → SDOWN
Replication heartbeatsPING to replicas delayed; past repl-timeout (default 60 s) replicas disconnect and force a full resync
Client timeoutIdle clients that should've been disconnected stay alive
Memory statsused_memory and fragmentation metrics go stale
Cluster gossipPeer 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 CommandWhySafe Alternative
KEYS *Scans the entire keyspace. 50M keys = multi-second blockSCAN (cursor-based, yields between iterations)
SMEMBERS/SUNION/SINTER on huge setsMaterializes the whole result in one shotSSCAN
HGETALL / LRANGE 0 -1 on giant collectionsO(N) serialization into the reply bufferHSCAN / bounded ranges
DEL of a 10M-element setFreeing all allocations is O(N) and synchronousUNLINK (frees on a background thread)
FLUSHALL / FLUSHDBFrees everything inlineFLUSHALL ASYNC
Unbounded Lua loopRuns to completion, blocks allSCAN-style iterative scripts

Diagnose offenders

slowlog-log-slower-than 10000   # flag commands > 10ms
SLOWLOG GET
LATENCY HISTORY / LATENCY LATEST

Atomicity: 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.

ConstructAtomic?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:

Diagram
io-threads 4
io-threads-do-reads yes

Helps: 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.