Learn Labs
Foundations

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

epoll / kqueuewhich sockets are ready?read & parseRESP per clientexecuteone command at a timewrite repliesoutput buffersserverCronhz=10: expiry, stats
  1. The OS tells Redis which of its thousands of client sockets have data (epoll on Linux). No thread per connection, no blocking.
  2. Redis reads and parses the commands that arrived.
  3. It executes them one by one, each to completion, against the in-memory data.
  4. It queues the replies into each client's output buffer and writes them back.
  5. Between iterations it runs timer events (serverCron, hz times 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.

What runs on other threads

Redis isn't strictly single-threaded; it's single-threaded for command execution. Other work happens elsewhere:

WorkWhere
Socket reads/writes and parsingOptional 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 filesBackground threads (bio)
RDB snapshots and AOF rewritesA 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
:1

The 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

  1. In one terminal: docker exec -it redis redis-cli --user default --pass redis123 MONITOR. It prints every command the server executes.
  2. In another, run docker compose -f compose_prod.yaml run --rm labs python leaderboard.py. Watch the stream of ZINCRBY commands. (Never leave MONITOR running in production; it costs a lot of throughput.)
  3. Run redis-benchmark from 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   # pipelined

Compare the two. The pipelined run should be several times faster. Same server, same commands, fewer round trips.

On this page