Redis Interview Questions and Answers
Last updated 2026-11-19
Redis is the default answer to caching, rate limiting, leaderboards and session storage in backend interviews, so the questions go beyond "what is Redis". Expect data-structure choices, persistence trade-offs, eviction, cache stampede and distributed locks. The commands below are valid redis-cli syntax.
For the surrounding theory see caching interview questions, and for how Redis fits among stores see NoSQL questions. Design rounds often use it too; the plan is in how to crack a system design interview.
| Model | In-memory data structure store |
|---|---|
| Persistence | RDB snapshots, AOF log, or both |
| Scaling | Replication, Sentinel, Cluster with 16384 hash slots |
Choosing the right structure
Most Redis answers become easy once you pick the structure. A string holds a value or a counter. A hash holds an object. A list is a queue or a recent-items feed. A set holds unique members and supports intersections. A sorted set orders members by score and is the right tool for leaderboards and delayed jobs. A stream is an append-only log with consumer groups.
Things that lose marks
- Claiming Redis is entirely single-threaded. Command execution is single-threaded, while newer versions use extra threads for network I/O.
- Using KEYS on a production dataset instead of SCAN.
- Describing MULTI/EXEC as having rollback. It queues commands and runs them atomically but does not undo earlier commands if a later one errors at runtime.
- Setting no TTL or eviction policy on a cache.
Redis Interview Questions and Answers: questions with worked answers
1 What is Redis and why is it fast?
easyRedis is an in-memory key-value store with rich data structures, optional persistence and replication. It is fast because data lives in RAM, operations use efficient structures with O(1) or O(log n) cost, command execution is single-threaded so there is no lock contention, and an event loop with I/O multiplexing serves many clients. A single instance commonly handles hundreds of thousands of simple operations per second, though throughput depends on hardware, pipelining and value size.
2 List the main Redis data types and one use for each.
easyString: counters and cached values. Hash: user profile fields. List: job queue or activity feed. Set: unique visitors and tag membership. Sorted set: leaderboards and scheduled tasks by timestamp. Bitmap: daily active flags per user id. HyperLogLog: approximate distinct counts using about 12 KB. Stream: durable event log with consumer groups. Geo: nearby-places queries, built on a sorted set.
3 Build a leaderboard with Redis commands.
mediumA sorted set keeps members ordered by score, with O(log n) insertion. ZADD sets or updates a score, ZINCRBY adds to it, ZREVRANGE with scores lists the top players and ZREVRANK returns a player's zero-based position from the top.
textZADD board 1500 asha ZADD board 1720 ravi ZINCRBY board 100 asha # asha now 1600 ZREVRANGE board 0 2 WITHSCORES # top 3 ZREVRANK board asha # 1 (second place)4 RDB versus AOF persistence: what are the trade-offs?
mediumRDB writes point-in-time snapshots at intervals: compact files, fast restarts, but you can lose the writes since the last snapshot. AOF appends every write command to a log, with fsync policies of always, every second or never; it loses at most about a second of data with everysec but produces larger files and slower restarts, mitigated by background rewrite. Many deployments enable both: RDB for backups and AOF for durability. If Redis is purely a cache, you can disable persistence.
5 What eviction policies does Redis offer?
mediumWhen memory reaches maxmemory, the policy decides what to remove. noeviction rejects writes. allkeys-lru and allkeys-lfu evict among all keys by least recently or least frequently used; volatile-lru, volatile-lfu, volatile-ttl and volatile-random consider only keys with a TTL; allkeys-random evicts at random. LRU and LFU are approximated by sampling keys. For a pure cache, allkeys-lru or allkeys-lfu is the usual choice.
6 Explain the cache-aside pattern and its race conditions.
mediumThe application reads the cache first; on a miss it reads the database, stores the result in the cache with a TTL and returns it. On writes it updates the database and then deletes the cache entry. A race exists: a slow reader fetches an old row, a writer updates and deletes the key, then the reader stores the stale value. TTLs bound how long staleness lasts. See caching questions for write-through and write-back.
pythondef get_user(uid): key = f"user:{uid}" cached = r.get(key) if cached: return json.loads(cached) user = db.fetch_user(uid) r.set(key, json.dumps(user), ex=300) # 5 minute TTL return user7 What is a cache stampede and how do you prevent it?
hardWhen a hot key expires, many requests miss at once and all hit the database. Mitigations: take a short-lived lock so only one request rebuilds the value while others wait or serve stale data; add random jitter to TTLs so keys do not expire together; refresh popular keys early in the background; and cache negative results briefly to stop repeated misses for non-existent keys.
8 How do you implement a distributed lock in Redis?
hardAcquire with a single atomic command that sets a unique token only if the key does not exist, with an expiry: SET lock:job42 token123 NX PX 30000. Release only if the stored value still equals your token, using a Lua script so check and delete are atomic. The expiry prevents a crashed holder from locking forever, but if work outlasts the TTL two clients can hold it, so use fencing tokens for correctness-critical work. On one instance this is advisory; Redlock across several nodes is debated for safety-critical use.
textSET lock:job42 token123 NX PX 30000 -- release (Lua): if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end9 Implement a fixed-window rate limiter with Redis.
mediumUse INCR on a key that includes the client and the time window, and set an expiry on first use. If the count exceeds the limit, reject. The fixed window allows bursts at window edges, up to twice the limit across a boundary; a sliding window log with a sorted set or a token bucket in Lua smooths this.
pythondef allow(client, limit=100, window=60): key = f"rl:{client}:{int(time.time()) // window}" count = r.incr(key) if count == 1: r.expire(key, window) return count <= limit10 What do MULTI, EXEC and WATCH do?
mediumMULTI starts queuing commands and EXEC runs them as one atomic, isolated block with no other client commands interleaved. Redis does not roll back: syntax errors abort the whole block, but a runtime error in one command leaves the others applied. WATCH key marks keys for optimistic locking: if a watched key changes before EXEC, the transaction is aborted and returns nil, so the client retries. Lua scripts are the other way to get atomic multi-step logic.
11 Explain Redis replication, Sentinel and Cluster.
mediumReplication is asynchronous: a replica copies the master, so a failover can lose recent writes. Sentinel monitors masters, performs automatic failover by majority agreement and tells clients the new master address; it does not shard. Redis Cluster shards data across masters using 16384 hash slots, where a key's slot is CRC16(key) mod 16384, each master owns a range of slots and has replicas. Multi-key commands need all keys in one slot, which you force with hash tags such as {user42}:cart.
12 KEYS versus SCAN, and what is a big key problem?
mediumKEYS pattern walks the entire keyspace in one blocking call, which stalls a single-threaded server on large datasets. SCAN iterates in small batches with a cursor and does not block, though it may return a key more than once. Big keys, such as a list with millions of elements, make DEL, replication and rehashing slow; use UNLINK for background deletion and split large collections into buckets.
13 How does pub/sub differ from streams?
mediumPub/sub is fire-and-forget: subscribers receive messages published while they are connected, and nothing is stored, so offline consumers miss messages. Streams are an append-only log with IDs, retained until trimmed, supporting consumer groups where each message is delivered to one consumer in the group, with acknowledgements and the ability to claim pending messages. Use pub/sub for ephemeral notifications and streams for reliable processing, as covered in message queue questions.
Frequently asked questions
Is Redis single-threaded?
Command execution runs on one main thread. Since version 6, optional I/O threads handle reading and writing sockets, and background threads handle tasks such as lazy freeing.
Can Redis be the primary database?
It can, with AOF and replication, but memory cost and durability limits make it more common as a cache, session store or secondary store.
What is the difference between Redis and Memcached?
Redis offers rich data structures, persistence, replication and scripting. Memcached is a simpler multithreaded string cache.
How big can a Redis value be?
A string can be up to 512 MB, but values of that size are a bad idea; keep values small for latency.
Related guides
More in CS Fundamentals Interview Questions
- REST API Interview Questions and Answers
- Routing Protocols Interview Questions: RIP, OSPF, BGP and Shortest Path Examples
- SDLC and Agile Interview Questions
- Shell Scripting Interview Questions with Bash Examples
- SOLID Principles Interview Questions with Examples
- System Design Interview Questions for Freshers
- System Design Interview Questions with Worked Designs
- TCP vs UDP Interview Questions with Socket Code and Numericals
- TCP/IP Interview Questions: Handshake, Congestion Control and Numericals
- Transactions and ACID Interview Questions
- What Happens When You Type a URL in the Browser: The Complete Answer
- Abstraction and Encapsulation Interview Questions