Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 42 ยท Practice and Review

Redis Interview Questions

30 common Redis interview questions with concise answers: single-threaded speed, data types, persistence, eviction, replication, cluster, locks and pitfalls.

Redis interviews rarely ask you to recite command names. They ask whether you understand why Redis behaves the way it does: why it is fast, what it loses when the server crashes, what happens when memory runs out, and which pattern fits which problem. This page collects 30 questions that come up again and again, with short and accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you cannot explain an idea in two or three sentences, follow the link to the lesson and review it. Two questions come with a runnable example. Redis itself cannot run on this site, so those examples are small JavaScript stand-ins that model the idea; real redis-cli snippets are read-only.

In an interview, a short correct answer plus one trade-off beats a long recital. "It is fast because the data lives in memory, but that also means capacity is limited by RAM" shows more understanding than a list of features.

Fundamentals

1. What is Redis and what is it used for?

Redis is an in-memory data structure server. Clients send commands over TCP, and Redis stores keys that hold strings, lists, hashes, sets, sorted sets, streams and other structures. Typical uses are caching, sessions, counters and rate limiting, leaderboards, queues, pub/sub messaging and short-lived locks. It can also persist data to disk, so it is sometimes used as a primary store for small, hot datasets. See What Is Redis?.

2. Why is Redis so fast?

Several reasons add up. Data lives in RAM, so there is no disk read on the normal path. Commands run on one thread in an event loop, so there are no locks or context switches between commands. The data structures (hash tables, skip lists, compact encodings) are chosen for fast operations on the server. The wire protocol (RESP) is simple to parse. And because clients can pipeline commands, a single connection can drive hundreds of thousands of operations per second. The cost of the speed is that capacity is limited by memory.

3. Is Redis really single-threaded?

Command execution is: one thread runs every command, one after another. Around it, Redis uses other threads and processes for work that should not block commands: background threads close files, sync the append-only file to disk and free large objects lazily, a forked child writes snapshots, and optional I/O threads (the io-threads setting) can read and write sockets in parallel. The rule to remember is that two commands never run at the same time on the same server, which is also why one slow command blocks everybody.

4. How does Redis differ from Memcached?

Memcached is a cache for strings (opaque values) with simple expiry. Redis offers rich data types, atomic operations on them, optional persistence, replication, scripting, transactions, pub/sub and clustering. If you only cache blobs, both work; if you need counters, sets, sorted sets or durability, choose Redis. Memcached's multi-threaded design can use many cores for plain gets and sets on one server, while Redis scales across cores mostly by running several instances or a cluster.

5. How does Redis differ from a relational database?

A relational database stores tables on disk, offers a query language with joins and constraints, and gives ACID transactions with rollback. Redis stores structures in memory and is accessed by key: you design the data around your access patterns, there are no joins or ad hoc queries (unless you add the query engine from Redis Stack), and transactions have no rollback. They complement each other: the database is the source of truth and Redis makes the hot paths fast. See Choosing the Right Data Type.

6. What is RESP?

The REdis Serialization Protocol is the text-based, length-prefixed format clients use to talk to the server. A command is sent as an array of bulk strings, and replies use simple strings, errors, integers, bulk strings and arrays (RESP3 adds more types such as maps and booleans). It is simple to implement and to parse, which is one reason Redis has a client for almost every language. See Installing Redis and Using redis-cli.

7. What does "atomic" mean for Redis commands, and how do you get atomicity across several commands?

Each command runs to completion without another command interleaving, so INCR, LPUSH or ZADD can never be seen half done. To make a group of commands atomic you can use MULTI/EXEC (queued and run back to back), WATCH for optimistic check-and-set, or a Lua script or Redis Function that reads and writes on the server in one step. Try the next example: it shows why a client-side read-modify-write loses updates while INCR does not.

JS Lost update versus atomic INCR

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second half models the server's one-command-at-a-time queue. See Transactions: MULTI, EXEC and WATCH.

Data types and commands

8. Which data types does Redis offer, and when do you use each?

