Architecture
The event loop, I/O threads, the RESP protocol, and background work
Postgres forks one process per connection. Redis does the opposite: one main thread serves every client, using an event loop. Almost everything about Redis's performance and its failure modes follows from that.
The event loop
- The OS tells Redis which of its thousands of client sockets have
data (
epollon Linux). No thread per connection, no blocking. - Redis reads and parses the commands that arrived.
- It executes them one by one, each to completion, against the in-memory data.
- It queues the replies into each client's output buffer and writes them back.
- Between iterations it runs timer events (
serverCron,hztimes per second, 10 by default): expiring keys, checking persistence, updating stats.
Because execution is serial, every command is atomic: no other client
can observe a ZINCRBY half-done or interleave with an LPUSH. There
are no locks in the data path at all.
The flip side: a command that takes 2 seconds blocks every client
for 2 seconds. KEYS * on 10 million keys, SMEMBERS on a
million-member set, DEL on a huge hash, or a long Lua script all
freeze the server. Latency problems in Redis are almost always "some
command was O(N) with a big N." That's why every command's docs list
its time complexity.
What runs on other threads
Redis isn't strictly single-threaded; it's single-threaded for command execution. Other work happens elsewhere:
| Work | Where |
|---|---|
| Socket reads/writes and parsing | Optional I/O threads (io-threads N). Helps at very high throughput on many cores. |
Freeing big objects (UNLINK, FLUSHALL ASYNC, lazy eviction/expiry) | Background threads (lazyfree) |
fsync of the AOF, closing files | Background threads (bio) |
| RDB snapshots and AOF rewrites | A forked child process |
io-threads is set to 1 in this repo. Enable it (e.g., 4 on an 8-core
machine) only when profiling shows the main thread is busy with network
I/O rather than commands.
The RESP protocol
Clients and Redis talk RESP (REdis Serialization Protocol), a simple text-prefixed protocol. You can speak it by hand:
# what redis-cli sends for: SET hello world
*3\r\n$3\r\nSET\r\n$5\r\nhello\r\n$5\r\nworld\r\n
# *3 an array of 3 elements
# $3 a bulk string of 3 bytes: SET
# ...
# reply
+OK\r\n# try it raw, with no client library
printf 'AUTH default redis123\r\nPING\r\nINCR counter\r\n' | nc localhost 6379
+OK
+PONG
:1The leading byte gives the type: + simple string, - error, :
integer, $ bulk string, * array. RESP3 (negotiated with
HELLO 3) adds maps, sets, doubles, and push messages used for
client-side caching and Pub/Sub.
The protocol is cheap to parse, so the dominant cost of a simple command is the network round trip: ~50-100 µs on localhost, often 0.5-1 ms across a data centre. That's why pipelining can give a 10x speedup: it sends many commands per round trip.
Memory layout, briefly
Every database is a big hash table mapping key → value object. Each value object records its type (string, list, hash, ...) and its encoding, the concrete in-memory representation. Small values use compact encodings; Redis converts them to general-purpose ones as they grow:
SET n 123 -> OBJECT ENCODING n "int" (stored as an integer)
SET s hello -> "embstr" (short string stored in one allocation with its key)
RPUSH l a b -> "listpack" (compact contiguous list)
SADD s 1 2 -> "intset" (sorted array of integers)
HSET h f v -> "listpack" (until 512 fields or a 64-byte value)This is why a million small hashes can use far less memory than a million separate string keys. Full detail in Encodings & Memory Layout.
Databases (and why not to use them)
A Redis server has 16 numbered databases (SELECT 0 … SELECT 15).
They share everything (memory, the thread, persistence, replication).
Only the keyspace is separate. Redis Cluster supports only database 0.
In practice, use key prefixes (cache:, session:) for separation,
and separate Redis instances for separate workloads.
Lab
- In one terminal:
docker exec -it redis redis-cli --user default --pass redis123 MONITOR. It prints every command the server executes. - In another, run
docker compose -f compose_prod.yaml run --rm labs python leaderboard.py. Watch the stream ofZINCRBYcommands. (Never leaveMONITORrunning in production; it costs a lot of throughput.) - Run
redis-benchmarkfrom inside the container:
docker exec redis redis-benchmark --user default -a redis123 -t set,get -n 100000 -q
docker exec redis redis-benchmark --user default -a redis123 -t set,get -n 100000 -q -P 16 # pipelinedCompare the two. The pipelined run should be several times faster. Same server, same commands, fewer round trips.