Redis in depth
Redis runs your commands one at a time on one thread. Learn what that buys you, what it costs, and what Redis can lose.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 20 March 2023, OpenAI took ChatGPT offline. Some users could see titles from another active user's chat history. 1
Later it found something worse. In the hours before the shutdown, some users could see another active Plus user's name, email address, payment address and the last four digits of their card. OpenAI says this may have affected 1.2% of Plus subscribers active in a nine-hour window. 1
ChatGPT cached user data in Redis Cluster. Its Python servers used the asyncio version of the redis-py client, with a shared pool of connections. 1
If a request was cancelled after it was sent, but before its reply was read, the connection kept that reply. The next, unrelated request on the connection read it instead. Usually this caused an error. Sometimes the data looked valid, so one user got another user's cached data. 1 The bug report shows the same thing: after a cancelled GET foo, the next GET bar returned foo's value. 2
At 1 a.m. Pacific time that day, a server change caused a spike in cancelled Redis requests. One fix OpenAI added: check that data from the cache belongs to the user who asked. 1
The bug was in the client library, not in the Redis server. 1 To use Redis well, you need to know exactly what it promises, and what it doesn't.
It happens for real
OpenAI · 20 Mar 2023ChatGPT: a Redis client bug showed some users other users' dataSome ChatGPT users saw chat titles from other active users, so ChatGPT was taken offline. Later checks found some Plus users' payment details (no full card numbers) may also have been visible to others. All incidents tagged “cache”The idea in simple words
Redis keeps your data in memory and runs one command at a time. That one rule explains most of its strengths and its traps.
- Fast and simple. Each command runs alone, so a single command is always atomic.
INCRnever loses an update. 6 - Fragile under slow commands. If one command takes two seconds, every client waits two seconds.
- Memory first, disk second. Data reaches disk later, by your choice of settings. A crash can lose recent writes.
- Copies are late. Replicas get writes after the primary replies. A failover can lose writes that clients saw succeed.
The key idea. Redis is safe for one command and fast for small ones. Ask of every use: how long does each command take, and what happens to my data if this node dies right now?
How it works
One thread runs every command
The docs call Redis "mostly single threaded". One main thread serves all requests, one after another, using an event loop. 3 Normal commands like GET, SET and LPUSH take a tiny, constant time. Commands that touch many elements do not. 3
Step through what one slow command does to everyone else.
- I/O threads (if you turn them on) read and parse requests. But one main thread runs every command, one after another. A GET takes microseconds, so the queue moves fast.
- Someone runs KEYS * on a database with 10 million keys. The main thread must walk every key before it can do anything else.
- Clients A, B and C sent tiny GETs. Their requests wait in line, even if I/O threads have already read them. Their timeouts fire, and many clients retry, which adds more load.
- The fix: SCAN walks the keys a small batch per call. Other commands run between the batches, so nobody waits long.
The usual suspects:
KEYS. The docs call it "a VERY common source of latency" in production. UseSCAN, which walks the keys in small steps. 3- Deleting a huge key.
DELfrees memory on the main thread. For a value with millions of elements, it "can block for a long time (even seconds)".UNLINKfrees it in the background instead. 5 - Long scripts. A Lua script blocks every other client while it runs. 7 More on that below.
- Forking for persistence. Saving a snapshot needs a
fork(). On a big dataset, Redis may stop serving clients for milliseconds, or even a second. 12
Find them with the slow log (SLOWLOG GET). 3
What about I/O threads? Since Redis 6.0, I/O threads can read requests, parse them and write replies. The main thread still runs every command. Redis kept this rule on purpose, to avoid races. 4 They are off by default. The config file suggests them only on machines with 4 or more cores, and only if you have a real performance problem. 5 I/O threads help with many busy connections. They do nothing for one slow command.
Atomic groups: MULTI/EXEC, WATCH and scripts
MULTI/EXEC queues commands and runs them together. No other client's command runs in the middle. 6 But there is no rollback. If one command fails at run time, the others still run. 6
In Redis, atomic means nothing else runs in the middle. It does not mean that failed work is undone.
WATCH adds a check-and-set. If a watched key changes before EXEC, the whole transaction aborts and EXEC returns null. You retry. 6 This is the optimistic locking from the concurrency control lesson, in Redis form.
Lua scripts can read, decide and write in one atomic step. The docs say a script is usually "both simpler and faster" than a transaction. 6 Here a script takes stock only if enough is left:
-- KEYS[1] = stock key, ARGV[1] = amount
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left < tonumber(ARGV[1]) then return -1 end
return redis.call('DECRBY', KEYS[1], ARGV[1])Pass every key name in KEYS. Never build key names inside the script. Redis needs this to run scripts correctly, and Redis Cluster needs it most. 8 Since Redis 7.0, functions let you load scripts into the server as named, first-class code. 7
The price of atomic is blocking. A script past the busy limit (five seconds by default) is not stopped. Other clients get BUSY errors. If the script has already written, only SHUTDOWN NOSAVE ends it. 7 So no loops over big data inside scripts.
Pick the structure that fits
- Sorted sets keep members ordered by score. The docs list leaderboards and sliding-window rate limiters as uses. Adding or updating a member costs O(log N). 9
- Streams act like an append-only log, for events in order. 10 For when to pick a log over a queue, see queues vs logs.
- HyperLogLog estimates unique counts, like unique visitors, in at most 12 KB, with a 0.81% standard error. 11
What a crash can lose
Redis has two ways to reach disk. 12
- An RDB snapshot is a point-in-time copy, written by a forked child. You usually save one every few minutes, so be ready to lose "the latest minutes of data".
- The append-only file (AOF) logs every write. Its
appendfsyncsetting decides how often Redis calls fsync:always,everysec(the default) orno. Witheverysecyou may lose 1 second of data. Withno, Linux usually flushes every 30 seconds. If the disk is slow,everyseccan lose up to about 2 seconds. 3
The docs suggest both together if you want safety close to PostgreSQL. 12
When memory is full
maxmemory caps the data size. On 64-bit systems the default is 0, which means no limit. 13 The default policy, noeviction, returns an error for writes that would add data when memory is full. Reads still work. 13 For a cache, allkeys-lru is a good default, as in caching stampedes. 13 The volatile-* policies only evict keys with a TTL, so with no TTLs they act like noeviction. Replication and AOF buffers are not counted, so leave some RAM free. 13
Copies, failover and shards
Replication is asynchronous. The primary replies to you, then sends the write to replicas. 14
WAIT n timeout blocks until n replicas acknowledge your earlier writes, or until the timeout. It returns how many did, so check that number. 15 It "does not make Redis a strongly consistent store". A write that reached replicas can still be lost in a failover. 15 min-replicas-to-write, with min-replicas-max-lag, limits the loss window to a few seconds. It does not remove it. 14
Sentinel watches a primary and its replicas. It promotes a replica when the primary fails, and tells clients the new address. Run at least three Sentinels. 16 The docs describe the result as "last failover wins": there is always a window for losing acknowledged writes. 16
Redis Cluster also shards data. Each key maps to one of 16,384 hash slots: CRC16 of the key, modulo 16384. 17 Multi-key commands, transactions and scripts work only if all keys share a slot. A hash tag forces this: user:{123}:profile and user:{123}:account land together. 17 Cluster can also lose acknowledged writes, through async replication or a network partition. 17
Locks in Redis, and the Redlock debate
The simple lock is one command: SET lock:job42 <random-value> NX PX 30000. Release it with a script that deletes the key only if the value is still yours. 18
On one primary with a replica, a failover can hand the same lock to two clients. The write may not have reached the replica yet. 18 Redlock answers this. A client takes the lock on a majority of, say, 5 independent primaries, within the lock's validity time. 18
Martin Kleppmann argued that Redlock depends on timing assumptions: bounded network delay, process pauses and clock error. A clock jump can let two clients hold the lock. 19 His advice: for efficiency, one Redis node is enough. For correctness, use fencing tokens and a consensus system such as ZooKeeper. 19 The locks lesson covers the pause problem.
Salvatore Sanfilippo (antirez), who wrote Redis, replied. If your storage can check tokens, he says, "you probably don’t need a distributed lock at all". A unique random token with check-and-set can work too. 20 He pointed out that Redlock checks the time again after it gets the majority. He also said pauses after that point hurt "all the distributed locks implementations". On clocks, he replied that Redlock does not need synchronized clocks. Processes only need to count time at about the same speed. He said ops teams can avoid big clock jumps: don't set clocks by hand, and use an ntpd that spreads changes out. 20 He did agree Redis should move to monotonic time. But he found no other point that broke Redlock's safety, and he rejected the advice to stop using it. 20
Today the Redis docs point readers to both posts. They tell you to use fencing tokens, and warn that TTLs do not use a monotonic clock. 18
Trade-offs
| Persistence setting | What a crash can lose | Cost | Use it when |
|---|---|---|---|
| None | Everything. | Fastest. A restarted empty primary can wipe its replicas. | A pure cache you can rebuild. |
| RDB snapshots only | Minutes of writes. | A fork per save, which can pause Redis. | Losing a few minutes is fine. |
AOF, everysec | About 1 second of writes. | Bigger files, some disk I/O. | The usual choice for data you care about. |
AOF, always | Very little. | "Very very slow." | Rarely. If every write must be on disk, a disk-first database may fit better. |
| RDB + AOF | About 1 second, plus easy backups. | Both costs. | You want safety close to PostgreSQL. |
At work: how a senior uses this
- Ask of every Redis use: "Is this a cache, or the only copy?" Settings for the two are very different.
- Rename or block
KEYSandFLUSHALLfor app users with ACLs. UseSCANandUNLINKin tools and scripts. - Watch the slow log and the latency monitor. A CPU-busy Redis with low traffic usually means slow commands. 3
- Keep values and collections small. A 5-million-member set is a slow command waiting to happen.
- Set
maxmemoryand a policy on purpose. Alert on evictions and on rejected writes. - Never turn off persistence on a primary that restarts by itself. It comes back empty, and replicas copy the empty set. 14
- For locks, ask: efficiency or correctness? For correctness, the database must check a token or a version.
- Treat client connections as stateful. On a cancel or timeout, drop the connection. Don't return it to the pool. 2
With AI
What to ask the agent
"Find every Redis call in this repo that is O(N) on a large key or keyspace: KEYS, SMEMBERS, HGETALL, LRANGE 0 -1, DEL on big keys. Suggest SCAN, paging or UNLINK for each."
"Rewrite this read-then-write Redis code as one Lua script. Pass all key names in KEYS. Add a test with 50 parallel clients."
"Review our Redis config for a cache: maxmemory, maxmemory-policy, persistence and io-threads. Explain each choice for a 16 GB, 4-core machine."
What to check yourself
- No script loops over a whole collection. Scripts must stay short.
- Every key the script uses is passed in
KEYS, and multi-key operations use hash tags in Cluster. - The code checks for a null
EXECand retries. - Any lock has a TTL, a unique value, and a safe release. Correctness still rests on a fencing check.
- A cancelled or timed-out request closes its connection.
- Nobody assumes
WAITmakes a write safe from failover.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 20 sources and related lessons
- OpenAI, “March 20 ChatGPT outage: Here’s what happened”, 24 March 2023 (opens in a new tab)
OpenAI's own account of the redis-py bug, what users could see, and the fixes. - redis/redis-py issue #2624, “Off by 1 - Canceling async Redis command leaves connection open, in unsafe state for future commands” (opens in a new tab)
A short script that shows a cancelled command leaving its reply on the connection. - Redis documentation, “Diagnosing latency issues” (opens in a new tab)
The single-threaded design, slow commands, KEYS, fork and fsync as sources of latency. - redis/redis pull request #13695, “Async IO Threads” (opens in a new tab)
How I/O threads read, parse and write while the main thread still runs every command. - Redis source, redis.conf (sections “THREADED I/O” and “LAZY FREEING”) (opens in a new tab)
When to turn on io-threads, and why DEL of a huge key blocks while UNLINK does not. - Redis documentation, “Transactions” (opens in a new tab)
What MULTI/EXEC guarantees, why there is no rollback, and WATCH for check-and-set. - Redis documentation, “Redis programmability” (opens in a new tab)
Scripts and functions run atomically and block the server; the five-second busy limit. - Redis documentation, “Scripting with Lua” (opens in a new tab)
EVAL, the KEYS and ARGV arguments, and why every key a script touches must be passed in. - Redis documentation, “Redis sorted sets” (opens in a new tab)
Sorted sets for leaderboards and sliding-window rate limiters. - Redis documentation, “Redis data types” (opens in a new tab)
A one-line summary of every Redis data type, including streams. - Redis documentation, “HyperLogLog” (opens in a new tab)
Counting unique items in at most 12 KB, with a 0.81% standard error. - Redis documentation, “Redis persistence” (opens in a new tab)
RDB snapshots, the append-only file, the three fsync policies and what each can lose. - Redis documentation, “Key eviction” (opens in a new tab)
maxmemory, every eviction policy, and the buffers that maxmemory does not count. - Redis documentation, “Redis replication” (opens in a new tab)
Asynchronous replication, WAIT, min-replicas-to-write, and the empty-primary restart trap. - Redis documentation, “WAIT” (opens in a new tab)
Why WAIT does not make Redis strongly consistent. - Redis documentation, “High availability with Redis Sentinel” (opens in a new tab)
What Sentinel does, why you need three of them, and the window for lost writes. - Redis documentation, “Scale with Redis Cluster” (opens in a new tab)
Hash slots, hash tags, and two ways Redis Cluster can lose acknowledged writes. - Redis documentation, “Distributed Locks with Redis” (opens in a new tab)
The single-node lock, the Redlock algorithm, and the docs' own consistency warnings. - Martin Kleppmann, “How to do distributed locking”, 8 February 2016 (opens in a new tab)
The critique of Redlock's timing assumptions, and fencing tokens. - Salvatore Sanfilippo (antirez), “Is Redlock safe?” (opens in a new tab)
The Redis author's reply to Kleppmann, point by point.
Real incident: OpenAI, 20 Mar 2023: ChatGPT: a Redis client bug showed some users other users' data
Case studies: Zerodha: Scaling a large broker with simple, boring choices
Related: Caching and cache stampedes · Rate limiting · Locking and MVCC in practice · Locks, atomics and deadlocks · Batching and pipelining · Replication · Sharding and consistent hashing · Leaderboards and live ops (coming soon) · Distributed caches · Leader election and leases
Before this: Caching stampedes, Rate limiting and Locking and MVCC in practice. Related: Batching and pipelining, Database replication, Sharding and consistent hashing and Consensus and Raft. See also Leader election and leases. Coming later: Leaderboards and live ops.