← All lessons

Key technologies

Redis

Most candidates call it a cache. It is a single-threaded data structure server, and nearly every good follow-up comes from that sentence.

24 min readUpdated October 2026Free

“We’ll put a Redis cache in front of it” is the most common sentence in system design interviews and one of the least informative. It tells the interviewer you know caching exists. It does not tell them whether you know what happens when the cached key expires under load, where the data goes when the node restarts, or why the lock you just described does not actually guarantee what you think.

Redis rewards a precise answer more than almost any other technology in these interviews, because the useful facts are mechanical and most people only know the marketing.

What Redis actually is

Redis is an in-memory data structure server, and it is single-threaded for command execution.

Both halves matter. “Data structure server” means you are not storing opaque blobs — you get sorted sets, hashes, streams and bitmaps as first-class things, with operations that run next to the data rather than requiring a read-modify-write from your application. “Single-threaded” means one command runs at a time, to completion, in the order received.

The point

Single-threaded execution is why every individual Redis command is atomic for free. No locks, no transactions, no compare-and-swap loop. INCR cannot lose an increment. ZINCRBY cannot lose a point. That is not a performance footnote; it is the property most Redis patterns are built on.

It is also why Redis is fast in a way that surprises people: no lock contention, no context switching between threads, and everything in RAM. A single instance handles on the order of 100,000 operations per second on ordinary hardware, with sub-millisecond latency — and the network round trip is usually the dominant cost, not the work Redis does.

The flip side is the thing to say before the interviewer says it: one slow command blocks everything. More on that below, because it is where real outages come from.

The data types, and what each one buys you

Knowing which structure solves which problem is most of the value. This is the table worth memorising.

Type Key operations What it is for
String GET SET INCR SET NX EX Cached values, counters, idempotency keys, locks
Hash HGETALL HSET HEXPIRE An object read in one round trip; per-field TTL since 7.4
List LPUSH BRPOP Simple queues and recent-items feeds
Set SADD SISMEMBER SINTER Membership, tags, “friends in common”
Sorted set ZADD ZRANGEBYSCORE ZREVRANK Leaderboards, schedulers, sliding windows, priority
Stream XADD XREADGROUP XACK XCLAIM Durable work queues and event logs with consumer groups
HyperLogLog PFADD PFCOUNT Unique counts in ~12 KB at any cardinality
Bloom / Count-Min / Top-K BF.ADD CMS.* TOPK.* Dedup, frequency and trending in fixed memory
Bitmap SETBIT BITCOUNT Daily-active flags, feature flags per user id
Vector index FT.CREATE + KNN Recommendations, semantic cache, agent recall

Two of these are worth reaching for unprompted because they make you sound like you have shipped something.

Sorted sets are the workhorse. The score is just a number, so it can mean points (leaderboard), a due timestamp (delayed job queue), or an event time (sliding-window rate limit). ZREVRANK answers “what is my rank out of ten million” in O(log N) — the query that is a crippling COUNT(*) in a relational database.

HyperLogLog is the trade nobody regrets. Unique visitors per day, exactly, means storing every visitor id. A HyperLogLog does it in about 12 KB regardless of cardinality, with 0.81% standard error. Nobody needs that number exact.

Run it yourself

Twelve labs against a real Redis 8

redis-lab has one small, tested component per pattern below — 60-plus tests, no mocks, every one against a real container. Each lab’s test suite is written as claims about behaviour, including the failure modes, so “I read that Redis locks are unsafe” becomes an interleaving you have watched fail.

Open the lab repo →

Single-threaded means one slow command stops the world

This is the operational fact that turns into an interview answer and a production incident.

Because commands run one at a time, an O(N) command over a large collection blocks every other client for its whole duration. The usual culprits:

Where candidates lose it

“Redis is fast so this is fine” is the wrong instinct. Redis is fast per operation; it has no concurrency to hide a slow one behind. A single KEYS on a few million keys is hundreds of milliseconds during which every other request in your fleet waits. Mention SCAN over KEYS unprompted and you have signalled production experience in six words.

