Skip to content

Why Redis is fast, and what you give up

Working knowledgeUnder the hood

Redis often answers in well under a millisecond, yet it runs every command on a single thread. The speed comes from three choices: data in memory, one thread, and simple structures. Each one has a price.

01 Where the time goes

A call to Redis has two parts: the trip over the network and the work inside the server. For a GET, the work is one hash table lookup in memory, which typically takes around a microsecond. Most of what your app waits for is the trip.

Read from RAM~100 nsWhat Redis does for each lookup. Nothing waits on a disk.
Random read from an SSD~10–100 µsHundreds of times slower. A disk-based database pays this whenever the data is not already in its cache.
Round trip in a data centre~0.5 msUsually the largest part of a Redis call, which is why sending commands in batches pays off.

These are rough, commonly cited figures; your hardware will differ. The order of magnitude is what matters: memory is fast, disks are slower, and the network is slower again. Redis is built on three choices that keep the server’s part tiny.

02 Choice 1: everything lives in memory

Redis keeps the whole dataset in RAM. A lookup never waits for a disk, and the structures are plain pointers and arrays in memory, not pages that must be loaded and decoded first.

The price is that your data has to fit in memory, and memory costs more per gigabyte than disk. When a maxmemory limit is set and reached, Redis either refuses writes (the default policy, noeviction) or evicts keys by the policy you choose:

Text
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lru

Memory is also wiped by a restart. Getting data back needs persistence, snapshots or an append-only file, and that is the next tutorial in this topic.

03 Choice 2: one thread runs every command

Redis runs commands on one main thread, in an event loop. The kernel reports which client sockets have data waiting (epoll on Linux, kqueue on macOS). Redis reads a command, runs it to the end, queues the reply and moves to the next one. Below, three clients race to change the same key.

The event loop runs one command at a time
Step 1 of 7
Sockets with a command waiting
Empty
Data in memory
hits→0
Replies sent
Empty
  • just arrived or written
  • read by a command

Three clients, A, B and C, are connected. hits is 0 and nobody has sent anything, so the loop is waiting in epoll_wait.

idle running now

This is why INCR is safe from many clients: B can’t slip in between A’s read and A’s write. It is also why one thread can serve thousands of clients. Each command is tiny, so the queue drains fast, and the thread never spends time on locks or switching between threads.

“Single-threaded” is about commands. Since Redis 6, io-threads can spread the reading and writing of sockets over several threads, and background threads already free memory after UNLINK and flush the append-only file. The commands themselves still run one at a time on the main thread.

04 The price: one slow command stalls everyone

The queue in the trace only drains fast if every command is fast. A command that takes four seconds holds the thread for four seconds, and every other client waits, even for a PING. You can see it with a Lua script that just counts:

Shell
# terminal 1: a script that loops for a few seconds
redis-cli EVAL "local i=0 while i<1000000000 do i=i+1 end return i" 0
# terminal 2, while it runs
time redis-cli PING

On one laptop run (Redis 8.4), the PING came back after about 3.5 seconds instead of a fraction of a millisecond. Redis records the culprit in its slow log, with the time in microseconds (here about 4 seconds):

Text
> SLOWLOG GET 1
1) 1) (integer) 1
2) (integer) 1793583240
3) (integer) 4069402
4) 1) "EVAL"
...

Once a script runs past busy-reply-threshold (5 seconds by default), Redis starts answering other clients with a BUSY error. That tells them something is wrong, but it still can’t run their commands until the script ends or is stopped with SCRIPT KILL.

05 Choice 3: simple structures with known costs

Each Redis command documents its time complexity, and the structures behind them are few and simple: hash tables, skip lists and packed arrays. You can tell what a command will cost before you run it, which matters a lot when one thread serves everyone.

What common commands cost
CommandCostWhy
GET keyO(1)one hash table lookup
HGET key fieldO(1)a second hash table inside the key
LPUSH / RPOPO(1)work only at the ends of the list
LINDEX key iO(N)walks the list to position i
ZADD key score mO(log N)insert into a skip list
ZRANGE key 0 9O(log N + 10)find the start, then walk 10
HGETALL / SMEMBERSO(N)returns every member
KEYS patternO(N)checks every key in the database

Small collections are stored even more simply. A hash, list, set or sorted set with few, short elements is one packed block of memory called a listpack (it replaced the older ziplist in Redis 7). Scanning a few dozen entries in one block is fast and saves the pointers a full hash table needs. Redis converts it to the full structure once it grows past limits such as hash-max-listpack-entries, 128 by default. OBJECT ENCODING shows which form a key is in:

Text
> HSET user:42 name Ana plan pro
(integer) 2
> OBJECT ENCODING user:42
"listpack"
> SET page:views 11
OK
> OBJECT ENCODING page:views
"int"

06 Measure it yourself

redis-benchmark ships with Redis. Run it twice against a local server: once sending one command per round trip, and once with -P 16, which pipelines 16 commands into each round trip.

One at a time
$ redis-benchmark -t get -n 100000 -q
GET: 165562.92 requests per second, p50=0.255 msec
Pipelined
$ redis-benchmark -t get -n 100000 -q -P 16
GET: 1587301.50 requests per second, p50=0.447 msec

Those numbers come from one laptop over loopback, so read them as a shape, not a promise. The work per GET didn’t change; the waiting did. With pipelining, Redis gets 16 commands in one socket read, runs them back to back and sends 16 replies in one write. Your app gets the same win from its client’s pipeline feature, or from MGET and MSET, which handle many keys in one command.

redis-cli --latency pings the server in a loop and prints the minimum, maximum and average round trip in milliseconds, which is a quick way to see how much of your time is network.

07 What you give up

maxmemory 2gbData must fit in RAMPast maxmemory, writes fail or keys are evicted. If the data can’t fit in memory at a price you accept, Redis is the wrong store for it.
KEYS *Long commands block everyoneUse SCAN instead of KEYS, UNLINK instead of DEL for big keys, and keep scripts short. Watch SLOWLOG for anything that slips through.
one core busyOne core per instance for commandsA single instance can’t use more cores for commands. To grow, shard keys across instances, for example with Redis Cluster, and accept that multi-key commands only work within one shard.
appendfsync everysecRecent writes can be lostWith the common append-only setting, a crash can lose about the last second of writes. appendfsync always closes that gap at the cost of a disk sync per write.
BGSAVESnapshots need spare memorySaving forks the process. Pages that change during the save are copied, so a busy instance can need noticeably more memory while it saves.

Never run KEYS on a production instance with many keys. It is O(N) on the one thread, so the whole service stops answering until it finishes. SCAN 0 MATCH user:* COUNT 100 does the same job in small batches, letting other clients in between.

08 Check yourself

Question

Two clients run INCR on the same key at the same instant. Why is the result always right?

Question

Each page in your app runs 200 GETs one after another and is slow, but Redis CPU use is low. What helps most?

Question

Someone runs a Lua script that loops for 10 seconds. What do other clients see?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?