Strings for values, counters and flags. Lists for queues and capped recent-items lists. Hashes for records with fields. Sets for unique members, tags and set algebra. Sorted sets for rankings and anything ordered by a score, including delayed jobs. Streams for an append-only log with consumer groups. Bitmaps and HyperLogLog for compact flags and approximate unique counts, and geospatial indexes for nearby search. Redis Stack and Redis 8 add JSON, search, vectors and probabilistic structures. See Strings and Counters, Sets, Sorted Sets and Streams.

9. How do you choose between a list, a set and a sorted set?

Ask what you need to do with the items. A list keeps insertion order and allows duplicates; it is good for queues and "latest N". A set keeps unique members with fast membership tests and no order. A sorted set keeps unique members ordered by a numeric score and supports range and rank queries, so it fits leaderboards, time-ordered indexes and priority queues. If you need both uniqueness and order, a sorted set is almost always the answer.

10. Should you store an object as a hash or as a JSON string?

A hash lets you read or change one field (HGET, HINCRBY) without moving the whole object, and small hashes are stored compactly. A JSON string is simplest when you always read and write the whole object, and it handles nested data naturally. If you need nested documents with partial updates and queries, the JSON type from Redis Stack or Redis 8 gives you both. A common pitfall is serializing an object with a counter inside it: two clients updating the counter overwrite each other, whereas HINCRBY is atomic.

11. How does a sorted set work internally?

Large sorted sets use two structures together: a skip list ordered by score (for range and rank queries in O(log N)) and a hash table from member to score (for O(1) ZSCORE). Small sorted sets use a compact listpack encoding to save memory and switch to the skip list above configured size limits. That combination is why ZADD, ZRANK and ZRANGE are all fast. See Sorted Sets.

12. Why should you avoid KEYS in production, and what do you use instead?

KEYS pattern walks the entire keyspace in one command, so on a large database it blocks the single command thread for as long as that takes. Use SCAN instead: it returns a small batch and a cursor, you call it again with the cursor until it returns 0, and the server stays responsive. SCAN may return a key more than once and may miss keys that were added or removed during the iteration, so your code must tolerate duplicates. See Keys, Expiry and TTL.

13. What is the difference between DEL and UNLINK?

DEL frees the memory of the key in the command thread, which is slow for a huge list, hash or set. UNLINK removes the key from the keyspace immediately and lets a background thread free its memory, so the command returns fast. For big collections prefer UNLINK.

14. What is HyperLogLog, and what are its trade-offs?

A probabilistic structure that estimates the number of distinct items (for example unique visitors) using a fixed amount of memory (about 12 KB per key) no matter how many items you add. The standard error is about 0.81 percent. You can add items (PFADD), read the estimate (PFCOUNT) and merge several counters (PFMERGE), but you cannot list the items or remove one. Use it when an approximate count is enough.

Memory, expiry and persistence

15. How does key expiry work?

You set a time to live with EXPIRE, PEXPIRE or the EX/PX options of SET. Redis removes expired keys in two ways: lazily, when a command touches a key whose time has passed, and actively, with a background cycle that samples keys that have a TTL several times per second and deletes the expired ones. So an expired key may briefly still use memory, but you will never read it. A plain SET clears the TTL unless you pass KEEPTTL.

16. What happens when Redis runs out of memory?

It depends on maxmemory and maxmemory-policy. Without maxmemory, Redis keeps growing until the operating system steps in (swap, or the out-of-memory killer). With maxmemory set, the policy decides: noeviction (the default) rejects commands that need more memory with an OOM error, while allkeys-lru, allkeys-lfu, allkeys-random, volatile-lru, volatile-lfu, volatile-random and volatile-ttl evict keys to make room. For a pure cache use an allkeys-* policy; for a store that must not lose data keep noeviction and monitor memory. See Memory Limits and Eviction.

17. How does Redis implement LRU eviction?

It does not keep a strict LRU list, which would cost memory and time. It uses an approximation: when it must evict, it samples a few random keys (maxmemory-samples, 5 by default) and removes the best candidate among them, for example the least recently used one. Raising the sample size makes the choice closer to true LRU at the cost of CPU. LFU works the same way but compares an access-frequency counter instead of the idle time.