The same property is what makes Lua scripts the standard answer to “how do you make these three operations atomic”. A script runs as one uninterruptible unit, so a read-compute-write that would be a race from your application becomes a single step. Keep them short, for the reason above.

Caching, done properly

Everyone proposes cache-aside: read from Redis, on a miss read the database and write it back. The pattern is three lines. The interview is about the two ways it hurts.

Stampede

A popular key expires. Every concurrent request for it misses at the same moment, and they all hit the database together — precisely when the key is hottest and the database can least cope.

A popular key expires and many concurrent requests miss at once. Without protection every one of them queries the database. With one loader admitted per key, the database is touched once and the remaining requests read the cache the loader fills. one popular key expires — 20 concurrent requests…20 of themRediskey expired1 loader admitted19 poll for the filled cachePostgres1 queryUnprotected, the same picture sends 20 queries — at the exact moment the key is hottest.A fixed sleep for the waiters is not enough: if the loader is slower, the herd arrives anyway.
Cache stampede: one loader per key is admitted to the source; the rest read what it writes.

The fix is to admit one loader per key and have the rest wait for its result. Note the detail that catches people: a fixed sleep for the waiters is not enough. If the loader takes longer than the sleep, every waiter wakes to a still-empty cache and the herd arrives anyway. The waiters have to poll for the value, or the loader has to publish it.

Negative caching

If “not found” is never cached, then requesting a bogus id in a loop is a free denial-of-service against your database — every request misses the cache by construction. Cache the absence too, with a shorter TTL than real values.

What a TTL actually means

The point

A TTL is a staleness budget, not a lifetime. TTL 60 does not mean “this data lives for a minute”, it means “we accept being up to a minute behind”. If that is unacceptable, invalidate on write instead of waiting for expiry. And if the data must never be stale, the answer is not a cache.

Say that sentence in an interview and you have answered the consistency follow-up before it arrives.

Run it yourself

Stampede and negative caching, measured

Lab 8 runs 20 concurrent misses against a 100 ms load and asserts the source was touched exactly once. The fixed-sleep version is in the tests too, failing the way described above.

Open the lab repo →

Durability: Redis is not your source of truth

The question “what happens when the Redis node restarts” has a precise answer, and most candidates guess.

RDB takes point-in-time snapshots. Compact and fast to load, but a crash loses everything since the last snapshot.

AOF appends every write to a log. The durability depends entirely on the fsync policy: everysec (the default) can lose up to a second of writes; always fsyncs per write and costs you most of the throughput; no leaves it to the OS.

Most production setups run both. But the fact that actually matters in a design discussion is different:

Where candidates lose it

Redis replication is asynchronous. A write acknowledged by the primary has not necessarily reached any replica, so a failover can lose acknowledged writes. WAIT lets you block until N replicas have the write, which narrows the window but is not a durability guarantee either. This is why a Redis stream is an excellent work queue and a bad transactional outbox — for an outbox the event must be written in the same database transaction as the data it describes.

So: Redis holds derived state, hot state, and state you can rebuild. Say out loud which category your Redis data falls into and you have pre-empted the whole line of questioning.

Expiry and eviction are different things

Candidates conflate these constantly, and the distinction is an easy mark.

Expiry is per key, and you asked for it (EX, PX, EXPIRE). Redis removes expired keys lazily — when the key is next touched — plus a background sampling pass. Which means an expired key can occupy memory after its TTL has passed, and keyspace notifications for expiry are lossy and late: they fire when the key is actually reclaimed, not when it logically expired. Do not build a scheduler on them. Use a sorted set scored by due time.

Eviction is what happens when maxmemory is reached, and the policy decides your failure mode:

