π₯ Redis Internals (important parts only)
1. Execution model
- Single-threaded command execution on an event loop (epoll) β every command is atomic β no locks
- I/O threads (6.0+) can parallelize socket reads/writes, but execution stays single-threaded
- Consequence: one slow command blocks everyone β avoid
KEYS *(useSCAN), hugeHGETALL/SMEMBERS, deleting big keys synchronously (UNLINK= lazy free) - Lua scripts / Functions run atomically too, so keep them short
2. Data structure encodings (memory vs speed)
| Type | Small encoding | Large encoding |
|---|---|---|
| String | int / embstr / raw (SDS: length-prefixed, binary-safe) | |
| Hash | listpack (compact contiguous) | hashtable |
| List | listpack | quicklist (linked list of listpacks) |
| Set | intset / listpack | hashtable |
| Sorted set | listpack | skiplist + hashtable (O(log n) ranks + O(1) score lookup) |
- Conversions happen at thresholds (
hash-max-listpack-entries, etc.): small objects are very memory-efficient - The hashtable uses incremental rehashing (two tables, migrated a bit per operation) β no big pause
3. Expiry & eviction
- Expiry: lazy (checked on access) + an active expire cycle (samples keys with TTLs, repeats if many were expired)
- Eviction (
maxmemory-policy): approximated LRU/LFU by samplingmaxmemory-sampleskeys; LFU uses a probabilistic counter with decay
4. Persistence
- RDB:
fork()+ copy-on-write snapshot β a memory spike proportional to the write rate during the snapshot; fork latency on large heaps - AOF: append every write;
appendfsync everysec(β€ 1 s of loss) vsalways(slow); background AOF rewrite compacts it - Durability β the main use case: treat Redis as a cache/ephemeral coordinator unless youβve designed for it
5. Replication & cluster
- Async replication with a replication backlog +
PSYNCpartial resync;WAITfor synchronous-ish acks (still not strong consistency) - Cluster: 16,384 hash slots (CRC16(key) mod 16384); hash tags
{tenant42}:quotakeep related keys in one slot (required for multi-key ops/Lua);MOVED/ASKredirects; gossip bus; replica promotion on failure - Failover can lose acknowledged writes (async) β distributed locks on Redis need fencing tokens
π¬ Prove it
-
OBJECT ENCODINGon a hash as it grows past the listpack threshold;MEMORY USAGEbefore/after -
redis-benchmarkwith and without pipelining (-P 16) β explain the throughput jump (RTTs) - Put 1M elements in a list,
DELit while another client does GETs β measure the latency spike β repeat withUNLINK -
SLOWLOG GET,LATENCY DOCTORafter aKEYS *on 1M keys - Trigger
BGSAVEunder heavy writes, watch RSS andINFO persistence(latest_fork_usec) - Your Lua token bucket: 200 concurrent goroutines β prove thereβs no over-admission
Interview questions interview-q
Why Redis is fast despite being single-threaded Β· how expiry works Β· RDB vs AOF Β· cluster hash slots and hash tags Β· why Redlock is controversial Β· the cache stampede and how to prevent it