18. What are RDB and AOF, and how do they differ?

RDB writes a compact point-in-time snapshot of the dataset to disk, either on a schedule (save rules) or on demand (BGSAVE). It gives small files and fast restarts, but you lose everything written since the last snapshot. AOF (append-only file) logs every write command and replays the log on startup; it loses much less data but the file is larger and restarts are slower, and Redis periodically rewrites it to keep it small. Many production setups enable both: AOF for durability, RDB for backups. See Persistence: RDB and AOF.

19. What do the appendfsync options mean?

appendfsync controls when the AOF is flushed to disk. always syncs after every write: safest and slowest. everysec (the default) syncs once per second, so a crash loses at most about one second of writes. no leaves flushing to the operating system, which is fastest and may lose more. Most deployments use everysec.

20. Why does Redis fork to save, and what does it cost?

BGSAVE and AOF rewrites fork a child process. The child sees a frozen copy of memory (copy-on-write) and writes it to disk while the parent keeps serving clients. Every page the parent modifies during that time is copied, so memory use can grow noticeably on write-heavy servers (in the worst case close to double), and the fork itself can pause the server briefly on a big dataset. That is why you leave memory headroom and set vm.overcommit_memory = 1 on Linux.

21. Is Redis durable? Can it lose data?

Yes, it can lose data. With no persistence a restart loses everything. With RDB you can lose the writes since the last snapshot, with AOF everysec up to about a second of writes, and with always almost nothing at a large speed cost. Replication is asynchronous by default, so a failover can drop writes the replica had not received yet. If you cannot lose any write, treat Redis as a cache or a best-effort store and keep your source of truth in a durable database.

Replication, high availability and scaling

22. How does replication work?

A replica connects to a primary (REPLICAOF host port), receives a full copy (an RDB snapshot plus the writes that happened meanwhile) and then a continuous stream of write commands. After a short disconnect it asks for a partial resync from the replication backlog; if the backlog no longer holds what it missed, it does a full resync. Replication is asynchronous, so replicas can lag and reads from them can be stale; WAIT can block until a number of replicas acknowledge, but it does not make the system strongly consistent. See Replication.

23. What does Sentinel do?

Sentinel is a set of monitor processes (use at least three) that watch a primary and its replicas, agree by quorum that the primary is down, elect one Sentinel to run the failover, promote a replica, reconfigure the others and tell clients the new address. Clients ask Sentinel for the current primary instead of hardcoding it. Sentinel gives high availability but not sharding: the whole dataset still has to fit on one primary. See High Availability with Sentinel.

24. How does Redis Cluster shard data?

The keyspace is split into 16,384 hash slots. A key's slot is CRC16(key) mod 16384, and each primary owns a range of slots. A client that sends a command to the wrong node gets a MOVED redirect (or ASK while a slot is migrating) and good clients cache the slot map. If a key contains a hash tag such as {user:1000}, only the text inside the braces is hashed, so related keys can share a slot. Run the example to compute slots like the server does.

JS Hash slots and hash tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The stand-in implements the same CRC16 and tag rule as Redis Cluster; the key foo lands in slot 12182 on a real cluster too. See Redis Cluster and Sharding.

25. What are the main limitations of Redis Cluster?

Multi-key commands, transactions and Lua scripts only work when all their keys are in the same slot, otherwise you get a CROSSSLOT error. Only database 0 exists. Replication is asynchronous, so a failover can lose recent writes, and a partitioned minority of nodes stops accepting writes. Clients must be cluster-aware. Design keys with hash tags where you need multi-key operations, and avoid creating one giant hot slot.

Three ways to grow

Replication Copies for reads and safety.
Sentinel Automatic failover for one primary.
Cluster Data split over many primaries.

Replication copies, Sentinel heals, Cluster shards.

1 / 2

Patterns and pitfalls

26. What is a cache stampede and how do you prevent it?