maxmemory-policy Behaviour
noeviction Writes fail with an error. Correct for a queue or a lock store — silently dropping those is worse.
allkeys-lru Evict least-recently-used across all keys. The right default for a pure cache.
volatile-lru Evict LRU among keys that have a TTL. Lets cache entries be evicted while durable keys are protected.
allkeys-lfu Least-frequently-used. Better when a few keys are persistently hot.
Say it like this

“I’d run two Redis deployments, or at minimum separate databases with different policies: the cache on allkeys-lru where eviction is harmless, and the rate-limit and lock keys on noeviction, where losing a key means letting traffic through or handing out a duplicate lock.”

That answer is unusual and it is correct, which is a good combination.

Distributed locks, and the honest caveat

The recipe is easy. SET lock:<resource> <unique-token> NX PX 30000 — set if absent, with a lease. Release with a Lua compare-and-delete, so you never delete a lock that is no longer yours. A bare DEL deletes whoever holds it now, which after your own lease expired is somebody else.

Then the part that distinguishes you:

Client A acquires a lock with fencing token 33, then stalls in a garbage-collection pause until its lease expires. Client B acquires the lock with token 34 and writes. When A wakes it still believes it holds the lock, but the resource has already seen token 34 and rejects A's write carrying the lower token 33. Client AClient BStoragelock, token=33GC pause — lease expireswrite(33)lock, token=34write(34)seen: 3433 < 34rejectedNo TTL prevents this, and neither does Redlock across several masters.Only the resource checking a monotonic token does.
A Redis lock is safe for efficiency, not correctness. A fencing token is what makes the protected resource safe.

A GC pause, a stalled syscall or a slow network can leave your process believing it holds a lease Redis has already reassigned. No TTL fixes this — a shorter lease makes it more likely, a longer one makes recovery slower. And Redlock across several masters does not fix it either; that was the core of Kleppmann’s critique, and it is about process pauses, not about node failures.

The point

A Redis lock is safe for efficiency — stopping two workers from doing the same expensive thing — not for correctness. If two simultaneous holders would corrupt data, you need a fencing token: a monotonically increasing number that the protected resource itself checks, rejecting anything stale. The lock service hands out the number; the storage layer enforces it.

If the resource cannot check a token, then Redis locks cannot give you correctness, and the real answer is a transaction or a conditional write in the datastore that owns the data.

Run it yourself

Watch the lock fail safely

Lab 4 implements both: the SET NX PX lock with a Lua release, and a fenced version. Its test walks the exact interleaving in the diagram — A stalls, B acquires, A wakes and is refused.

Open the lab repo →

Queues: list versus stream

If asked to build a work queue on Redis, the choice of structure is the answer.

A list with LPUSH / BRPOP is a queue in two commands, and it loses work. BRPOP removes the item; if the worker dies holding it, it is gone. There is no record that it was ever delivered.

A stream is an append-only log with consumer groups. Entries stay after being read, each group keeps its own cursor, and every delivery is tracked in a Pending Entries List until it is acknowledged with XACK. A worker that dies leaves its entry in the PEL, and XCLAIM lets another worker take it over after an idle timeout — which is exactly a visibility timeout.

Where candidates lose it

Nothing is redelivered automatically. An entry read by a worker that then dies sits in that worker’s PEL forever. Other workers polling normally see nothing: the entry is not “available” again, it is owned by a consumer that no longer runs. A consumer group without an explicit recovery pass silently strands work. That recovery pass is yours to write.

Delivery is at-least-once, so handlers must be idempotent — the same conclusion as Kafka, for the same reason. And XRANGE gives you the capability a list cannot: re-read the retained log from any id without consuming anything or disturbing a single group cursor.

Pub/Sub is the opposite trade. PUBLISH to a channel with no subscriber returns 0 and the message is simply gone — not queued, not retried, and a reconnecting subscriber cannot ask what it missed. That makes it right for cache-invalidation fanout, where a restarted instance has an empty local cache anyway, and wrong for anything you cannot lose.

Run it yourself

Strand a job, then recover it

Lab 1 is the one to study first: PEL inspection, XCLAIM recovery and replay. Lab 11 asserts the zero-subscriber Pub/Sub case explicitly, because that is the whole point of the comparison.

