Redis interviews should test whether candidates can match a data structure to a workload and explain its behavior when traffic spikes, timeouts occur or a primary fails. A good answer separates what one Redis command guarantees from what a client or downstream service must do to protect correctness.
These 120 Redis interview questions move from strings, hashes, lists, sets and expiration to caching strategies, streams, atomic updates, persistence, clustering and incident diagnosis. The examples use Redis Open Source concepts unless noted; check which commands and modes your deployment and client support.
How can you tell whether a candidate can reason through a real Redis incident?
Give them one hot shard, a slow origin and a counter that may already have been incremented. Ask which evidence they would gather before retrying. In remote interviews, Sherlock AI can help reviewers examine evidence of possible AI-assisted cheating, deepfakes, impersonation or other unauthorized assistance alongside the candidate’s technical reasoning.
Redis Interview Questions
Start with the level that matches the role. For infrastructure and backend roles, follow definitions with scenarios about retries, memory pressure and consistency.
Redis Interview Questions for Beginners
Start with commands, data structures, caching and the Redis deployment model.
What is Redis?
How does Redis differ from a relational database?
Why is Redis often fast?
Is Redis completely single-threaded?
What is a Redis key?
When should you use a Redis string?
When should you use a Redis hash?
When should you use a Redis list?
When should you use a Redis set?
When should you use a Redis sorted set?
How is a Redis stream different from a list?
What do GET and SET do?
How does INCR work on a Redis key?
What is the difference between MGET and multiple GET calls?
What does a key’s TTL represent?
How do EXPIRE and PERSIST differ?
What are active and passive expiration?
What is the difference between expiration and eviction?
What does SET NX do?
What is the difference between DEL and UNLINK?
Why is KEYS risky on a busy Redis server?
How does SCAN work?
How does Redis Pub/Sub work?
What does Redis persistence mean?
What is an RDB snapshot?
What is the Redis append-only file?
What is Redis replication?
What does Redis Sentinel do?
What is Redis Cluster?
What is Redis pipelining?
What is a Redis transaction?
What does WATCH do in Redis?
What is cache-aside with Redis?
What is a Redis cache hit ratio?
What does maxmemory control?
How can TTLs protect a cache from stale data?
Why is using Redis logical databases not the same as isolation?
What is HyperLogLog useful for in Redis?
How are bitmaps represented in Redis?
How can you inspect the type and size of a Redis key?
Redis Interview Questions for Intermediate
Explore conditional updates, memory policy, streams, clustering and client behavior.
How do you choose an eviction policy for a Redis cache?
How do Redis LRU and LFU differ?
What happens under the noeviction policy?
What is TTL jitter and when is it useful?
How does negative caching work in Redis?
When should you use a pipeline, a transaction or a script?
How do you handle a Redis WATCH conflict?
Can Redis roll back a command error inside EXEC?
How do Lua scripts achieve atomicity in Redis?
How do Redis Functions differ from Lua scripts invoked with EVALSHA?
How do you implement a fixed-window Redis rate limiter?
How is a sliding-window rate limiter different?
How do you choose keys for a multi-key operation in Redis Cluster?
What are MOVED and ASK replies?
How do you choose between Redis Streams and Pub/Sub?
What is a Redis Streams consumer group?
What is a stream’s pending entries list?
What do XACK and XAUTOCLAIM do?
How do you make a Redis Streams consumer idempotent?
How should you trim a Redis stream?
What is the difference between blocking and nonblocking stream reads?
How does a sorted set support pagination?
How should you scan a Redis Cluster?
How do you interpret Redis memory fragmentation?
How do large keys affect Redis performance?
What is a hot key in Redis?
How do snapshots and AOF rewrites affect memory?
What is the difference between full and partial replication resynchronization?
How do you assess Redis replica lag?
What does the Redis WAIT command guarantee?
How do you select client timeouts for Redis?
How do Redis connection pools help?
What do Redis ACLs protect?
What is RESP in Redis?
How can sorted sets and hashes model a leaderboard?
How do you impose consistent lifetime on several Redis keys?
How should you design Redis keys for a cache schema migration?
How do you distinguish Redis latency from application latency?
When does write-through caching make sense?
What does Redis keyspace notification delivery guarantee?
Redis Interview Questions for Experienced
Test operational judgment with workload design, correctness guarantees and recovery scenarios.
How would you prevent a cache stampede on a hot Redis key?
How do you prevent a stale refill after cache invalidation?
When should a service avoid falling back to its database on every cache failure?
How do you distinguish a hot key from a hot shard caused by skewed key layout?
How would you split a write-hot counter without losing the ability to read totals?
How do you estimate Redis memory before deploying a new workload?
How do you handle Redis eviction when data cannot be recomputed?
How would you plan a capacity increase in Redis Cluster?
What happens during a Redis Cluster network partition?
How do Sentinel quorum and majority differ?
How would you rehearse a Redis failover?
When should a Redis replica serve application reads?
How do RPO and RTO shape Redis persistence choices?
How would you handle a Redis restore that loses recent writes?
How do you troubleshoot a sudden p99 latency jump in Redis?
How does Redis SLOWLOG differ from end-to-end latency monitoring?
What would you check when Redis memory grows despite stable key count?
How do you clean up millions of obsolete Redis keys safely?
How do you avoid retrying unsafe Redis writes after a timeout?
Why is SET NX PX not sufficient for every distributed lock?
What is a fencing token and what must enforce it?
How would you handle a worker crash between stream processing and acknowledgment?
How would you handle growing Redis Streams consumer lag?
How do you preserve ordering in a parallel stream consumer design?
When should you choose an external durable broker rather than Redis Streams?
How would you design a multi-region Redis cache?
How would you rotate Redis credentials without causing an outage?
How would you enforce workload isolation in a shared Redis environment?
What should a Redis production dashboard include?
How do you bench-test a proposed Redis optimization?
How do you manage Redis during a mass cache warmup?
How would you design Redis session storage across deployments?
What risks should you consider with Redis-backed rate limiting across an outage?
How would you test correctness for a Redis-backed reservation system?
How do you roll out a new Redis server-side function safely?
How do you decide whether a Redis command is safe for a request path?
How do you avoid false positives when detecting Redis hot keys?
How would you migrate a stateful Redis deployment with minimal downtime?
How would you investigate an unexpected drop in Redis cache hit rate?
What would you ask a senior candidate to diagnose in a Redis incident?
Redis Interview Questions and Answers
The answers connect Redis behavior to concrete engineering decisions. Use the examples to discuss why a choice works and what can still go wrong in a real deployment.
Redis Interview Questions and Answers for Beginners
Review the basic behavior of each structure and command, including the assumptions behind simple examples.
1. What is Redis?
Redis is a networked data store that exposes operations on structures such as strings, hashes, sets, sorted sets and streams. It normally serves active data from memory and can be used as a cache or as a data store with deliberately chosen durability settings.
For example, a storefront can cache product cards while maintaining a separate sorted set for its daily leaderboard. The two keys need different lifetimes and recovery plans even though both use the same Redis deployment.
2. How does Redis differ from a relational database?
Redis operations address keys and structures; relational databases typically offer joins, constraints and richer queries over rows. Redis is a useful choice when the access path is known and the required operation maps directly to a command.
Store page counters in Redis if the application retrieves a counter by page ID. Keep authoritative orders in a database that enforces uniqueness and supports reconciliation across orders, payments and refunds.
3. Why is Redis often fast?
Memory-resident operations and efficient data structures avoid disk access on the usual read path. Actual latency still includes network transit, command complexity, payload size, server contention and work such as persistence.
A small GET near the application may be quick, but reading a huge sorted-set range across regions can still be slow. Compare representative payloads and measure end-to-end percentiles instead of quoting one benchmark.
4. Is Redis completely single-threaded?
Many ordinary commands execute on a main thread per server process, which simplifies command ordering. Background work and some I/O may use other threads or processes, depending on the Redis version and configuration.
The main-thread model explains why one expensive synchronous operation can delay unrelated requests. It does not mean CPU usage across every Redis thread or child process is capped at a single core.
5. What is a Redis key?
A key is the binary-safe name used to locate a value. Applications usually adopt a human-readable namespace and a stable identifier so teams can reason about ownership and lifetime.
A key such as catalog:v2:product:482 distinguishes schema versions and resource type. Use a migration plan for old namespaces, and avoid exposing email addresses or other sensitive values in names that may appear in operational tooling.
6. When should you use a Redis string?
Use a string for one byte sequence or a value that should support string commands such as GET, SET or INCR. It can hold serialized data, but Redis does not query arbitrary JSON fields stored in an ordinary string.
A JSON-encoded profile works when reads and writes use the entire document. For independent field updates, consider a hash or a dedicated document feature if it is installed and appropriate.
7. When should you use a Redis hash?
A hash stores named field-value pairs under one key. It is a good fit when callers frequently retrieve or change a few fields without replacing the whole record.
A profile cache can update display_name independently from locale. Keep records bounded and distinguish whole-key expiry from version-dependent per-field expiration; the semantics are not interchangeable.
8. When should you use a Redis list?
Use a list for ordered elements when push and pop at the ends are central. Unlike a set, a list preserves duplicate entries and insertion order.
LPUSH plus RPOP can form a FIFO queue. But removing a job before an external write succeeds can lose it on worker failure; use an explicit processing-list pattern or streams when recovery matters.
9. When should you use a Redis set?
Use a set for unique members, fast membership checks and operations such as intersections. A plain set does not promise a useful ordering.
A promotion service can store eligible account IDs and test a single shopper with SISMEMBER. Do not use SMEMBERS for a multi-million-member set on a request path just to answer one membership test.
10. When should you use a Redis sorted set?
Use a sorted set when each unique member has a numeric score and requests need rank or score ranges. Updating a member score changes its position without building a full sort on each read.
A leaderboard can increment a player’s score and fetch just the top ten. Define a tie-breaking rule explicitly; equal scores use member ordering rather than an implicit latest-winner rule.
11. How is a Redis stream different from a list?
A stream records entries with IDs, supports reading ranges, and offers consumer-group delivery state. A list is useful for position-based pushes and pops but has no equivalent built-in history or per-group tracking.
A stream can let a billing processor and an audit processor advance independently. A single destructive list pop would consume a job for whoever got there first, so it would not meet that independent-reader requirement.
12. What do GET and SET do?
GET retrieves a string value, returning a nil response when the key is missing. SET writes a string and supports options such as conditional creation and expiration; writing over an existing key normally replaces its prior expiry unless instructed otherwise.
A session publisher can set the value and its lifetime in one command. Splitting the write and expiration into separate calls leaves a failure window where the session exists without the intended expiry.
13. How does INCR work on a Redis key?
INCR atomically adds one to a string holding an integer. A missing key starts from zero; a present value must be a valid integer within the command’s supported range.
Concurrent requests can increase a page-view count without a client-side read-modify-write race. That does not deduplicate a retry after an ambiguous network failure, so exact business counting may require an event identity.
14. What is the difference between MGET and multiple GET calls?
MGET retrieves several string keys in one command and preserves requested order. Multiple GET calls can be pipelined, but separate commands are not one atomic operation.
Batching a small group of related product cache keys reduces round trips. In Redis Cluster, a multi-key command generally requires keys in the same hash slot; a cluster client may use separate commands to cover many slots.
15. What does a key’s TTL represent?
TTL is the key’s remaining lifetime in seconds; PTTL reports milliseconds. For current Redis, minus one means the key exists without expiry and minus two means the key does not exist.
When a session unexpectedly survives, a TTL of minus one suggests the expiration was missing or cleared by a replacement write. A key near zero does not mean an application should rely on millisecond-exact expiry events.
16. How do EXPIRE and PERSIST differ?
EXPIRE assigns a timeout to an existing key. PERSIST removes the key’s timeout without deleting its value. Both report whether the requested state change occurred.
If a short-lived draft becomes a durable catalog entry, decide whether the cache key should become permanent or be replaced by a separate namespace. Do not assume calling EXPIRE can create a key that is already gone.
17. What are active and passive expiration?
Redis can discover expired keys upon access and also runs active expiry work to remove keys that are not being accessed. A key’s logical availability and the instant its memory is reclaimed are different details.
A traffic pattern can expire many sessions together while eviction pressure remains high for a period. Add expiry jitter where exact deadlines are not required, and observe memory and latency rather than assuming instantaneous physical reclamation.
18. What is the difference between expiration and eviction?
Expiration is driven by a key’s assigned lifetime. Eviction removes eligible keys when the server reaches its configured memory policy threshold, even if their TTL has time remaining.
A product card can remain logically fresh for one hour yet disappear earlier under allkeys-lru. The application should treat cache misses as normal and track evicted_keys separately from expired_keys to diagnose why misses rose.
19. What does SET NX do?
SET with NX succeeds only if the target key does not already exist. Combining it with EX or PX can create a short-lived marker as a single atomic command.
A worker can record a temporary duplicate-suppression marker. If that marker is used as an ownership lease, uniqueness at creation is only the first step; expiry, safe release and downstream stale-writer handling matter too.
20. What is the difference between DEL and UNLINK?
Both remove a key from the keyspace. UNLINK schedules most reclamation work for background processing, which can reduce main-thread blocking when removing complex values.
Removing a giant abandoned set with DEL can create a latency spike. UNLINK helps with reclamation cost, but memory may remain in use briefly; rate-limit a large cleanup and observe background work.
21. Why is KEYS risky on a busy Redis server?
KEYS scans the keyspace to produce matching names, and large scans can block other command execution. It is better suited to small, controlled environments than large production request paths.
An operator looking for a namespace should use incremental SCAN with conservative batches or an application-maintained index. Incremental scanning still consumes resources, so per-iteration size and throttling matter.
22. How does SCAN work?
SCAN iterates with an opaque cursor until it returns zero. COUNT is a hint, not a guaranteed page size, and a changing keyspace can cause duplicates or uncertain visibility for keys that were added or removed during iteration.
A maintenance worker should tolerate empty batches and repeated names. It can make updates idempotent by key rather than assuming every page contains ten new items or taking an individual call as a complete scan.
23. How does Redis Pub/Sub work?
Publishers send messages to channels and connected subscribers receive matching publications. Ordinary Pub/Sub does not retain messages for offline subscribers or provide acknowledged replay.
Use it for best-effort notifications such as telling a live dashboard to refresh. For a job that must survive a consumer restart, store a durable event or use a stream with a recovery plan instead.
24. What does Redis persistence mean?
Persistence writes Redis state or write history to disk so data may be recovered after restart. The choice of snapshots, append-only files and synchronization policy sets the durability and performance trade-off.
A disposable cache may intentionally have no persistence. A store for pending jobs should document how much data it can lose, rehearse restore, and distinguish a recent backup from asynchronous replicas.
25. What is an RDB snapshot?
An RDB snapshot captures a point-in-time Redis dataset. It is useful for compact backups and restarts, but writes after the last retained snapshot may not reappear on restore.
With hourly snapshots, a failure near the end of the hour can lose nearly that hour’s writes if no more recent source exists. Choose the interval based on the actual business loss tolerance.
26. What is the Redis append-only file?
AOF persists a representation of write activity and replays it to reconstruct dataset state. Synchronization settings govern when data is flushed to disk, and rewrites keep the files from growing indefinitely.
If the deployment syncs every second under normal conditions, a process or system failure can still lose recent data. Measure disk behavior and test the configured recovery point rather than describing AOF as zero-loss.
27. What is Redis replication?
Replication sends a primary’s updates to replicas, normally asynchronously. Replicas can help high availability and, where appropriate, serve reads that tolerate lag.
A catalog read can accept a slightly old copy. A read after a user changes a password or authorization state should be designed against stale results rather than assigned to any replica for convenience.
28. What does Redis Sentinel do?
Sentinel monitors Redis instances, supports failover of a primary, and helps clients discover the currently elected primary. Sentinel manages high availability for a primary-replica deployment rather than sharding keys across a cluster.
Use a Sentinel-aware client to rediscover the primary after failover. Pointing every client permanently at the original host can leave them connected to a replica even while the service is recovering correctly.
29. What is Redis Cluster?
Redis Cluster partitions keys across hash slots assigned to primaries and can use replicas for failover. A cluster-aware client routes commands and handles redirection rather than treating every node as a complete copy of the database.
Separate account keys may live on different nodes, raising total capacity. A single hot account key still lives on just one shard, so adding nodes cannot split its command load automatically.
30. What is Redis pipelining?
Pipelining sends multiple commands before waiting for each response. It reduces network round trips but does not make the commands a transaction or guarantee that they all succeed together.
Batch 100 independent counter reads to reduce network wait. A client that sends unbounded pipelines can increase response buffering, so pick a batch size from representative throughput and latency tests.
31. What is a Redis transaction?
MULTI queues commands and EXEC runs the queued sequence without serving other clients’ commands in the middle of that sequence. It does not provide SQL-style rollback for runtime command errors.
If one queued command targets the wrong data type, its result can be an error while another command succeeds. The client must inspect each EXEC result and the design should validate preconditions before changing critical state.
32. What does WATCH do in Redis?
WATCH makes EXEC conditional on the watched keys not having changed since the watch began. It supports optimistic compare-and-set logic, provided the client watches and executes on the same connection.
If two workers update the same record, one transaction may abort and need to recompute from fresh data. Use bounded retries and prefer a single native atomic command when it expresses the same update.
33. What is cache-aside with Redis?
In cache-aside, the application reads Redis first, fetches the authoritative store on a miss, and then caches the result. It typically also invalidates or updates the cache after writes.
A product details endpoint can cache expensive fetches for a few minutes. If the database version changes while a miss is filling, consider version-aware writes or a short TTL to limit how long a stale refill survives.
34. What is a Redis cache hit ratio?
It measures the share of relevant cache lookups that find a usable result. Redis INFO includes keyspace hit and miss counters, but application-level hit rates may differ because clients also make non-cache lookups.
A high aggregate ratio can hide a poor result for the most expensive endpoint. Break down latency, misses and fallback database load by workload before changing TTL or increasing memory.
35. What does maxmemory control?
maxmemory configures the threshold Redis uses for its memory policy. It is not a hard cap on the entire operating-system process footprint, which can also include allocator overhead, buffers and persistence-related effects.
If a container has an 8 GiB limit, a maxmemory value of 8 GiB leaves no room for process overhead. Measure resident memory during expected load and background operations, then reserve headroom.
36. How can TTLs protect a cache from stale data?
A TTL limits how long a cached entry can remain available without refresh. It is a backstop, not a guarantee of immediately reflecting a fresh authoritative write.
A five-minute TTL may be reasonable for a product description. Inventory available to promise can require a stronger invalidation or source-of-truth check because correctness is not defined by the cache’s wall-clock timer.
37. Why is using Redis logical databases not the same as isolation?
Numbered databases separate namespaces on deployments that support them, not CPU, memory, persistence or service availability. Redis Cluster supports only database zero.
Placing sessions in database 1 and a large cache in database 2 does not keep one workload from consuming shared capacity. Use separate instances or deployments when reliability, resource budgets or trust boundaries differ.
38. What is HyperLogLog useful for in Redis?
HyperLogLog approximates the count of distinct observed items without storing an exact set of those items. Use it when a small estimation error is acceptable and member enumeration is unnecessary.
It can estimate unique daily visitors economically. Use a set or a durable event store when the application must name every visitor or use the exact count to calculate a payment.
39. How are bitmaps represented in Redis?
Redis bitmap commands manipulate bits in an underlying string. A bitmap works well when the application can map items to compact offsets and wants to perform flag checks or bitwise aggregation.
Marking consecutive day indexes in a bitmap can capture attendance for one user. Mapping arbitrary huge IDs to offsets can allocate an unnecessarily large sparse string, so use an index or a different data structure.
40. How can you inspect the type and size of a Redis key?
Use TYPE for the data type and the relevant size command, such as STRLEN, HLEN or ZCARD, to learn its logical size. MEMORY USAGE estimates memory associated with the key and value.
A hash with few fields can still hold large values. Compare item count and actual bytes, sample safely, and avoid returning the full value from a large production key merely to estimate its footprint.
Redis Interview Questions and Answers for Intermediate
Review implementation trade-offs and what to verify before relying on a Redis primitive in production.
41. How do you choose an eviction policy for a Redis cache?
Start with the workload’s reuse pattern and whether all keys are disposable. Compare allkeys policies with policies restricted to expiring keys, then evaluate hit ratio and origin load under a representative trace.
A catalog cache with frequently re-read popular entries might favor approximate LFU. A volatile policy has no eligible candidates if keys lack TTLs, so verify expiry coverage or Redis can reject memory-growing writes.
42. How do Redis LRU and LFU differ?
LRU favors recently accessed keys; LFU estimates access frequency with decay so historic popularity does not dominate forever. Redis approximates eviction selection rather than maintaining a perfect global ranking.
A short burst of one-off reads may displace frequently used keys under recency, while frequency can preserve them. Compare policies during a genuine workload shift because frequency may also adapt more slowly.
43. What happens under the noeviction policy?
Redis does not remove existing keys simply to admit more data. It can reject commands that grow memory past the policy threshold; existing data can still generally be read and operations that free space can proceed.
A queue or session store may prefer visible write failure to silently evicting required state. Alert early, handle rejected writes explicitly, and leave working headroom rather than discovering the capacity limit through dropped jobs.
44. What is TTL jitter and when is it useful?
TTL jitter adds a bounded random offset to expiration times to avoid having many unrelated entries expire together. It helps spread origin requests and redistributions of cache load.
If 100,000 products are warmed at deployment, avoid giving all of them exactly 600 seconds of life. Add a small offset unless an exact deadline is required; security or contractual expiry should not be stretched casually.
45. How does negative caching work in Redis?
Negative caching stores a short-lived indication that an authoritative lookup returned no result. It saves repeated expensive misses, but the absence marker must remain distinguishable from a temporary backend failure.
Cache a confirmed missing product for a few seconds if callers repeatedly ask for it. Do not cache a database timeout as not found, and clear or supersede the marker when the product is created.
46. When should you use a pipeline, a transaction or a script?
A pipeline reduces round trips for independent commands, a transaction isolates a queued sequence, and a script can perform bounded server-side decisions using values it reads. Pick based on the property required, not on whichever tool is most powerful.
Read many unrelated values with a pipeline. To conditionally consume a token and record a result atomically, use a suitable native command or bounded script with known key scope and carefully validated inputs.
47. How do you handle a Redis WATCH conflict?
Treat an aborted EXEC as a failed comparison, not as a completed update. Re-read state and recompute under a new watch session, with a bounded retry policy and backoff if contention is meaningful.
If many requests compete on one inventory record, repeated optimistic retries can waste capacity. A single operation implementing the invariant, or a redesign moving authoritative allocation elsewhere, may be more predictable.
48. Can Redis roll back a command error inside EXEC?
No. A runtime error in one queued command does not roll back earlier successful commands or prevent every later command from executing. Syntax or queue-time errors can make the whole transaction abort before execution.
If a hash write targets a string, the transaction can still successfully increment a separate counter. Validate expected key types and values, and examine each result rather than relying only on the transport request’s success.
49. How do Lua scripts achieve atomicity in Redis?
A Redis script runs without interleaving other ordinary commands on the executing server, so it can read and update related key state together. That isolation is not rollback if the script has already issued writes before an error.
Validate types and inputs before changes, then keep the script’s work bounded. Walking a huge collection in Lua makes a logically atomic operation but can push unrelated traffic past its latency budget.
50. How do Redis Functions differ from Lua scripts invoked with EVALSHA?
Functions are installed named server-side libraries and form a managed deployment artifact. EVALSHA invokes cached script code by hash, so a client must handle a missing cache and reload as appropriate.
A team can version and deploy a shared function alongside clients. For ad hoc scripting, use the client’s supported script registration and fallback path, and test restart, replica promotion and each target shard.
51. How do you implement a fixed-window Redis rate limiter?
Map each identity and time window to a counter and update it atomically. Set expiry as part of the same logical operation so that a process failure cannot leave an unintended permanent counter.
A one-minute window is simple but allows bursts around the boundary, potentially close to twice the per-window limit in a short period. Use a rolling or token approach when that behavior is unacceptable.
52. How is a sliding-window rate limiter different?
A sliding window evaluates activity over the preceding interval relative to now rather than fixed clock buckets. A sorted set can evict old request IDs and count current ones atomically, at a memory and CPU cost.
Use unique members even when two requests share a timestamp, and bound stored entries and cleanup work. For very high traffic, an approximate rolling counter or token bucket may meet the same goal with less state.
53. How do you choose keys for a multi-key operation in Redis Cluster?
Use the same intentional hash tag when related keys must live in one slot and participate in a multi-key command or server-side operation. Do not tag unrelated traffic into the same slot by default.
Keys such as cart:{42}:items and cart:{42}:version can be located together. Tagging every cart with {all_carts} makes cluster routing simpler at the expense of concentrating capacity on one shard.
54. What are MOVED and ASK replies?
MOVED points a cluster client at the node currently responsible for the slot and can prompt a routing refresh. ASK is a temporary redirect during migration and requires handling appropriate to the next redirected command.
Use a cluster-aware client rather than caching an initial node address indefinitely. Observe redirect rates during resharding, and verify that retry behavior does not repeat non-idempotent operations after some other ambiguous failure.
55. How do you choose between Redis Streams and Pub/Sub?
Choose Streams for retained entries, cursor-based replay and optional consumer-group tracking. Use Pub/Sub for best-effort delivery when only currently connected subscribers need the update.
A visual presence indicator may tolerate a missed signal because it can refresh. A task that must update a billing record needs durable processing, retention, failure recovery and deduplication beyond ordinary Pub/Sub.
56. What is a Redis Streams consumer group?
A consumer group tracks progress and pending deliveries for a stream while distributing new entries among its consumers. Different groups can process the same stream independently.
Several workers may share a payments group, while an analytics group has its own position. Acknowledgment by an analytics worker does not acknowledge the message on behalf of payments.
57. What is a stream’s pending entries list?
The pending entries list tracks entries delivered to a group consumer but not yet acknowledged. It reveals ownership and idle time, supporting recovery when workers leave work incomplete.
If a consumer dies after reading an event, the entry may stay pending rather than being delivered as new to another worker. Monitor pending age and design a claim process that distinguishes slow healthy work from abandoned work.
58. What do XACK and XAUTOCLAIM do?
XACK acknowledges processing for a particular group, removing the entry from that group’s pending state. XAUTOCLAIM transfers eligible idle pending entries to a consumer for possible recovery.
A reclaimer can take pending jobs older than a chosen threshold, then run the same idempotent handler. An acknowledgment alone does not generally remove the original stream entry; retention is a separate decision.
59. How do you make a Redis Streams consumer idempotent?
Record a stable event identifier at the durable destination, ideally in the same transaction as the business effect. Acknowledge only after committing or proving that the effect has already been applied.
A worker can crash just after committing an invoice. On redelivery, a destination uniqueness constraint on event ID prevents a second invoice, and the worker can acknowledge the already-applied entry safely.
60. How should you trim a Redis stream?
Choose a length or age-based retention policy that accounts for the slowest required consumer and business replay window. Approximate trimming can be cheaper but does not impose an exact instantaneous boundary.
If a consumer is down for six hours, a one-hour stream history can make recovery impossible from Redis alone. Monitor group lag and oldest recoverable entry and archive events elsewhere if the audit window is longer.
61. What is the difference between blocking and nonblocking stream reads?
Blocking reads can wait for work up to a chosen timeout; nonblocking reads return promptly when no data is available. A blocking command occupies a client connection even though it does not block the Redis server’s main command loop.
Use a dedicated or appropriate pooled connection for a blocking worker rather than sharing it with latency-sensitive traffic. Choose a finite wait when workers need to check shutdown or readiness regularly.
62. How does a sorted set support pagination?
For stable paging, choose an ordering and a continuation boundary that includes a unique tie-breaker when scores repeat. Offset-based paging can be expensive at large offsets and unstable when updates change ranks.
A leaderboard may use rank pages for a live snapshot. For an event index with many equal timestamps, use a design that remembers both score and member or reads an immutable range, so a tie does not skip entries.
63. How should you scan a Redis Cluster?
A SCAN generally operates on the node processing the request, not as one global cluster snapshot. Use a cluster-aware process that visits relevant primaries and can tolerate duplicates or movement.
For a namespace migration, scan each primary at a controlled rate and make each change idempotent. Reconcile against an authoritative index if the operation needs proof of complete coverage during resharding.
64. How do you interpret Redis memory fragmentation?
Compare memory reported by Redis with its resident set and allocator metrics over time. A high ratio can come from allocator fragmentation, a small used-memory denominator or retained memory; a ratio alone does not diagnose the cause.
After deleting a large namespace, used memory may drop faster than RSS. Review fragmentation bytes, workload history and background persistence before enabling additional reclamation work or restarting the process.
65. How do large keys affect Redis performance?
A large key can make operations slow, create large responses, add replication and migration work, and be expensive to delete. Item count matters, but byte size and the command’s access pattern matter too.
A hash with an enormous field value can hurt an HGET even if HLEN is small. Break values into independently accessed units or move large artifacts to object storage and cache only references or small projections.
66. What is a hot key in Redis?
A hot key receives disproportionate traffic, saturating the shard that owns it before cluster averages look busy. It is a request concentration problem and can occur even when the value itself is tiny.
If every home-page request reads one feature flag, a local short-lived cache can absorb demand when staleness is acceptable. For write-hot counters, consider sharded counters and accept the cost and semantics of aggregation.
67. How do snapshots and AOF rewrites affect memory?
Persistence work may fork a process, and writes during the child’s lifetime can copy modified memory pages. The memory required depends on write activity, dataset size and duration, not just stored bytes.
A heavily written shard can hit a container limit during a rewrite even when normal memory looks stable. Reserve headroom, observe copy-on-write metrics and avoid creating synchronized heavy rewrite bursts across instances.
68. What is the difference between full and partial replication resynchronization?
A partial resynchronization sends changes missed within available replication history. If the replica’s offset or replication history cannot be matched, a full synchronization transfers a fresh dataset representation before catching up.
An undersized backlog can make brief network interruptions trigger large transfers repeatedly. Size it for realistic write rate and interruption duration, and monitor full resync frequency and resource impact.
69. How do you assess Redis replica lag?
Compare replication offsets and link health, then use application-level probes if you need to measure how quickly a tagged write becomes visible. Offset divergence and time lag are related but not interchangeable.
A burst of large writes can create significant byte lag. If a feature reads its own writes, route those reads to the primary or use a deliberately bounded consistency mechanism rather than hoping replicas are close enough.
70. What does the Redis WAIT command guarantee?
WAIT asks for acknowledgment from a requested number of replicas for preceding writes on the connection, within a time limit. It reports how many acknowledged; it is not a guarantee of disk durability or linearizable failover.
A client that requires two acknowledgments must check the returned count. Even if two replicas acknowledge, evaluate failover selection and durability requirements before depending on Redis as an authoritative financial ledger.
71. How do you select client timeouts for Redis?
Set connection and operation deadlines inside the application’s overall latency budget, and classify failures that occurred before sending versus ambiguous failures after sending. Use a bounded retry policy and understand client library behavior.
If a 200 ms request can tolerate only 40 ms for cache lookup, an aggressive reconnect loop can consume all remaining budget. Return a controlled fallback when Redis is optional and avoid repeating business writes blindly.
72. How do Redis connection pools help?
Pools reuse connections and can limit how many sockets the application creates. They introduce their own queueing and must support special cases such as blocking commands or watched transactions requiring a reserved connection.
If the Redis runtime looks healthy while requests wait for a pool slot, inspect client pool size, connection lifetimes and timeout reasons. Creating many more connections may just move pressure to Redis memory and networking.
73. What do Redis ACLs protect?
ACLs restrict users to approved command categories or commands and can scope access to keys and channels. They complement authentication and transport protection rather than replacing network segmentation or TLS.
A cache reader can be allowed to GET from one namespace without allowing configuration or deletion commands. Validate both allowed and denied calls against a staging deployment, including commands hidden behind client abstractions.
74. What is RESP in Redis?
RESP is the wire protocol Redis uses to encode commands and replies. RESP versions differ in supported reply types and behavior; client libraries typically negotiate or configure the protocol and translate those responses into language types.
A redis-cli nil or error response is not a literal string value. When upgrading a client or enabling RESP3, test places that rely on the exact shape of maps, sets, nulls or push messages.
75. How can sorted sets and hashes model a leaderboard?
Use the sorted set for scores and ranks and a separate hash or durable store for display metadata. Decide how to reconcile the two structures and define time windows, ties and deletion behavior explicitly.
A top-ten request can retrieve ten member IDs, then batch-load the labels. If a player profile disappears, report or substitute a label instead of accidentally changing the recorded ranking.
76. How do you impose consistent lifetime on several Redis keys?
Prefer one structure when it naturally owns the values under a single TTL. If several keys must be updated together, use coordinated expiry and atomic updates where feasible, while tolerating eviction and partial presence in readers.
A session could store small related fields in one hash with a whole-key expiration. If additional keys are needed, check whether the application can reconstruct or reject a partially present session rather than trusting independent expiries.
77. How should you design Redis keys for a cache schema migration?
Version namespaces and support a controlled migration, with compatible readers, selective warming or safe lazy population. Set expiration on old keys and observe metrics while switching traffic.
A deployment can introduce catalog:v3 while leaving v2 available for rollback. Avoid a mass key rename or flush during peak traffic; gradually retire old keys once no callers depend on them.
78. How do you distinguish Redis latency from application latency?
Time the client’s pool wait, network and server round trip separately where possible, then compare with command timing on the server. A quiet server slow log does not prove that clients see low latency.
If requests cluster near a predictable timeout while slow log is empty, inspect connection acquisition, routing, packet loss or response size. A large server execution time instead points to command or workload characteristics.
79. When does write-through caching make sense?
Write-through updates the cache as part of the write path, which can reduce misses immediately after writes. Decide how failures between the authoritative store and cache are handled, because they do not form one atomic transaction by default.
A profile service can commit to its database first and then republish the cached projection. If the cache update fails, an outbox or invalidation event can repair it; do not claim success depends on independent writes magically agreeing.
80. What does Redis keyspace notification delivery guarantee?
Keyspace notifications use Pub/Sub semantics when enabled, so disconnected consumers can miss them. Expiry notifications are tied to deletion processing rather than a precise business deadline.
Use notifications to help invalidate an optional local cache. For a required renewal or billing action, persist a deadline in an authoritative scheduler or database and reconcile missed work explicitly.
Redis Interview Questions and Answers for Experienced
Review failure modes and mitigation choices with attention to evidence and the source of truth.
81. How would you prevent a cache stampede on a hot Redis key?
Combine bounded request coalescing, randomized expiry and a fallback policy tied to the origin’s capacity. When policy allows, serve a recently stale value while one worker refreshes it.
An expired popular product page should not cause thousands of simultaneous database queries. Limit refresh concurrency, use a short hard deadline and expose coalescing and origin saturation, so a failed leader does not stall everyone.
82. How do you prevent a stale refill after cache invalidation?
A fetch begun before a database update may write an old value after invalidation. Prevent it using versioned values or conditional cache fills, or accept bounded staleness with a short lifetime and explicit consistency requirements.
If the authoritative profile moves from version 7 to 8, reject a late fill for version 7 once the cache knows about version 8. Test a reordered read, write and invalidation rather than only sequential success tests.
83. When should a service avoid falling back to its database on every cache failure?
Unlimited fallback can turn a cache outage into a database outage. Establish an origin request budget, shed or degrade noncritical traffic, and restore cache capacity or warm it progressively.
If Redis serves most storefront reads, sending all traffic straight to the warehouse can overwhelm it. Protect essential endpoints with bounded fallback, and use stale or simplified responses where product requirements allow.
84. How do you distinguish a hot key from a hot shard caused by skewed key layout?
Correlate operations and latency by shard with sampled key traffic, slot distribution, and persistence or network signals. One dominant key needs a different fix from many unrelated keys tagged or placed together.
If thousands of keys share a custom tag, redesign slot placement for future traffic. If one key receives most reads, a local cache or semantic key split is more useful than just redistributing other slot ranges.
85. How would you split a write-hot counter without losing the ability to read totals?
Shard increments across deterministic subkeys and aggregate reads across those subkeys, making explicit whether the total must be current and consistent. Retain a durable event stream when exact totals matter.
A site can sum 16 counters for an approximate live view and compute final daily totals from events. If callers require atomic global threshold enforcement, splitting the counter breaks that invariant unless another coordinator enforces it.
86. How do you estimate Redis memory before deploying a new workload?
Use realistic key lengths, value distributions, access patterns and expiry behavior on representative data. Account for structure overhead, fragmentation, client and replication buffers, peak copy-on-write and safety margin.
Estimate the expected steady-state key count, populate a sample and compare actual memory to the estimate. Repeat under writes and persistence work, because a static value-size estimate can hide peak RSS risk.
87. How do you handle Redis eviction when data cannot be recomputed?
Do not run required data under an eviction policy that assumes disposable values. Choose isolation, explicit refusal or backpressure when full, appropriate durability and a tested authoritative recovery path.
Separate ephemeral product caches from job coordination or session state if they have different loss budgets. A prefix cannot isolate eviction pressure by itself, and sharing an instance also couples memory and outage risk.
88. How would you plan a capacity increase in Redis Cluster?
Determine whether the shortage is aggregate memory, throughput, a hot slot or client bottlenecks. Add capacity where it addresses the cause, rebalance conservatively and verify slot coverage and client redirect handling.
During migration, track p99, redirects, per-shard CPU and replication health. Keep migration steps reversible and throttled; moving large values while a replica is catching up can consume the headroom the expansion sought to create.
89. What happens during a Redis Cluster network partition?
Availability depends on which nodes and shard replicas can communicate and satisfy the cluster’s failover and coverage rules. An isolated primary can accept writes briefly before it stops, and accepted writes may be lost when another primary is chosen.
Test your client against loss of quorum and coverage rather than assuming every surviving shard stays writable. Document outage behavior, expected loss and which business operations require a stronger data store.
90. How do Sentinel quorum and majority differ?
Sentinel’s configured quorum is used to establish objective failure detection. A Sentinel leader still needs a majority authorization for failover; these requirements can diverge when some Sentinels are unreachable.
With five Sentinels and quorum two, two agreeing can detect failure, but a failover election needs majority support. Spread Sentinels across genuinely independent failure domains and exercise the actual partition cases.
91. How would you rehearse a Redis failover?
Use a representative environment and measure detection, election, client reconnection, recovery time and observed data loss under real traffic patterns. Check whether clients rediscover the primary and whether in-flight operations have ambiguous outcomes.
Write stable test IDs before and during the failover, then reconcile them against the promoted primary. A successful ping after promotion does not prove no writes were lost or replayed twice.
92. When should a Redis replica serve application reads?
Serve reads from replicas only where the application accepts their potential staleness and understands failover behavior. Writes and read-after-write paths may need the primary or a different consistency mechanism.
A product description can often tolerate temporary lag. Reading a just-revoked entitlement from a replica may be unacceptable, so route that lookup according to its security and correctness contract.
93. How do RPO and RTO shape Redis persistence choices?
Recovery point objective limits acceptable data loss; recovery time objective limits service recovery time. Measure snapshots, AOF settings, replicas and backup restore against both rather than assuming one feature handles every failure.
A replayable cache can rebuild given a slow warmup plan. A stateful system may require stricter synchronization, off-host backups and a measured restore path, and may still need a separate authoritative database.
94. How would you handle a Redis restore that loses recent writes?
Keep clients from building on an unverified restore, find the restored checkpoint, then reconcile missed operations with an authoritative source or replay log before fully reopening writes.
If counters or reservations appeared successful before failure, inspect which durable event IDs are absent. Resume idempotently and avoid treating a Redis restart plus clean health check as proof of business consistency.
95. How do you troubleshoot a sudden p99 latency jump in Redis?
Split the path into application queueing, network, server execution and background effects. Compare slow log entries and latency events with CPU, recent forks, response sizes, evictions and deployment changes.
A slow-log spike around a bulk range operation suggests expensive command execution. A latency spike near fork with few slow commands suggests a different remedy; first find the correlated cause instead of only widening timeouts.
96. How does Redis SLOWLOG differ from end-to-end latency monitoring?
SLOWLOG records server command execution time above configured thresholds, not the full client experience including network I/O and connection waiting. It is evidence about one part of the request path.
If a large response spends time crossing the network, clients may report slow reads without matching SLOWLOG entries. Use both measurements and workload context rather than assuming one can replace the other.
97. What would you check when Redis memory grows despite stable key count?
Inspect sampled value sizes, per-type distribution, memory buffers, allocator statistics and copy-on-write rather than assuming key cardinality explains growth. Stream backlog or expanding values can increase bytes without adding top-level keys.
A growing stream under one key may retain millions of entries. Check retention and consumer lag, then assess whether trimming is safe before changing the maxmemory limit.
98. How do you clean up millions of obsolete Redis keys safely?
Prefer application-managed expirations or a versioned namespace with a controlled retirement. If cleanup requires scanning, use bounded batches, asynchronous deletion when appropriate, and rate limits tied to service health.
A migration worker can scan match patterns and remove old v1 keys gradually while monitoring operation latency and pending lazy frees. Do not flush the database or assume the scan is an exact snapshot under change.
99. How do you avoid retrying unsafe Redis writes after a timeout?
Treat a timeout after transmission as ambiguous: the server may already have executed the command. Use operations with idempotency keys or verify an authoritative result before replaying non-idempotent effects.
A retry of INCR can count one event twice. A durable event ID or bounded same-key deduplication can prevent duplicates, but retain that ID for at least the maximum realistic retry horizon.
100. Why is SET NX PX not sufficient for every distributed lock?
It can grant a time-bounded lease in one Redis instance, but the owner can pause beyond expiry, another owner can acquire it, and failover can affect state. A successful acquisition does not prevent stale writers at the destination.
Use unique owner tokens and release only the matching lease. For strict correctness, use fencing that the downstream resource enforces or a suitable transactional or consensus-backed alternative rather than relying on the lease alone.
101. What is a fencing token and what must enforce it?
A fencing token gives a holder a monotonic ordering value that the protected destination checks against prior accepted values. The check must happen where the effect is applied, not merely inside the process that obtained a lock.
If lease holder 10 stalls and holder 11 writes first, the destination rejects a late write with token 10. The token generator must preserve the ordering guarantees required across failover; an unchecked counter is not enough.
102. How would you handle a worker crash between stream processing and acknowledgment?
Design for redelivery by coupling event deduplication with the durable business effect, then acknowledge after a successful commit. Recover pending entries after an appropriate idle threshold and handle poison messages explicitly.
If the worker crashes after recording an invoice but before XACK, reclaim the event and verify the existing invoice by event ID. Keep retries bounded and route irrecoverable records to a monitored recovery path.
103. How would you handle growing Redis Streams consumer lag?
Separate the backlog of new entries from old pending work, and compare ingest rate, processing rate and error rates. Add consumers only if downstream capacity and any ordering requirements allow the added concurrency.
If backlog grows because a single event repeatedly fails, more workers may not fix it. Inspect pending ownership, age and errors, then manage retries or quarantine according to the business contract and protect retention while investigating.
104. How do you preserve ordering in a parallel stream consumer design?
Streams provide ordered entry IDs within a stream, but several workers can finish out of order. Preserve required order with partitioning by business key, serial processing within each partition, or version checks at the destination.
Updates for one account can be assigned to the same ordered work lane. If global order is mandatory, parallel completion requires explicit coordination and can limit throughput; avoid promising order from a consumer group alone.
105. When should you choose an external durable broker rather than Redis Streams?
Choose based on retention, replay, operational failure tolerance, cross-system consumers and throughput needs. Redis Streams can be appropriate for bounded workflows, but its deployment settings determine what survives failures.
If compliance needs long independent replay and very large retained volume, a broker or dedicated log may fit better. Keep Redis for live coordination and document which system is the source for replay and reconciliation.
106. How would you design a multi-region Redis cache?
Localize caches by region and define which writes or invalidations reach each cache, who is authoritative, and how long staleness is acceptable. Avoid assuming cross-region failover behaves like one local Redis instance.
A regional cache outage can degrade locally rather than flooding another region’s primary. Use versioned invalidations and bounded regional fallback; separate features needing globally consistent state from caches that can rebuild.
107. How would you rotate Redis credentials without causing an outage?
Use supported overlap and staged rollout, deploy the new credentials to clients, verify connections, then retire the old credentials. Test long-lived connections, replicas or Sentinel paths wherever they authenticate differently.
A new application identity can be rolled out to a small group first. Monitor authentication failures and reconnect rates before disabling the old identity, and do not log secret values while diagnosing errors.
108. How would you enforce workload isolation in a shared Redis environment?
Determine which boundaries need capacity isolation and which need security isolation. ACLs and key prefixes can reduce accidental access; separate capacity or deployments are necessary when shared memory, CPU or failure risk is unacceptable.
A reporting worker making large scans should not share a latency-critical session store without an explicit capacity contract. Separate environments can apply different eviction policies, persistence options and network controls.
109. What should a Redis production dashboard include?
Track availability, client latency percentiles, command rate, rejected writes, hit and miss patterns, expirations and evictions, memory headroom, replication state and persistence health according to the workload.
Add application signals such as fallback database load and stream backlog. Alert on a meaningful trend with current impact; raw CPU or total keys alone rarely tells the operator what decision to make.
110. How do you bench-test a proposed Redis optimization?
Match real command mix, payload sizes, pipeline batches, connection counts, key distribution and persistence settings. Compare throughput, tail latency and correctness before and after under both normal and stressed conditions.
A representative test should include skew and fallback, not just random GET and SET on tiny values. Record results by shard and inspect p99 under load rather than selecting the highest throughput number alone.
111. How do you manage Redis during a mass cache warmup?
Rate-limit writes and origin fetches, prioritize high-value keys, spread expiration and stop the warmup when capacity or latency signals cross a threshold. Plan overload behavior before production traffic shifts.
Warm popular product categories first rather than preloading the entire catalog. If the origin slows, slow down warmup instead of competing with user requests, and use progressive rollout to flatten load.
112. How would you design Redis session storage across deployments?
Define session life, invalidation, authorization freshness, loss tolerance and fallback before selecting storage. Keep session state small, avoid sharing a disposable eviction policy with required sessions, and coordinate versioned serialization.
If deployment rolls back, both versions may need to parse existing session values. Test expired, malformed and revoked sessions, then decide which requests must fail closed when Redis is unavailable.
113. What risks should you consider with Redis-backed rate limiting across an outage?
Choose fail-open or fail-closed by route based on business and abuse risk, and bound fallback traffic with local limits or another trusted control. Distributed approximations may temporarily admit more or fewer requests than desired.
A public read can use a local emergency quota, while a high-risk operation can refuse requests temporarily. Make the degraded mode observable so operators know whether availability or strict enforcement was prioritized.
114. How would you test correctness for a Redis-backed reservation system?
Check simultaneous claims, retry after a lost response, lease expiry, process pause and failover. Verify invariants in the authoritative inventory store, not merely in Redis logs or successful API responses.
If a reservation worker pauses and resumes after ownership changes, its stale write must fail at the destination. Use these tests to decide whether Redis is a safe optimization or the design needs stronger storage guarantees.
115. How do you roll out a new Redis server-side function safely?
Treat it like shared production code: version its behavior, validate inputs and key scopes, keep its runtime bounded, and deploy a compatible library before clients require it. Test all target primaries and failover paths.
Introduce a versioned entry point without removing the previous one while old clients are active. Monitor server latency and errors, and roll clients back before retiring a function they still call.
116. How do you decide whether a Redis command is safe for a request path?
Check algorithmic complexity, concrete input and response bounds, frequency, and whether the operation can block main execution. A theoretically efficient command can still consume time returning a large result.
A sorted-set range fetching 20 records behaves differently from a request that fetches millions. Enforce server or application limits and move full scans or bulk export to controlled operational jobs.
117. How do you avoid false positives when detecting Redis hot keys?
Use multiple observations over a representative interval and correlate sampled key telemetry with shard saturation and endpoint behavior. Some tools are policy- or version-dependent and sampling can miss short bursts.
A well-cached feature flag may be busy but harmless. A moderately frequent large response can cause more impact, so track bytes and command cost as well as the number of requests per key.
118. How would you migrate a stateful Redis deployment with minimal downtime?
Define the source of truth, use supported replication or migration tooling, establish a cutover checkpoint and verify data and TTL semantics before moving writers. Prepare rollback and write reconciliation explicitly.
For critical keys, compare sample values, expirations and counts at the target. During cutover, one verified writer path is safer than informal dual writes unless conflicts and retries have a clear resolution rule.
119. How would you investigate an unexpected drop in Redis cache hit rate?
Break down misses by workload and deployment version, then compare key prefix changes, expirations, evictions, shard health and request mix. A lower hit rate can reflect cold starts or a bug rather than insufficient memory.
If misses spike immediately after a schema prefix change with stable eviction counts, check migration and warmup. If evicted keys climb across a steady workload, inspect policy and working set before tuning fixed lifetimes.
120. What would you ask a senior candidate to diagnose in a Redis incident?
Provide application p99, shard metrics, a recent change and one business invariant. Ask for a testable hypothesis, a low-risk mitigation and an explanation of what the chosen evidence cannot prove.
For example, one shard saturated after a leaderboard release while failover exposed duplicate increments. A strong candidate separates hot-key mitigation from retry idempotency and proves both with controlled measurements.
Redis Documentation and Further Reading
Use these official references to verify command semantics, configuration and compatibility for your Redis version and deployment.
Similar Posts
