Redis
medium 34 minRedis keeps its whole dataset in memory and runs commands one after another, so every command is atomic and most take well under a millisecond.
See it run
One command thread, memory that fills up, a restart, a failover and a cluster, step by step.
Operations
The command loop
Two clients send commands. Redis runs them one after another, so each is atomic, and a slow one delays the rest.
Step 1 of 5
Two commands arrive
waiting
INCR (web) · INCR (mobile)
running
nothing
Both clients send INCR likes at the same moment. The value is 10.
Step 1: Two commands arrive
while True: for client in ready_sockets(): # epoll or kqueue command = read(client) reply = run(command) # one at a time write(client, reply)- Waits for
- The queue
- Can lose
- Nothing
- SCAN instead of KEYS
- many short turns
Atomic covers one command. Reading, changing in your program and writing back is three.
In the real world
The same redis doing real jobs. Pick one and step through it.
Two servers miss at the same moment. Only one goes to the database.
Step 1 of 4
Hit
Hit
Both servers read the page from Redis. The database is idle.
Step 1: Hit
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No memory limit
criticalOn 64-bit systems the default is no limit. The process grows until the operating system kills it.
Wrong# redis.conf: nothing setRightmaxmemory 6gbmaxmemory-policy allkeys-lfuRead, change, write back
criticalTwo clients read the same value and one update is lost.
Wrongn = int(r.get("stock"))r.set("stock", n - 1)Rightleft = r.decr("stock")if left < 0: r.incr("stock")Deleting a lock without checking the owner
majorYour lock may have expired and belong to somebody else now.
Wrongr.delete("lock:job")Rightr.eval(RELEASE_IF_MINE, 1, "lock:job", token)KEYS in production
majorIt walks every key on the only command thread.
Wrongfor k in r.keys("user:*"): ...Rightfor k in r.scan_iter("user:*", count=100): ...Expecting replicas to be current
minorReplication is asynchronous, so a user may not see their own change.
Wrongprimary.set(k, v)return replica.get(k)Rightprimary.set(k, v)return v # or read the primary
Interview tips
How to explain it
- Data structures in memory, one command thread.
- Atomic commands, optional persistence.
- Replicas for copies, slots for scale.
Before production
- maxmemory and a policy.
- TTL on every cache key.
- Short timeouts and a fallback.
- Alerts on evictions and replica lag.
Reach for it when
- The same data is read very often.
- You need a counter, a rank or a short-lived session.
- The hot data fits in memory.
Be careful when
- It would be the only copy.
- Two lock holders would corrupt data.
- One key takes most of the traffic.