Redis internals: why it is fast, how it stores data and how it removes expired keys
Why Redis runs commands on one thread and still handles hundreds of thousands per second, and why one KEYS * can freeze the whole system. The event loop, io-threads (rewritten in Redis 8), compact encodings, the two ways expired keys are removed, eviction policies, Redis 8 and Valkey; how to review Redis code written by AI.
On this page
1. The problem
A Redis cache with 8 million keys, GET p99 at 0.4 ms. A session-cleanup job at 2 a.m. calls KEYS session:*: Redis freezes for 2.1 seconds and 1,200 requests time out. CPU stays under 15%, and Redis logs no errors.
2. Key idea
Redis runs every command one after another on one thread. Like a single, very fast cashier: one slow customer and the whole line waits.
| Why it's fast | The price |
|---|---|
| Data lives in RAM | it must fit in RAM; when full, evict or refuse writes |
One command thread: no locks, INCR is atomic for free |
one O(N) command raises every client's p99 |
I/O multiplexing (epoll): only handles sockets with data |
more cores for commands means more instances or Cluster |
| Compact encodings (listpack, intset) for small collections | past the threshold memory jumps and never shrinks back |
io-threads (off by default) only read and write sockets; persistence runs in a child process after fork(); background threads handle AOF fsync and freeing memory for UNLINK.
2.1 What to use to avoid blocking?
| Tool | Use when | Don't use when |
|---|---|---|
SCAN, HSCAN, SSCAN in batches |
iterating many keys or a big collection | you need an exact snapshot (SCAN may return duplicates) |
| Group small keys into hashes of ≤ 512 fields | millions of small values of one kind | each value needs its own TTL (unless HEXPIRE) |
| TTLs with jitter | loading caches in bulk | keys must expire at one exact moment |
UNLINK, lazyfree-lazy-* |
deleting large values | memory must be freed within the command |
allkeys-lru/allkeys-lfu |
pure caches: a lost key is just a miss | sessions, locks, queues: noeviction, a separate instance |
A hash's encoding threshold: at most 512 fields and every value ≤ 64 bytes. 512 short fields is 5 KB; one more field is 28 KB (Redis 7.4).
3. In Java
// Wrong: KEYS walks the whole keyspace on the single command thread
// Set<String> keys = redis.keys("session:*");
// Right: SCAN in batches of 500, delete with UNLINK (freed on a background thread)
var opts = ScanOptions.scanOptions().match("session:*").count(500).build();
try (Cursor<String> cursor = redis.scan(opts)) {
List<String> batch = new ArrayList<>(500);
while (cursor.hasNext()) {
batch.add(cursor.next());
if (batch.size() == 500) { redis.unlink(batch); batch.clear(); }
}
if (!batch.isEmpty()) redis.unlink(batch);
}
// TTL with jitter so 1 million keys don't all expire in the same second
Duration ttl = Duration.ofSeconds(3600 + ThreadLocalRandom.current().nextInt(300));
redis.opsForValue().set(key, json, ttl);redis is a StringRedisTemplate. Other languages: Go go-redis has a Scan iterator; Node.js ioredis has scanStream; Python has scan_iter.
Key expiry, Redis 8 and Valkey
- Expiry: keys with a TTL live in the
expiresdict. They're removed lazily when a command touches them, and actively by theserverCronloop (defaulthz 10) sampling keys with TTLs. Millions of keys expiring together make the active loop work hard and latency spikes;SLOWLOGdoesn't show it because it isn't a client command. - Diagnosis:
SLOWLOG GET,LATENCY DOCTOR(afterCONFIG SET latency-monitor-threshold 10),INFO persistence→latest_fork_usec. Block dangerous commands with the ACL-@dangerous. - Oversized instances aren't slow because of some RAM threshold, but because
fork()and replica sync take long. Use several moderate shards. - Redis 8 folds JSON, time series, probabilistic types and the query engine into the main release and adds an AGPLv3 licence. Valkey (a BSD fork of 7.2.4 under the Linux Foundation) is offered on ElastiCache and Memorystore. Both are compatible on core commands up to 7.2; each side's new features aren't.
- Memcached is multi-threaded, byte strings only, with no built-in persistence or failover; nodes are split by client-side consistent hashing.
4. Working with AI
Delegate to AI: converting keys() to scan(), scripts that load test data to measure MEMORY USAGE, reading INFO output.
Check yourself:
- No
keys(),KEYS *or synchronousFLUSHALLin production code. - No
HGETALL,SMEMBERS,LRANGE 0 -1on collections that can grow large. - Bulk-loaded TTLs have jitter; large values are deleted with
UNLINK. - Caches and data that mustn't be lost (locks, sessions) don't share an
allkeys-lruinstance.
5. Exercises
Exercise 1: Review a "light, hourly" cart-cleanup job
Production has 3 million carts, one hash each. Find the bugs and fix them.
@Scheduled(cron = "0 0 * * * *")
void cleanAbandonedCarts() {
Set<String> keys = redis.keys("cart:*");
for (String key : keys) {
Map<Object, Object> cart = redis.opsForHash().entries(key);
if (isAbandoned(cart)) redis.delete(key);
}
}Solution to Exercise 1
keys("cart:*")walks the keyspace on the single thread: Redis freezes for seconds. Usescan()withcount(500).entries()isHGETALL: slow for big carts. If you only need the update time,HGETone field; better, use a sliding TTL (extended on every change) so Redis cleans up itself and no job is needed.deleteis a synchronousDEL: switch tounlink.- The job runs on the hour on every service instance: it needs a distributed lock or a single runner.
- Proof: load 1 million test keys, run the job, check
SLOWLOG GETandLATENCY LATEST.
Exercise 2: Read an on-the-hour latency incident
p99 is normally 1 ms but jumps to 80 ms for a few seconds every hour on the hour. INFO stats at 10:00:02 shows expired_keys up 900,000 versus a minute earlier; SLOWLOG GET is empty. What's the likeliest cause, what do you do in the next 15 minutes, and which hypotheses must you rule out?
Solution to Exercise 2
- Likeliest: an hourly cache-loading job sets a round 1-hour TTL, so 900,000 keys expire together; the slowlog is empty because expiry isn't a client command. 15 minutes:
CONFIG SET lazyfree-lazy-expire yes; fix the root with TTL jitter. - Rule out: scheduled RDB snapshots (
fork()blocks the main thread): checklatest_fork_usec. AOF rewrite andfsyncstalled on disk: look for "Asynchronous AOF fsync is taking too long". O(N) commands from cron: ruled out by the empty slowlog.
Summary
- One command thread: fast because commands are O(1), slow for everyone when one is O(N).
- Use
SCANinstead ofKEYS,UNLINKinstead ofDELfor large values. - Compact encodings only hold below thresholds; above them memory jumps.
- Jitter TTLs so keys don't expire en masse.
- Separate caches from data that mustn't be lost, with different eviction policies.
Next: Part 2: Persistence, replication, Sentinel and Cluster.
Practice interview questions on this topic
- Why is Redis fast despite being single-threaded, and is Redis 6+ still single-threaded?
- How do Redis and Memcached differ, and when do you choose each for a project?
- How does TTL work in Redis, and what happens when Redis runs out of memory?
- What are Redis's main data types, and what problem does each one solve?
- Hot keys, big keys and slow commands are pushing Redis p99 up: how do you find and fix them?
Comments
Community rules