Open the lab repo →

Rate limiting: why the obvious way is wrong

INCR a key named for the current minute, EXPIRE it, reject above the limit. It is three lines and it permits twice your limit: a caller spends its full quota at the end of one window and its full quota again at the start of the next, so the real peak over a sliding minute is double.

A token bucket refills by elapsed time instead. That means reading two fields, computing against the clock, and writing both back — four round trips and a race from your application, one atomic step in Lua.

A sliding window with a sorted set is the other honest answer: ZADD the request time, ZREMRANGEBYSCORE to drop anything older than the window, ZCARD to count. More memory, exact behaviour.

One Cluster detail worth dropping: every key a Lua script touches must hash to the same slot, so keys used together need a hash tag — rl:{alice}:tokens and rl:{alice}:ts share the braced part and therefore the slot.

Scaling, and the shapes it takes

Replicas scale reads and give you failover, with the asynchronous-replication caveat above. Sentinel adds automatic failover for a single primary. Cluster shards the keyspace across primaries using 16,384 hash slots.

Cluster is where the constraints bite:

Redis versus the alternatives

Reach for it when Avoid when
Redis You need data structures, sub-ms latency, atomic counters, leaderboards, rate limits, locks, a queue with replay It must be the durable source of truth
Memcached Pure key-value cache, multi-threaded, simplest possible You want any structure, persistence, or replication
DynamoDB + DAX You are on AWS and want a durable store with a managed cache in front You want sorted sets and Lua
Kafka Event log for many independent consumers, long retention, high sustained throughput You want sub-ms reads of current state
Postgres It is the source of truth; SKIP LOCKED makes a decent queue at modest volume You need 100k ops/s of counter updates
Dedicated vector DB Billions of vectors, advanced index tuning You already run Redis and want KNN with filters in one call

When to propose Redis in an interview

Say it when the design needs one of:

Do not say it when you have just described a durable system of record, when the data is larger than RAM is affordable for, or when the real problem is an unindexed query. “Put Redis in front of it” to fix a slow query is the answer an interviewer is often testing for — adding a cache to hide a missing index is how you get a fast system that serves stale wrong answers.

Say it like this

“I’d cache the product page read-through in Redis with a 60-second TTL, single-loader protection so an expiry doesn’t stampede the database, and tombstones for missing ids so a scan of bogus ids can’t become a denial of service. Redis holds nothing here that I can’t rebuild from Postgres — and I’d check the query is indexed before I cache it, because otherwise the cache is hiding the real bug.”

Sizing it on the whiteboard

Memory is the whole calculation, and candidates forget the overhead. Say 10 million cached product records at ~2 KB of JSON each:

Throughput: 100k ops/s per instance as a working figure, so a read-heavy design needs replicas long before it needs Cluster.

The follow-ups, and the one-line answers

  1. “What happens when the cache expires under load?” Stampede. One loader per key, waiters poll for the result, tombstones for misses.
  2. “Is the data safe if Redis restarts?” RDB plus AOF narrows the loss; replication is async, so a failover can lose acknowledged writes. Nothing lives only in Redis.
  3. “How do you stop two workers doing the same job?” SET NX PX with a unique token and a Lua release — safe for efficiency. For correctness, a fencing token the storage layer checks.
  4. “How do you rate limit across replicas?” Token bucket in a Lua script; one atomic step, with a hash tag so it works in Cluster.
  5. “What’s the eviction policy?” allkeys-lru for the cache, noeviction for locks and counters — and that is a reason to separate them.
  6. “How do you find my rank out of 10 million?” ZREVRANK, O(log N).
  7. “Why not just a list for the queue?” BRPOP loses the item if the worker dies. Streams track delivery in the PEL and XCLAIM reassigns it.
  8. “What would you never put in Redis?” Anything whose loss I could not tolerate or recover, and anything I would need to query by something other than the key I stored it under.