When a popular cached item expires, many requests miss at the same moment and all hit the database to rebuild it. Defences: take a short lock so only one request rebuilds while others wait or serve stale data, add random jitter to TTLs so keys do not expire together, refresh early before the TTL ends, and cache "not found" results briefly (negative caching). See Cache Invalidation and Stampedes.

27. How do you implement a distributed lock with Redis, and is it safe?

Acquire with a single command: SET lock:name <random-token> NX PX 30000 (only if absent, with an expiry so a crashed owner cannot hold it forever). Release only if the value is still your token, in one atomic step with a short Lua script: otherwise you might delete someone else's lock after yours expired. This is good for efficiency locks (avoid duplicate work). It is not a guarantee of mutual exclusion: a paused process, a long garbage collection or a failover can let two holders overlap. For correctness-critical work add a fencing token checked by the resource, or use a system built for consensus.

TEXT
SET lock:report 6c1f2a NX PX 30000
EVAL "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" 1 lock:report 6c1f2a
28. What is the difference between MULTI/EXEC, WATCH and Lua scripts?

MULTI/EXEC queues commands and runs them uninterrupted, but you cannot branch on a reply inside it and there is no rollback: a command that fails at run time does not undo the others. WATCH adds optimistic locking: if a watched key changes before EXEC, the transaction is skipped and you retry. A Lua script (or Function) runs read, decide and write as one atomic unit on the server with no retries, which suits contended keys. Keep scripts short, because they block every other client while they run.

29. Pub/Sub or Streams: which one do you pick?

Pub/Sub is fire-and-forget: a message goes to the subscribers connected right now and is gone, so a disconnected subscriber misses it (at-most-once delivery). It suits live notifications and cache-invalidation signals. Streams keep an append-only log with IDs, let consumers read from any point, and with consumer groups track acknowledgements (XACK) and pending entries, giving at-least-once processing. Use streams when messages must not be lost or processed twice by the same group. See Pipelining and Pub/Sub and Streams.

30. What are big keys and hot keys, and why are they a problem?

A big key is one value that is huge, such as a list with millions of items. Commands that read or delete it (LRANGE 0 -1, HGETALL, DEL) take long on the single command thread and block everyone, and replicating or snapshotting it is slow. Split it into smaller keys and use SCAN-style iteration and UNLINK. A hot key is a key that receives a disproportionate share of traffic, which can saturate one core or one cluster node. Spread it with several copies (key suffixes), cache it in the application, or shard the data. redis-cli --bigkeys, SLOWLOG and MEMORY USAGE help you find both. See Performance and Latency.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Redis runs commands on a single thread. Which statement is accurate?

    Command execution is serial, which makes each command atomic and also makes slow commands such as KEYS harmful. Background threads and processes handle persistence and lazy freeing.
  2. 2. You need a lock that a crashed owner cannot hold forever. Which command acquires it?

    SET with NX and PX tests, writes and sets an expiry in one atomic command. The token lets only the owner release it.
  3. 3. Which persistence setup loses at most about one second of writes after a crash?

    With everysec the AOF is synced once per second. RDB can lose everything since the last snapshot.
  4. 4. In Redis Cluster, which formula picks the slot of a key without a hash tag?

    Clusters have 16,384 hash slots and a key maps to CRC16(key) mod 16384. With a hash tag only the text inside the braces is hashed.

Summary

  • Redis is fast because data is in memory, commands run serially without locks, and structures are tuned; the price is RAM capacity and that a slow command blocks everyone.
  • Know the data types and when to use each, and prefer SCAN over KEYS and UNLINK over DEL for big values.
  • Expiry is lazy plus active; eviction is policy-driven and approximate; noeviction is the default.
  • RDB gives snapshots, AOF gives a write log, and nothing in Redis is durable unless you configure it so.
  • Replication is asynchronous, Sentinel adds failover, Cluster shards 16,384 slots by CRC16.
  • Locks, transactions and queues each have well-known traps: tokens for locks, no rollback in transactions, streams instead of Pub/Sub when delivery matters.

Last, keep a one-page reference nearby: the Redis Cheat Sheet.