One thread, one command at a time — the Redis event loop and slow-command stalls
Redis runs every command on a single event-loop thread, so atomicity is free but one slow command stalls every client.
You've named the parts. Here's the first thing that defines how Redis behaves — there is exactly ONE event loop between every client and every byte of data.
Scene 02
One thread, one command at a time
- Watch
- Try it
- Predict
- Capture
Three clients dispatch GETs and SETs into the loop. One thread pulls one command at a time, runs it to completion, then takes the next. With fast commands, every client gets sub-millisecond latency.
Highlighted lines are the ones running in the diagram right now.
while server.running:ready = epoll_wait(fds)for fd in ready:readQueryFromClient(fd) # parses RESPcmd = nextReadyCommand()if cmd is not None:reply = execute(cmd) # touches the datasetaddReplyToClient(cmd.client, reply)# nothing else runs until execute() returnsflushPendingWrites()
def keysCommand(pattern):matches = []for key in server.db.dict: # every key, every timeif stringmatch(pattern, key):matches.append(key)# loop is held the entire time;# no other client is served until we returnreturn matches# contrast: SCAN returns a cursor after ~COUNT keys# so the loop is free between batches
Where this sits in Build Redis
Scene 02 of 10, in the The loop act — One thread, one command — and the encoding under it.. Why a single event loop is fast — and why one slow command (KEYS *, big LRANGE, slow Lua) stalls every client.
Up next. Encodings — if one loop runs every command, the SHAPE of the value it's touching matters. Some shapes are cheap; some quietly aren't.
Designs that use this
- URL ShortenerShorten a long URL. Read-heavy. Don't collide.
- Distributed Rate LimiterEnforce a per-key request limit across a fleet of enforcers — accurately, in under a millisecond, without becoming the outage.
- Twitter / X TimelinePush or pull? Both. The canonical fanout problem.
- Uber / Lyft — Match Drivers and RidersMatch a rider to the closest acceptable driver in under 3 s. Geohash, S2, surge.