Redis
Redis is an in-memory data structure server. It holds keys in RAM, and each key maps to a value that can be a string, a hash, a list, a set, a sorted set, a stream and more. Clients send commands over TCP (SET, INCR, ZADD, XADD) and get answers back in well under a millisecond. It's most famous as a cache, but it's just as often used for rate limiters, leaderboards, locks, session stores, queues and real-time counters.
The properties that matter:
- In memory: all data lives in RAM, which is why it's fast and why the dataset has to fit in memory (across the cluster).
- Single-threaded command execution: one thread executes commands one at a time, so each command is atomic with no locks. A single instance handles on the order of 100,000+ simple operations per second, and more with pipelining.
- Rich data structures: the server implements the structures and their operations, so "add 10 points to this player and return their new rank" is one command, not a read-modify-write in your app.
- Optional persistence: snapshots and an append-only log can save data to disk, but Redis is usually not the system of record.
- Replication and sharding: asynchronous replicas for read scaling and failover (with Sentinel), and Redis Cluster for spreading keys across many nodes.
Redis appears in a large share of system design answers, often in several roles at once. Interviewers rarely question "put a cache in front of the database," but they do probe the details: what happens on a cache miss storm, how you avoid a hot key, whether a Redis lock is safe, what you lose if a node fails, and why Redis and not Memcached. We'll cover each.
A note on names: after Redis changed its license in 2024, the Linux Foundation started Valkey, an open-source fork that is protocol-compatible. Cloud providers offer both (for example Amazon ElastiCache and MemoryDB). Everything below applies to either.
Data Structures
Choosing the right structure is most of the skill in using Redis.
| Type | Key commands | Typical uses |
|---|---|---|
| String (up to 512 MB) | GET, SET ... EX/PX NX, INCR, INCRBY |
Cached objects, counters, locks, idempotency keys |
| Hash | HSET, HGET, HINCRBY, HGETALL |
Objects with fields (a user session, a product's live stock) |
| List | LPUSH, RPOP, BLPOP, LRANGE, LTRIM |
Simple queues, recent-items lists (last 100 events) |
| Set | SADD, SISMEMBER, SINTER, SCARD |
Unique members, tags, "who liked this" for small sets |
| Sorted set | ZADD, ZINCRBY, ZRANGE, ZRANK, ZRANGEBYSCORE |
Leaderboards, priority queues, sliding windows, timelines |
| Bitmap | SETBIT, GETBIT, BITCOUNT |
Daily active users by user ID, feature flags per user |
| HyperLogLog | PFADD, PFCOUNT, PFMERGE |
Approximate unique counts (unique viewers) in 12 KB |
| Geo | GEOADD, GEOSEARCH |
Nearby drivers, stores within a radius |
| Stream | XADD, XREADGROUP, XACK |
Durable-ish event logs with consumer groups |
| Pub/Sub | PUBLISH, SUBSCRIBE |
Fire-and-forget fan-out to connected subscribers |
Newer Redis releases (and the earlier Redis Stack modules) also add JSON documents, probabilistic structures like Bloom filters and Top-K, time series and a search engine with vector indexes.
A few of these deserve a closer look:
- Sorted sets store unique members, each with a floating-point score, kept ordered by score. They're implemented as a skip list plus a hash table, so adding, updating, ranking and range queries are all O(log N). This is the structure behind nearly every leaderboard answer.
- HyperLogLog estimates the number of distinct elements with about 0.81% standard error using at most 12 KB, no matter whether you add a thousand items or a billion. Exact unique counting of a billion IDs would need gigabytes.
- Geo commands store locations in a sorted set, using a 52-bit geohash as the score, so "find drivers within 3 km" becomes a few range scans over the sorted set.
Why Redis Is Fast
But what is actually happening under the hood? Several design choices combine:
- Everything is in memory. A lookup is a hash table probe in RAM, not a disk seek or even a page-cache read.
- A single-threaded event loop. One thread uses the OS's event notification (epoll on Linux) to multiplex thousands of client connections. It reads a command, executes it to completion, queues the reply and moves on. There are no locks, no context switches between workers and no contention, so the CPU spends its time doing actual work. Since Redis 6, optional I/O threads handle reading and writing network buffers in parallel, but command execution stays on one thread.
- Compact encodings. Small hashes, lists, sets and sorted sets are stored as dense, contiguous listpacks (or integer arrays for small integer sets) instead of pointer-heavy structures. They switch to full hash tables or skip lists automatically when they grow past a threshold.
- A simple protocol and pipelining. Clients can send many commands without waiting for each reply, which removes network round trips from the cost. Batching 100 commands per round trip can multiply throughput several times.
The single thread has a flip side: one slow command blocks everyone. KEYS * on a million keys, HGETALL on a hash with millions of fields, SMEMBERS on a huge set, or deleting a huge key with DEL can stall the server for hundreds of milliseconds or more. Use SCAN / HSCAN / SSCAN to iterate incrementally and UNLINK to free large keys in the background, and keep individual keys reasonably small.
In an interview, the single-threaded model is useful in two directions. It explains why every Redis command is atomic (great for counters and rate limiters), and it explains why one instance has a throughput ceiling, so you scale by adding shards, not threads.
Atomic Operations
Every individual command is atomic. INCR, SET key value NX (set only if absent), ZINCRBY and HINCRBY need no extra coordination. For multi-step logic, there are three tools:
MULTI/EXEC: queue several commands and execute them together, with no other client's commands interleaved. There's no rollback: if one command fails, the rest still run.WATCH: optimistic locking. Watch a key, read it, thenMULTI ... EXEC. If the key changed in between,EXECaborts and you retry.- Lua scripts (
EVAL) and functions: run logic server-side atomically. Nothing else executes while the script runs, so keep scripts short.
Here's a sliding-window rate limiter as one atomic script, allowing limit requests per window for a key:
-- KEYS[1] = "rl:user:42" ARGV: now_ms, window_ms, limit, request_id
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1] - ARGV[2]) -- drop old entries
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[1], ARGV[4]) -- record this request
redis.call('PEXPIRE', KEYS[1], ARGV[2])
return 1 -- allowed
end
return 0 -- rejected
A cheaper fixed-window limiter is just INCR rl:user:42:<minute> followed by EXPIRE on the first increment, at the cost of allowing bursts at window boundaries. See rate limiters for the trade-offs between algorithms.
Expiry and Eviction
Any key can have a TTL (SET session:abc ... EX 3600, or EXPIRE later). Redis removes expired keys in two ways: lazily, when a client touches an expired key, and actively, by sampling keys with TTLs many times a second and deleting the expired ones. Expired keys may linger in memory briefly, but a client will never read one.
When memory reaches maxmemory, the eviction policy decides what happens:
| Policy | Behavior |
|---|---|
noeviction (default) |
Reject writes with an error |
allkeys-lru |
Evict the least recently used key, any key |
allkeys-lfu |
Evict the least frequently used key |
volatile-lru / volatile-lfu |
Same, but only among keys with a TTL |
volatile-ttl |
Evict keys with the nearest expiry first |
allkeys-random / volatile-random |
Evict random keys |
For a pure cache, allkeys-lru or allkeys-lfu is the usual choice. LFU keeps popular items even if they weren't touched in the last few seconds, which suits skewed workloads. For a Redis that also holds data you can't afford to lose (locks, rate-limit counters, queues), use noeviction or a volatile-* policy and keep that data separate from the cache.
Redis's LRU and LFU are approximate: rather than maintain an exact ordering of every key, it samples a handful of keys (5 by default) and evicts the best candidate among them, keeping a small pool of good candidates between rounds. It's close to true LRU at a fraction of the memory cost.
Persistence
Redis offers two persistence mechanisms, which can be combined:
- RDB snapshots: periodically, Redis forks; the child process writes a compact point-in-time snapshot of memory to disk while the parent keeps serving. Thanks to copy-on-write, the fork is cheap at first, but memory can grow toward double under heavy writes during the snapshot. Restarts load the snapshot quickly. You lose everything since the last snapshot on a crash.
- AOF (append-only file): every write command is appended to a log. The
appendfsyncsetting controls durability:always(fsync every write, slow),everysec(the default, so up to about a second of writes can be lost) orno(leave it to the OS). The log is periodically rewritten in the background into a compact form, and modern Redis writes the rewritten base as an RDB snapshot followed by incremental AOF.
Even with AOF, a write is acknowledged before it's replicated, and replication is asynchronous, so Redis on its own isn't a fully durable database in the way Postgres is. That's fine for caches, sessions and counters that can be rebuilt. If you need a Redis-compatible store that's durable across failures, managed options like Amazon MemoryDB write to a distributed transaction log before acknowledging.
A common mistake is treating Redis as the only copy of important data without saying what happens on failure. Either say "this is a cache; on loss we rebuild from Postgres" or say how you make it durable. Interviewers listen for that sentence.
Replication and High Availability
A Redis primary can have any number of replicas. Replication is asynchronous: the primary acknowledges writes immediately and streams them to replicas afterwards. When a replica connects for the first time, the primary sends an RDB snapshot followed by the write stream. After a brief disconnection, a replica resumes from an in-memory replication backlog instead of starting over (partial resync).
Because replication is asynchronous, a primary that fails can lose writes it acknowledged but hadn't yet sent. The WAIT numreplicas timeout command blocks until a write reaches some number of replicas, which narrows the window but doesn't make Redis strongly consistent: a failover can still pick a replica that missed it.
Redis Sentinel provides automatic failover for non-clustered deployments. A few Sentinel processes (usually three) monitor the primary. When enough of them (a configured quorum) agree it's down, they elect a leader among themselves, promote the best replica and reconfigure the others to follow it. Clients ask Sentinel for the current primary's address. Failover typically takes a few seconds to tens of seconds depending on timeouts.
Redis Cluster
One Redis instance is limited by one machine's memory and, because of the single thread, roughly one core's worth of command execution. Redis Cluster shards the keyspace across many primaries.
- The keyspace is divided into 16,384 hash slots. A key's slot is
CRC16(key) mod 16384. - Each primary owns a subset of the slots, and each primary has one or more replicas.
- Clients are cluster-aware: they cache the slot-to-node map and send each command directly to the right node. If the map is stale, the node replies
MOVED <slot> <node>and the client updates its map. During a slot migration, anASKredirect sends the client to the new node for keys that have already moved. - Nodes talk over a cluster bus using gossip. If a majority of primaries agree a primary is unreachable, one of its replicas is promoted automatically.
- Resharding moves slots between nodes online, key by key, so you can add nodes without downtime.
The constraint you must design around: multi-key operations only work when all keys are in the same slot. MGET, SINTER, transactions and Lua scripts across keys in different slots are rejected. Hash tags solve this: only the part of the key inside {...} is hashed, so {user:42}:profile and {user:42}:cart always land in the same slot. Use them deliberately, since putting too much under one tag creates a hot slot.
Redis Cluster doesn't provide strong consistency. Asynchronous replication plus failover means an acknowledged write can be lost, and during a network partition a primary on the minority side keeps accepting writes until its node timeout expires. That's the standard trade for speed.
Capacity math: caching 200 million user profiles at about 1 KB each is about 200 GB of data, plus per-key overhead (often tens of bytes per key, more for small values). With 64 GB nodes kept below about 75% full to leave room for forks and fragmentation, you'd want around 5 primaries, plus a replica for each, so 10 nodes. At roughly 100,000 operations per second per primary, 5 primaries serve on the order of 500,000 operations per second.
Common Patterns
Caching
The most common pattern is cache-aside: the application owns the logic.
- Read:
GET product:123. On a hit, return it. - On a miss, read from the database, then
SET product:123 <json> EX 300. - On a write, update the database, then
DEL product:123so the next read repopulates it.
Deleting rather than updating the cached value on writes avoids a race where two concurrent writers leave the cache holding the older value. A TTL bounds how stale things can get if an invalidation is ever lost. Other variants include write-through (the app writes to cache and database together) and write-behind (the app writes to cache, which is flushed to the database later, faster but riskier).
The failure mode interviewers like is the cache stampede: a hot key expires, and thousands of concurrent requests all miss and hit the database at once. Defenses:
- Request coalescing: one request takes a short lock (
SET lock:product:123 1 NX PX 5000) and rebuilds the value; the others wait briefly or serve the stale value. - Jittered TTLs: add randomness to expirations so keys loaded together don't all expire together.
- Early refresh: refresh hot keys in the background before they expire.
For a full treatment, see distributed caches.
Distributed Locks
A simple lock is one command:
SET lock:order:9001 <random-token> NX PX 30000
NX makes it succeed only if nobody holds the lock, and PX makes it expire so a crashed holder doesn't block everyone forever. To release, delete the key only if it still holds your token, atomically:
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
This is fine for efficiency locks, where an occasional double execution is harmless (avoiding duplicate work). It's not safe for correctness locks: a holder can pause (a long GC, a slow network) past its TTL while another client acquires the lock, and an async failover can lose the lock entirely. The multi-node Redlock algorithm reduces the failover risk but still depends on timing assumptions. When correctness matters, use fencing tokens (a number that increases with each lock grant, checked by the resource being protected) or a consensus-backed lock service like ZooKeeper or etcd. See distributed locks.
Leaderboards
ZINCRBY leaderboard:2026-11 50 "player:42" # add points
ZREVRANGE leaderboard:2026-11 0 9 WITHSCORES # top 10
ZREVRANK leaderboard:2026-11 "player:42" # player's rank (0-based)
All three are O(log N), so a sorted set with tens of millions of players still answers in well under a millisecond. Ties can be broken by encoding a timestamp into the score. For the full design, including sharding a global leaderboard, see leaderboards.
Queues: Pub/Sub vs Streams vs Lists
- Pub/Sub delivers each message to the subscribers connected right now. If nobody's listening, the message is gone, and a slow subscriber can be disconnected. Good for live fan-out like typing indicators and chat delivery between servers, where the source of truth is elsewhere.
- Lists with
LPUSHandBRPOPmake a simple work queue. Moving an item to a processing list withLMOVE(orBLMOVE) lets you recover items a crashed worker took. - Streams are an append-only log with IDs, consumer groups, per-message acknowledgement (
XACK) and a pending list, so unacknowledged messages can be reclaimed (XAUTOCLAIM) by another consumer. That's much like a small Kafka topic inside Redis. Streams can be capped by length (XADD ... MAXLEN ~ 1000000).
For high-volume, durable, replayable event pipelines, Kafka is still the better tool. Streams fit moderate volumes where you already run Redis.
Counting and Presence
- Counters:
INCR/HINCRBYhandle very high rates, and periodic flushes to the database give durability. For extremely hot counters, shard them across several keys and sum on read. - Unique counts:
PFADD views:video:7 <user_id>andPFCOUNTfor approximate unique viewers. - Daily active users:
SETBIT dau:2026-11-29 <user_id> 1andBITCOUNT. One bit per user, so 100 million users is about 12.5 MB per day. - Presence:
SET online:<user_id> 1 EX 60, refreshed by heartbeats. Presence is a key that exists while the user is around. See presence services.
Hot Keys and Big Keys
Even in a cluster, each key lives on one primary, so a single extremely popular key (a celebrity profile, a flash-sale item) can saturate one node while others idle. Options:
- Local in-process caching for a few seconds on each app server, which absorbs most reads. Redis 6's client-side caching (tracking) can invalidate those local copies when the key changes.
- Replicate the key under several names (
product:123:0...product:123:9) on different slots and have readers pick one at random. - Read from replicas for hot, read-mostly keys, accepting slight staleness.
Big keys (a hash with millions of fields, a 100 MB string) cause slow commands, uneven memory across nodes and slow migrations. Split them into smaller keys, for example by bucketing a huge set by hash.
Memcached vs Redis
Memcached is the other classic in-memory cache. It's older and deliberately simpler.
| Memcached | Redis | |
|---|---|---|
| Data model | Opaque string values only | Strings, hashes, lists, sets, sorted sets, streams, geo, HLL... |
| Threading | Multithreaded | Single-threaded execution (I/O threads optional) |
| Max value | 1 MB by default (configurable) | 512 MB per string |
| Persistence | None | RDB snapshots and AOF |
| Replication / HA | None built in | Replicas, Sentinel, Cluster |
| Sharding | Client-side (consistent hashing in the client library) | Redis Cluster, or client-side |
| Eviction | LRU within slab classes | Configurable LRU, LFU, TTL, random |
| Memory management | Slab allocator, predictable, little fragmentation | General allocator, can fragment |
| Extras | None | Lua scripting, transactions, pub/sub, TTL per key |
Memcached's strengths are simplicity and multithreading: one large Memcached server uses all its cores for plain get/set traffic, and its slab allocator gives very predictable memory use. Very large companies have run enormous Memcached fleets as look-aside caches in front of their databases. Its weakness is everything beyond get/set: no data structures, no persistence, no replication, so losing a node simply means cache misses until it warms up again.
In an interview, the practical answer is usually Redis: it does everything Memcached does for caching, plus the data structures you'll want for counters, rate limits, leaderboards and locks, plus replication for availability. Choose Memcached if the requirement is purely a huge, simple, multithreaded object cache and you want the simplest possible thing.
Redis in an Interview
When to Use It
- Caching database reads, computed results, rendered fragments and API responses.
- Fast counters and rate limiting: atomic
INCRand scripts make these simple and correct. - Leaderboards and rankings with sorted sets.
- Ephemeral state with TTLs: sessions, OTP codes, presence, seat holds, idempotency keys.
- Lightweight coordination: efficiency locks, deduplication sets, short work queues.
- Geo lookups for moving objects like drivers and couriers.
- Real-time fan-out with pub/sub between servers holding WebSocket connections.
Knowing Its Limitations
- Memory-bound. Data must fit in RAM across the cluster, which gets expensive at terabyte scale.
- Not strongly consistent or fully durable. Async replication means acknowledged writes can be lost on failover. Keep a source of truth elsewhere for anything important.
- One thread per instance. Slow commands block everything, and one instance's throughput is bounded; scale by sharding.
- Cluster restricts multi-key operations to keys in the same slot.
- Hot keys don't spread across nodes on their own.
- Locks aren't safe for correctness without fencing tokens.
Questions You Might Get
- "What happens when the cache node dies?" With a replica, failover in seconds and a small window of lost writes. Without one, the keys on that node become misses and load shifts to the database, so size the database (or use request coalescing) to survive that.
- "How do you keep the cache consistent with the database?" Cache-aside with delete-on-write plus TTLs, or CDC from the database that invalidates keys, and accept a short window of staleness.
- "How do you handle a celebrity key?" Local caching, key replication across slots, or replica reads.
- "Is a Redis lock safe?" For avoiding duplicate work, yes. For correctness, add fencing tokens or use a consensus-based lock service.
- "Why not Memcached?" You need data structures, TTL-based patterns and replication; Memcached is a fine choice only for a plain object cache.
Summary
Redis is an in-memory data structure server whose single-threaded execution makes every command atomic and whose structures (strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, geo, streams) turn common problems into one or two commands. Expiry and eviction policies make it a natural cache and a home for ephemeral state. RDB and AOF persistence and asynchronous replication with Sentinel give it reasonable durability and availability, and Redis Cluster spreads data across 16,384 hash slots on many primaries.
In an interview, use Redis for caching, counters, rate limiting, leaderboards, sessions, presence and light coordination, and be explicit about its limits: data in memory, async replication that can lose writes, single-slot multi-key operations, and locks that need fencing for correctness. Pick it over Memcached unless all you need is the simplest possible multithreaded object cache.