Interview questions with answers
Redis interview questions and answers
Data structures, caching, persistence, Pub/Sub, Streams and clustering. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1What is Redis and why is it so fast?Asked almost every time
Redis is an in-memory data structure store used as a cache, database, message broker and more. It is fast because data lives in RAM, commands run on a single main thread (no locks), it uses efficient data structures and an event loop with non-blocking I/O, and the protocol is simple. Newer versions add I/O threads for networking.
2Explain the main Redis data types and a use for each.Asked almost every time
Strings (cache values, counters with INCR), Hashes (objects such as a user profile), Lists (queues, recent items), Sets (unique tags, followers), Sorted Sets (leaderboards, rate-limit windows, priority queues), Streams (event logs with consumer groups), Bitmaps and HyperLogLog (flags and approximate unique counts), Geospatial indexes (nearby search), plus JSON and vector types in Redis Stack / Redis 8.
3How does Redis persist data?Asked almost every time
RDB writes point-in-time snapshots at intervals: compact and quick to restart from, but you can lose the last few minutes. AOF logs every write, replayed on restart, with fsync every second as the usual balance; it is rewritten in the background to stay small. Many deployments use both, or none for a pure cache.
4How would you use Redis as a cache, and what are the pitfalls?Asked almost every time
Use cache-aside: read Redis, on a miss load from the database and SET with a TTL; delete the key on writes. Set maxmemory and an eviction policy such as allkeys-lru. Pitfalls: stampedes on hot keys (use locks or early refresh), stale data from missed invalidations, huge keys, and treating the cache as a source of truth.
5How do you prevent cache stampede with Redis?Asked almost every time
When a hot key expires, many requests may rebuild it at once. Prevent it with a short lock (SET lock NX PX) so one request rebuilds while others wait or serve stale data, refresh early before expiry, add random jitter to TTLs, and keep popular keys warm in the background.
6How does Redis replication work?Asked almost every time
Replicas connect to a primary, receive a snapshot, then a stream of write commands. Replication is asynchronous, so a failover can lose the last acknowledged writes; WAIT can require replicas to acknowledge. Replicas serve reads and provide redundancy.
7How would you design a session store with Redis?Asked almost every time
Store sessions as hashes or strings keyed by a random session ID, set a TTL that refreshes on activity, keep only what is needed, use replication or a managed service for availability, and encrypt or sign cookie IDs. Invalidate on logout by deleting the key.
8How do you build a rate limiter with Redis?Very often asked
Fixed window: INCR a key per user and window with EXPIRE. Sliding window: a sorted set of request timestamps, removing old ones with ZREMRANGEBYSCORE and counting with ZCARD. Token bucket: a Lua script that refills and takes a token atomically. Atomicity matters, so use MULTI or Lua.
9Pub/Sub vs. Streams: when do you use each?Very often asked
Pub/Sub is fire-and-forget: only connected subscribers get a message, and nothing is stored. Streams are an append-only log with IDs and consumer groups; messages are stored, can be read later, acknowledged (XACK) and claimed by another consumer if one fails. Use Streams for reliable processing, Pub/Sub for live notifications.
10How do Redis Sentinel and Redis Cluster differ?Very often asked
Sentinel provides high availability for a primary with replicas: it monitors, fails over automatically and tells clients the new primary, but data is not split. Cluster shards data across many primaries using 16,384 hash slots, each primary with replicas, giving horizontal scale and failover. Multi-key operations in Cluster need keys in the same slot (hash tags like {user:1}).
11How do you implement a distributed lock?Very often asked
SET lock:resource <random-token> NX PX 30000 acquires it only if free, with an expiry so a crashed holder does not block forever. Release it with a Lua script that deletes only if the token matches, so you never remove someone else's lock. For safety-critical work, add fencing tokens; Redlock spreads the lock across several nodes but has debated guarantees.
12What are eviction policies?Very often asked
When maxmemory is reached, Redis evicts by policy: noeviction (writes fail), allkeys-lru or allkeys-lfu (evict least recently / frequently used among all keys), volatile-lru/volatile-lfu/volatile-ttl (only keys with a TTL), or random variants. Caches usually use allkeys-lru or allkeys-lfu.
13What are sorted sets and how are they implemented?Very often asked
Members unique with a numeric score, kept ordered. They use a skip list plus a hash table, giving O(log n) inserts and range queries by score or rank (ZRANGE, ZRANK). Small sets use a compact listpack encoding.
14What is Lua scripting or functions in Redis for?Very often asked
Running several commands atomically on the server with EVAL or registered functions: no other command runs in the middle. It is used for rate limiters, compare-and-set logic and lock release checks, while saving network round trips.
15How do you safely release a distributed lock?Very often asked
Store a unique token as the lock value, and release with a Lua script that deletes the key only if the value still matches, so you never delete a lock another client acquired after yours expired.
16What is the single-threaded model and its implications?Very often asked
Commands execute one at a time on a main thread, so each command is atomic, but a slow command (large KEYS, big SMEMBERS, heavy Lua) blocks everyone. Since Redis 6, I/O threads can handle network reads and writes, but command execution remains single-threaded.
17How do Redis Streams consumer groups work?Very often asked
Each group tracks delivered and acknowledged entries. XREADGROUP gives each message to one consumer in the group; pending entries remain until XACK. XAUTOCLAIM reassigns messages left pending by crashed consumers.
18What is the difference between EXPIRE and eviction?Very often asked
Expiration removes a key when its TTL ends (lazily on access and by a periodic sampler). Eviction removes keys when memory hits maxmemory, according to the policy, even if they have no TTL or have not expired.
19How do transactions work in Redis?Often asked
MULTI queues commands and EXEC runs them in order without other clients' commands in between. There is no rollback: if one command fails at runtime, the others still run. WATCH adds optimistic locking: EXEC aborts if a watched key changed. Lua scripts are often simpler for atomic read-modify-write.
20Why is the KEYS command dangerous in production?Often asked
KEYS scans the whole keyspace in one blocking call, freezing the single main thread on large datasets. Use SCAN, which iterates in small batches with a cursor, and design key names so you can find things without scanning.
21How do you find and fix memory problems?Often asked
Use INFO memory and MEMORY USAGE, redis-cli --bigkeys or --memkeys to find large keys, set TTLs, pick compact types (hashes for small objects), avoid unbounded lists and sets, and watch the fragmentation ratio.
22What is pipelining?Often asked
Sending many commands without waiting for each reply, then reading all replies together. It cuts network round trips dramatically for bulk work. Unlike MULTI, it is not atomic; it is purely a network optimisation.
23How do you use Redis for a job queue?Often asked
Use lists with LPUSH and blocking BRPOP for simple queues, BLMOVE to a processing list for reliability, or Streams with consumer groups for acknowledgements and retries. Libraries like BullMQ add scheduling, retries and priorities on top.
24How do you monitor Redis?Often asked
Watch memory use and fragmentation, hit and miss ratio, evicted and expired keys, connected clients, ops per second, latency (LATENCY tools), slow log entries and replication lag. Alert on memory nearing maxmemory and rising evictions.
25What are bitmaps and bitfields used for?Often asked
Compact per-ID flags, such as daily active users by user ID (SETBIT, BITCOUNT) or feature flags. Millions of users fit in a few megabytes, and bitwise operations combine days.
26How does geospatial indexing work in Redis?Often asked
GEOADD stores longitude and latitude as a geohash score in a sorted set; GEOSEARCH finds members within a radius or box. Useful for nearby drivers or stores.
27What is client-side caching in Redis?Often asked
With tracking enabled, the server remembers which keys a client read and sends invalidation messages when they change, so the client can keep a local copy safely and avoid network round trips.
28How does Redis support vector search?Sometimes asked
Redis Stack (and Redis 8 with the query engine) can index vector fields in hashes or JSON documents and run k-nearest-neighbour searches with filters, so it can serve as a vector store or semantic cache for AI apps. Redis 8 also adds a native vector set type.
29What changed with Redis licensing and what is Valkey?Sometimes asked
In 2024 Redis moved from the BSD license to source-available licenses; the Linux Foundation forked the last open version as Valkey. Redis 8 later added AGPL as an option. Many cloud providers offer Valkey as a compatible alternative.
30How do you secure a Redis instance?Sometimes asked
Never expose it to the internet, require authentication with ACL users and least-privilege command rules, enable TLS, rename or disable dangerous commands, and keep it on a private network.
Objective questions 30
1Which data type is best for a leaderboard?Asked almost every time
Why: Sorted sets order members by score with ZADD and ZRANGE.
2Which command sets a key only if it does not exist, with an expiry?Asked almost every time
Why: SET with NX and PX is the standard lock / once-only write.
3Which persistence option logs every write?Asked almost every time
Why: The append-only file replays writes on restart.
4What prevents many requests rebuilding the same expired key?Asked almost every time
Why: This avoids cache stampede.
5Redis replication is by default…Asked almost every time
Why: WAIT can require acknowledgements.
6How do you release a lock safely?Asked almost every time
Why: Avoids deleting someone else's lock.
7Which eviction policy suits a general cache?Very often asked
Why: It evicts the least recently used keys across the whole keyspace.
8What should replace KEYS in production?Very often asked
Why: SCAN iterates incrementally without blocking.
9How many hash slots does Redis Cluster use?Very often asked
Why: Keys map to one of 16,384 slots, spread across primaries.
10What is true of Redis Pub/Sub?Very often asked
Why: Pub/Sub does not persist messages.
11Which command acknowledges a processed stream message?Very often asked
Why: XACK removes it from the consumer group's pending list.
12Which structure backs a sorted set?Very often asked
Why: O(log n) operations.
13Which command runs a Lua script?Very often asked
Why: Scripts run atomically.
14Which command reads as part of a consumer group?Very often asked
Why: Each message goes to one consumer.
15What happens when memory reaches maxmemory?Very often asked
Why: noeviction makes writes fail.
16Why can one slow command hurt everyone?Very often asked
Why: Each command blocks the loop.
17Does a failed command inside MULTI/EXEC roll back the others?Often asked
Why: Other commands still run.
18What does pipelining reduce?Often asked
Why: Many commands share one round trip.
19Which type counts unique visitors approximately in about 12 KB?Often asked
Why: HyperLogLog estimates cardinality with a fixed small size.
20What makes multi-key commands work in Cluster?Often asked
Why: Hash tags like {user:1} put keys in one slot.
21Which command reassigns stale pending stream messages?Often asked
Why: Recovers work from crashed consumers.
22Which commands track daily active users compactly?Often asked
Why: One bit per user.
23Which command finds members within a radius?Often asked
Why: Geo data lives in a sorted set.
24Which blocking command pops from a list?Often asked
Why: Waits until an item arrives.
25Which tool lists slow commands?Often asked
Why: Find commands blocking the server.
26Adding random jitter to TTLs helps avoid…Often asked
Why: Spreads cache rebuilds.
27Which command atomically increments a counter?Sometimes asked
Why: INCR is atomic, so concurrent clients never lose updates.
28Sentinel's main job is…Sometimes asked
Why: Sentinel promotes a replica if the primary fails.
29Valkey is…Sometimes asked
Why: Forked in 2024.
30Which feature restricts users to certain commands?Sometimes asked
Why: Least-privilege access.
Track what you have practised and search every bank in your dashboard.
Start learning