Skip to main content

Redis - Interview Preparation

1. Basic Questions​

Q1: What is Redis and what are its primary use cases?​

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store. It can be used as a database, cache, message broker, and streaming engine.

  • In-Memory: Data is stored in RAM, providing sub-millisecond latency.
  • Data Structures: Supports strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes.
  • Primary Use Cases:
    • Caching: Storing frequently accessed data to reduce DB load.
    • Session Management: Fast access to user session data.
    • Real-time Analytics: High-speed counters and leaderboards.
    • Message Queues: Using Pub/Sub or Streams for communication.
    • Rate Limiting: Efficiently counting requests per user.

Redis is often described as a "data structure server" because it doesn't just store blobs; it understands the structures it holds.

# Setting a key in Redis
SET user:1 "John Doe"
GET user:1

Q2: What are the different data types supported by Redis?​

  • Strings: The most basic type, can store text, serialized objects, or binary data (up to 512MB).
  • Lists: Linked lists of strings. Great for queues (Lpush/Rpop).
  • Sets: Unordered collections of unique strings. Supports intersection, union, and difference.
  • Hashes: Maps between string fields and string values. Ideal for representing objects.
  • Sorted Sets (ZSets): Similar to sets but every member is associated with a score, used to keep the set sorted.
  • Bitmaps: Allows bit-level operations on strings.
  • HyperLogLogs: Probabilistic data structure for estimating cardinality (unique elements) with fixed memory.
  • Streams: Log-like data structure for event sourcing and messaging.
  • Geospatial: Stores longitude/latitude pairs.
# Working with a Hash
HSET user:1 name "Alice" age 30
HGETALL user:1

Q3: Explain the difference between Redis and Memcached.​

While both are in-memory key-value stores:

  • Data Types: Redis supports many data structures (lists, sets, etc.), while Memcached is primarily strings-only.
  • Persistence: Redis can persist data to disk (RDB/AOF); Memcached is volatile.
  • Replication: Redis supports master-slave replication and high availability (Sentinel/Cluster); Memcached is standalone or uses client-side sharding.
  • Memory Management: Redis manages its own memory and uses different eviction policies. Memcached uses a slab allocator to prevent fragmentation.
  • Thread Model: Redis is primarily single-threaded (per process) for command execution. Memcached is multi-threaded.

Q4: How does Redis achieve such high performance?​

  1. In-Memory: Eliminates disk I/O latency.
  2. Efficient Data Structures: Optimized implementations for every type.
  3. Single-Threaded Execution: Avoids the overhead of context switching and lock contention between threads for command execution (Redis 6.0 introduced IO threads for networking, but the core remains single-threaded).
  4. Non-blocking I/O: Uses multiplexing (epoll/kqueue) to handle thousands of concurrent connections efficiently.

Q5: What is "Persistence" in Redis and what are the two main types?​

Persistence allows Redis to save data to disk so it can be restored after a restart.

  • RDB (Redis Database):
    • Takes point-in-time snapshots of the dataset at specified intervals.
    • Compact and fast to restart.
    • Risk of data loss (changes since the last snapshot are lost).
  • AOF (Append Only File):
    • Logs every write operation received by the server.
    • More durable (can sync every second or every write).
    • File size grows large (requires periodic "rewriting").
    • Slower to restart as it must replay the log.

Many production environments use both for a balance of speed and safety.

Q6: What is the purpose of the EXPIRE command?​

The EXPIRE command sets a time-to-live (TTL) for a key. After the specified number of seconds, the key is automatically deleted. This is fundamental for caching strategies and temporary data. You can also use PEXPIRE for milliseconds.

SET session:123 "data"
EXPIRE session:123 3600 # Expires in 1 hour
TTL session:123 # Returns remaining time

Q7: Explain Redis "Replication".​

Replication allows data from one Redis server (the Master) to be exact copies on other servers (the Replicas).

  • Asynchronous: The master doesn't wait for replicas to acknowledge writes.
  • Scalability: Replicas can handle read queries, scaling read throughput.
  • Data Safety: Replicas provide a backup if the master fails.
  • One-way: Data only flows from Master to Replica.
# On the replica server
REPLICATEOF master_host master_port

Q8: What is "Redis Sentinel"?​

Sentinel is the system designed for managing Redis high availability. It performs three main tasks:

  1. Monitoring: Checks if master and replica instances are working as expected.
  2. Notification: Alerts administrators or other systems via an API.
  3. Automatic Failover: If a master fails, Sentinel promotes a replica to be the new master and updates the other replicas and clients.

Q9: What is "Redis Cluster"?​

Redis Cluster is a distributed implementation of Redis that provides:

  • Horizontal Scaling: Data is automatically sharded across multiple nodes.
  • Availability: It continues to operate even if some nodes fail (using a master-replica model within shards).
  • Hash Slots: Redis uses 16384 hash slots. Every key is mapped to a slot, and every node is responsible for a subset of these slots.

Q10: What is a "Transaction" in Redis?​

A Redis transaction is a block of commands that are executed sequentially as a single atomic unit.

  • Keywords: MULTI (starts), EXEC (executes all), DISCARD (cancels).
  • Atomic: No other client's command will be executed in the middle.
  • No Rollback: If one command fails (e.g., syntax error), the others will still execute. Redis transactions are about isolation, not necessarily "all-or-nothing" in the ACID sense if logic errors occur.
MULTI
SET account:1:balance 50
SET account:2:balance 150
EXEC

Q11: What is "Pub/Sub" in Redis?​

Pub/Sub is a messaging pattern where senders (publishers) do not send messages directly to specific receivers (subscribers). Instead, messages are published to "channels".

  • Real-time: Subscribers receive messages immediately as they are published.
  • Fire-and-forget: Redis does not store published messages; if a subscriber is offline, it misses the message.
# Client 1
SUBSCRIBE news_channel
# Client 2
PUBLISH news_channel "Breaking News!"

Q12: How do you handle "Pipelining" in Redis?​

Pipelining is a technique to improve performance by sending multiple commands to the server in a single network request, without waiting for the replies of individual commands. This drastically reduces the overhead of network round-trip time (RTT).

# Python example using redis-py
pipe = r.pipeline()
pipe.set('foo', 'bar')
pipe.get('foo')
pipe.execute() # Sends both at once

Q13: What is "Eviction Policy"?​

When Redis reaches its memory limit (maxmemory), it must decide which keys to remove to make room for new data. This is controlled by the maxmemory-policy. Common policies:

  • noeviction: Returns an error on write.
  • allkeys-lru: Removes the Least Recently Used keys.
  • volatile-lru: Removes LRU keys that have an expiration set.
  • allkeys-random: Removes random keys.
  • allkeys-lfu: Removes the Least Frequently Used keys.

Q14: What is a "Lua Script" in Redis?​

Redis allows you to run Lua scripts directly on the server.

  • Atomicity: The script is executed as a single atomic operation, similar to a transaction but with logic (loops, conditionals).
  • Efficiency: Reduces network round-trips by performing complex logic server-side.
  • Consistency: Ensures that multiple steps are completed without interference.
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey myval

Q15: What are "Sorted Sets" (ZSets) and their use cases?​

Sorted Sets are unique collections of strings where each member is associated with a floating-point score.

  • Sorting: Members are always kept sorted by their score.
  • Use Cases: Leaderboards (gaming), priority queues, time-series data (using timestamp as score).
ZADD leaderboard 100 "user1"
ZADD leaderboard 200 "user2"
ZRANGE leaderboard 0 -1 WITHSCORES # Returns sorted list

Q16: Explain "Bitmaps" in Redis.​

Bitmaps are not a separate data type but a set of bit-oriented operations on the String type. Since strings are binary safe and can be up to 512MB, they can represent up to $2^{32}$ bits.

  • Use Case: Tracking daily active users (each bit represents a user ID). It's extremely memory-efficient.
SETBIT user_activity:2023-10-27 123 1 # User 123 is active
BITCOUNT user_activity:2023-10-27 # Count active users

Q17: What is "HyperLogLog" and when would you use it?​

HyperLogLog is a probabilistic data structure used to estimate the cardinality (the number of unique elements) of a set.

  • Memory: It uses a constant, very small amount of memory (max 12KB) regardless of the number of elements.
  • Accuracy: It has a standard error of 0.81%.
  • Use Case: Counting unique visitors to a website.
PFADD visitors "ip1" "ip2" "ip1"
PFCOUNT visitors # Returns ~2

Q18: How do you secure a Redis instance?​

  1. Password Protection: Use AUTH or requirepass.
  2. Network Isolation: Only bind to internal IP addresses or use a VPC.
  3. Rename Commands: Disable dangerous commands like FLUSHALL, CONFIG, or KEYS by renaming them to empty strings in redis.conf.
  4. TLS/SSL: Use encrypted connections (supported natively in Redis 6.0+).
  5. ACL (Access Control Lists): (Redis 6.0+) Define specific permissions for different users.

Q19: What is the KEYS command and why is it dangerous?​

The KEYS pattern command returns all keys matching a pattern. It is an $O(N)$ operation where $N$ is the total number of keys in the database.

  • Danger: In a production database with millions of keys, it will block the entire server for several seconds, causing a complete outage.
  • Alternative: Use SCAN, which iterates through the keys incrementally without blocking.

Q20: Describe the "SCAN" command.​

SCAN is a cursor-based iterator that allows you to traverse all keys in the database in small, non-blocking steps. It returns a new cursor for the next call. When the cursor returns to 0, the iteration is complete.

SCAN 0 MATCH user:* COUNT 10

Q21: What is "Redis Streams"?​

Introduced in Redis 5.0, Streams is a log-like data structure that allows append-only storage of messages.

  • Consumer Groups: Allows a group of clients to cooperate in consuming different parts of the same stream of messages, providing high-performance message processing similar to Kafka.
  • Persistence: Unlike Pub/Sub, messages are stored in the stream until explicitly deleted.

Q22: Explain "Object Encoding" in Redis.​

Redis automatically chooses the most efficient internal representation for each data structure based on its size.

  • Example: A small Hash might be stored as a ziplist (compact memory), but as it grows, Redis converts it to a hashtable (fast access). This allows Redis to be extremely memory-efficient for small objects.
OBJECT ENCODING mykey

Q23: What is the INFO command?​

The INFO command returns a large amount of statistics and information about the current Redis server state: version, uptime, memory usage, connected clients, replication status, and CPU usage. It's the primary tool for monitoring Redis health.

Q24: How do you delete all data in Redis?​

  • FLUSHDB: Deletes all keys in the current database.
  • FLUSHALL: Deletes all keys in all databases of the current Redis instance. Both are dangerous in production!

Q25: What is the "Redlock" algorithm?​

Redlock is a distributed locking algorithm proposed by the creator of Redis. It aims to provide a safe way to implement locks across multiple independent Redis masters, ensuring that the lock is held even if some nodes fail or become partitioned.

Q26: What is the difference between EXPIRE and PERSIST?​

  • EXPIRE: Sets a time-to-live for a key.
  • PERSIST: Removes the expiration from a key, making it permanent again.

Q27: Describe Redis "Databases".​

By default, Redis has 16 databases (numbered 0 to 15). You can switch between them using the SELECT command. In production, it's generally recommended to use separate Redis instances rather than databases for better isolation and performance management.

Q28: What is a "Client Buffer" in Redis?​

When Redis sends data to a client, it first stores it in a buffer. If a client is too slow to read the data, the buffer can grow, potentially consuming all of the server's memory. Redis allows you to set limits on these buffers and will disconnect clients that exceed them.

Q29: Explain SETNX.​

SETNX stands for "SET if Not eXists". It only sets the key if it doesn't already exist. It returns 1 on success and 0 if the key was already there. This is a classic primitive for implementing distributed locks.

SETNX lock_key "locked"

Q30: What is the purpose of CONFIG SET?​

CONFIG SET allows you to change server configuration parameters at runtime without restarting the server. Not all parameters can be changed this way, but many critical ones like maxmemory or slowlog-log-slower-than can be.

Q31: Explain "Slow Log" in Redis.​

The slow log is a system to log commands that exceed a specified execution time. It only records the execution time (not including network latency). You can inspect it to find problematic queries.

SLOWLOG GET 10

Q32: What is MONITOR command?​

MONITOR is a debugging command that streams back every single command processed by the Redis server in real-time. It has a significant performance impact and should only be used briefly for debugging.

Q33: How do you increment a value in Redis?​

Use INCR for integers or INCRBYFLOAT for decimals. If the key doesn't exist, it is created with a value of 0 before the increment.

INCR counter
INCRBY counter 10

Q34: What is "Redis Geo"?​

Redis provides commands to store longitude and latitude and perform geospatial queries like finding members within a certain radius of a point.

GEOADD locations 13.361389 38.115556 "Palermo"
GEORADIUS locations 15 37 200 km

Q35: Explain MSET and MGET.​

  • MSET: Sets multiple keys to multiple values in a single atomic operation.
  • MGET: Returns the values of all specified keys. These are more efficient than multiple SET or GET calls because they reduce network overhead.

Q36: What is the purpose of WATCH in a transaction?​

WATCH provides "Optimistic Locking" for Redis transactions. You watch one or more keys before starting a MULTI block. If any of the watched keys are modified by another client before you call EXEC, your transaction will fail. This allows you to implement "Check-and-Set" (CAS) logic.

  • DEL: Deletes a key synchronously. If the key holds a massive object (like a million-element list), DEL will block the server until the memory is freed.
  • UNLINK: (Redis 4.0+) Removes the key from the keyspace immediately (making it invisible), but performs the actual memory reclamation in a background thread.

Q38: Explain TYPE vs OBJECT ENCODING.​

  • TYPE: Returns the high-level data type (string, list, etc.).
  • OBJECT ENCODING: Returns the low-level internal representation used by Redis to store that data.

Q39: What is the WAIT command?​

WAIT blocks the current client until all the previous write commands are successfully acknowledged by at least the specified number of replicas. It returns the number of replicas that acknowledged the writes. This can be used to improve the durability of writes.

Q40: What is SWAPDB?​

SWAPDB atomically swaps the contents of two Redis databases. This is useful for blue-green deployments of data: you populate a background database and then swap it with the live one instantly.

Q41: How do you handle "Session Affinity" with Redis?​

If you have multiple Redis Cluster nodes, you can ensure that related keys (like a user's profile and their session) are stored on the same node using "Hash Tags". Wrap the common part of the key in curly braces {...}.

SET user:{123}:profile "..."
SET user:{123}:session "..."
# Both will map to the same hash slot

Q42: What is the ROLE command?​

The ROLE command returns the role of the Redis instance (master, slave, or sentinel) and metadata about its current state (e.g., connected replicas for a master, or replication offset for a slave).

Q43: Explain HINCRBY.​

Increments the value of a field in a Hash by a specific integer. Similar to INCR but for hash fields.

Q44: What is the purpose of DBSIZE?​

Returns the total number of keys in the currently selected database.

Q45: Explain LRANGE.​

Returns a range of elements from a list. It uses 0-based indexing. -1 represents the last element.

LRANGE mylist 0 10 # First 11 elements

Q46: What is SMEMBERS?​

Returns all the members of a Set. This is an $O(N)$ operation where $N$ is the number of elements in the set. For large sets, use SSCAN.

Q47: How do you check if a key exists?​

Use the EXISTS command. It returns 1 if the key exists, 0 otherwise.

Q48: Explain CLIENT LIST.​

Returns information and statistics about all currently connected client connections in a human-readable format (IP, port, age, idle time, current database, etc.).

Q49: What is TTL and PTTL?​

  • TTL: Returns the remaining time to live of a key in seconds.
  • PTTL: Returns it in milliseconds. Both return -1 if the key exists but has no associated expire, and -2 if the key does not exist.

Q50: What is LASTSAVE?​

Returns the UNIX timestamp of the last successful RDB snapshot save to disk.


2. Intermediate Questions​

Q51: Explain the "Redis 6.0 Multi-threaded I/O" architecture.​

Historically, Redis was strictly single-threaded. In version 6.0, it introduced multi-threading only for the network I/O layer.

  • The Core: The execution of commands (accessing and modifying data structures) is still single-threaded to maintain simplicity and atomicity.
  • The Threads: Dedicated threads are used to handle the reading of requests from the socket and the writing of responses back to the socket.
  • Benefit: This allows Redis to scale better on multi-core machines when the bottleneck is the CPU overhead of processing the network stack.

Q52: Describe the "AOF Rewrite" process.​

As Redis runs, the AOF file grows by appending every write. To keep it manageable, Redis can "rewrite" the AOF.

  1. Redis forks a child process.
  2. The child writes the current state of the database to a new, temporary AOF file (generating the shortest possible sequence of commands to reach that state).
  3. Meanwhile, the parent continues to log new writes to the old AOF and a separate buffer.
  4. Once the child is done, the parent appends the buffer to the new AOF and replaces the old one.
  • Result: A much smaller AOF file that represents the same dataset.

Q53: How does "Redis Cluster" handle failover?​

Redis Cluster doesn't use Sentinel. Instead, the nodes monitor each other.

  1. Nodes send "PING/PONG" packets to each other.
  2. If a node detects that a master is unresponsive, it marks it as "PFAIL" (Possible Failure).
  3. If a majority of masters agree that a node is down, it's marked as "FAIL".
  4. The replicas of the failed master hold an election. The winning replica promotes itself to master and takes over the hash slots of the failed node.

Q54: Explain "Client-side Caching" in Redis 6.0.​

Redis 6.0 introduced support for "Tracking", which helps developers implement efficient client-side caches.

  • Invalidation: Redis tracks which keys a client has read. If one of those keys is modified, Redis sends an "Invalidation Message" to that client.
  • Benefit: This allows applications to store data in local memory with high confidence that it's consistent with the Redis server, drastically reducing network round-trips for hot keys.

Q55: What are the pitfalls of "Master-Slave Replication" data loss?​

Since replication is asynchronous, data loss can occur in two main scenarios:

  1. Master Crash: If the master receives a write, acknowledges it to the client, but crashes before sending it to the replicas.
  2. Network Partition (Split Brain): If a master is partitioned from the rest of the cluster and Sentinel promotes a new master. When the old master returns, it becomes a replica and overwrites its data with the new master's data, losing any writes it received during the partition.
  • Mitigation: Use min-replicas-to-write settings to ensure a master only accepts writes if it's connected to a certain number of healthy replicas.

Q56: Describe the "Ziplist" and "Hashtable" internal encodings for Hashes.​

  • Ziplist: A specially encoded, dually-linked list designed to be very memory-efficient. It stores keys and values consecutively in a single block of memory. It's used for small hashes.
  • Hashtable: A standard hash table providing $O(1)$ access. Used when the number of elements or the size of a value exceeds a threshold. Redis automatically handles the conversion (the "promotion") between these types.

Q57: How do you implement a "Distributed Lock" correctly with Redis?​

A basic SETNX isn't enough because the client might crash while holding the lock.

  1. Set with TTL: SET lock_key unique_id NX PX 30000. This sets the lock only if it doesn't exist, with an expiration (e.g., 30s) and a unique identifier.
  2. Release with Logic: To release, you must check if the unique_id matches before deleting (using a Lua script). This prevents a client from accidentally deleting a lock that was actually acquired by someone else after the original client's TTL expired.
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end

Q58: Explain "Backpressure" and how to handle it in Redis Streams.​

If producers are faster than consumers, the stream will grow indefinitely.

  • XTRIM / MAXLEN: You can limit the size of a stream by trimming it to a specific number of elements.
  • Consumer Acknowledgements (ACK): Consumers must acknowledge messages. If a message isn't acknowledged within a timeout, it can be claimed by another consumer (XCLAIM), ensuring no messages are lost.

Q59: What is "Memory Fragmentation" in Redis?​

Fragmentation occurs when the OS allocates memory to Redis, but when Redis frees that memory, the OS can't easily reclaim it because it's interspersed with memory still in use.

  • Ratio: mem_fragmentation_ratio = used_memory_rss / used_memory. A high ratio (> 1.5) indicates significant fragmentation.
  • Fix: Redis 4.0 introduced an "Active Defragmenter" that can rearrange memory in the background to reduce fragmentation.

Q60: Describe "Redis Module" system.​

Modules allow developers to extend Redis with new data types and commands, written in languages like C or Rust.

  • Examples: RedisJSON (native JSON support), RediSearch (full-text search), RedisTimeSeries.
  • Performance: Modules run at the same speed as built-in data types because they are loaded directly into the Redis core.

Q61: How does Redis handle "Large Key Eviction"?​

Deleting a massive key (e.g., a Set with 10 million members) can block the server. Redis provides the lazyfree-lazy-eviction configuration. If enabled, when Redis needs to evict a key to free memory, it uses the same logic as UNLINK (deleting the key in a background thread) to avoid blocking.

Q62: Explain "Optimistic Locking" with WATCH.​

Optimistic locking assumes that conflicts are rare. You WATCH a key, get its value, calculate a new value, and then try to update it inside a MULTI/EXEC block. If another client changed the key in the meantime, EXEC returns null, and you simply retry the entire process. This is much more scalable than heavy row-level locking.

Q63: What is the difference between RDB and AOF in terms of file size and recovery speed?​

  • RDB: Small file size (compressed snapshot). Extremely fast recovery because it just loads the data into memory.
  • AOF: Large file size (every command logged). Slower recovery because it must re-execute every command. However, "AOF Rewrite" helps keep the file size reasonable.

Q64: How do you monitor Redis performance in production?​

  1. latency monitor: Tracks and logs latency spikes.
  2. slowlog: Identifies slow commands.
  3. info memory: Monitors memory usage and fragmentation.
  4. info replication: Checks for lag between master and replicas.
  5. External Tools: Using Prometheus/Grafana with the Redis Exporter is the industry standard for real-time visualization and alerting.

Q65: Explain "Hash Slot" migration in Redis Cluster.​

When adding or removing nodes from a Cluster, you must move hash slots.

  1. The source node marks a slot as MIGRATING.
  2. The destination node marks it as IMPORTING.
  3. Keys are moved one by one using the MIGRATE command.
  4. Once all keys are moved, the cluster topology is updated across all nodes. This process is online and doesn't require downtime.

Q66: Describe the "Redis Bitset" population counting optimization.​

For very large bitmaps, BITCOUNT can be slow. To optimize, you can:

  1. Divide the bitmap into smaller chunks.
  2. Use BITOP to perform bitwise operations across multiple keys.
  3. Cache the counts of completed chunks.

Q67: What is "Redis Bloom Filter"?​

Available via the RedisBloom module, it's a probabilistic data structure that tells you if an element is definitely not in a set or might be in a set.

  • Benefit: Extremely memory-efficient way to prevent "Cache Penetration" (requesting keys that don't exist in the database).

Q68: Explain "Pipelining" vs "Transactions".​

  • Pipelining: A network optimization. Multiple commands are sent at once to save RTT. Commands from other clients can be interleaved on the server.
  • Transactions (MULTI/EXEC): A consistency feature. Ensures a block of commands is executed atomically and in isolation.

Q69: How do you handle "Hot Keys" in Redis?​

A "Hot Key" is a single key that receives a disproportionate amount of traffic, potentially overwhelming the node it resides on.

  • Solutions:
    1. Client-side caching: Store the value in the application's memory.
    2. Replication: Spread the read load across multiple replicas.
    3. Key Splitting: Instead of one key global_counter, use global_counter:1, global_counter:2 etc., and aggregate them in the application.

Q70: What is "Big Key" problem and how to detect it?​

A "Big Key" is a key that contains a very large amount of data (e.g., a List with millions of elements). It causes high latency during deletion, slow backups, and replication issues.

  • Detection: Use redis-cli --bigkeys. It samples the keyspace and reports the largest keys found for each data type.

Q71: Describe the "COW" (Copy-on-Write) mechanism in Redis Persistence.​

When Redis performs an RDB save or an AOF rewrite, it forks a child process.

  • Mechanism: The OS doesn't immediately copy all the memory. Instead, both processes share the same physical memory pages. Only when the parent process modifies a page does the OS create a unique copy for that process.
  • Impact: This allows Redis to take a snapshot with very little extra memory, provided the write rate is not extremely high during the process.

Q72: What is "Read Scaling" in Redis?​

You can scale read operations by adding replicas and configuring the application to send GET requests to those replicas. In a Redis Cluster, you must use the READONLY command on a replica connection before it will accept read queries for the slots owned by its master.

Q73: Explain the MEMORY USAGE command.​

Introduced in Redis 4.0, this command reports the actual number of bytes a key consumes in RAM, including all the overhead of the data structure and the pointers. This is much more accurate than just looking at the length of a string.

Q74: What is the purpose of XPENDING in Streams?​

XPENDING allows you to inspect the "Pending Entries List" (PEL) for a consumer group. It shows which messages have been delivered to consumers but haven't been acknowledged yet. This is critical for identifying stuck or crashed consumers.

Q75: Describe "Redis Pub/Sub" limitations for reliable messaging.​

  1. No Persistence: Messages are lost if no one is listening.
  2. No Acknowledgements: Publishers don't know if anyone received the message.
  3. No Buffering: If a subscriber is slow, Redis might disconnect it to protect its own memory. For reliable messaging, use Redis Streams instead.

Q76: How do you use GEOSEARCH?​

GEOSEARCH (Redis 6.2+) is the successor to GEORADIUS. It allows for more flexible geospatial queries, including searching within rectangular areas and sorting results.

Q77: Explain "Active Expiry" vs "Passive Expiry".​

  • Passive: Redis deletes a key when a client tries to access it and it's found to be expired.
  • Active: Redis periodically (10 times per second) samples a random set of keys with an expiration set and deletes those that have expired. This ensures that expired keys that are never accessed are eventually removed.

Q78: What is the SYNC command?​

SYNC is the low-level command used by replicas to initiate the replication process with a master. It triggers the master to create an RDB file and stream it to the replica. For incremental updates, PSYNC (Partial Sync) is used.

Q79: Describe "Replication ID" and "Offset".​

  • Replication ID: A unique string identifying a specific dataset "history".
  • Offset: An integer representing the number of bytes of the replication stream produced by the master. Together, these allow a replica to reconnect and perform a "Partial Resync" if it was disconnected for a short time, rather than performing a full, expensive RDB transfer.

Q80: What is the purpose of DEBUG OBJECT?​

It's an internal command that provides very low-level information about a key, such as its physical address in memory and its reference count. It should never be used in production.

Q81: Explain "Intsets" encoding for Sets.​

If a Set only contains small integers, Redis uses an intset encoding, which is a highly compact, sorted array of integers. This is much more memory-efficient than a hash table.

Q82: How do you implement "Auto-complete" with Redis?​

Use a Sorted Set. Store the strings as members and 0 as the score. Use ZRANGEBYLEX to find strings that start with a specific prefix. This provides $O(\log N)$ prefix searching.

Q83: What is the OBJECT IDLETIME command?​

Returns the number of seconds since a key was last read or written. This is used by the LRU eviction policy to decide which keys to remove.

Q84: Describe "Slave-side Read-Only" mode.​

By default, replicas are read-only. This prevents accidental writes that would create data inconsistency with the master. While you can make a replica writable, those writes are local and will be overwritten as soon as the replica receives an update from the master.

Q85: Explain BITFIELD.​

BITFIELD allows you to treat a Redis string as an array of bits and perform atomic operations on bit-fields of arbitrary sizes (e.g., incrementing a 5-bit integer at bit offset 10). It's a very powerful tool for building custom bit-packed data structures.

Q86: What is the "Redis Security" ACL LOG?​

The ACL Log records all failed authentication attempts and all attempts to execute commands that the user doesn't have permission for. It's an essential tool for security auditing.

Q87: How do you handle "Time-series" data in Redis?​

  1. Sorted Sets: Use timestamp as the score.
  2. Streams: Each entry is an event with a timestamp.
  3. RedisTimeSeries Module: Provides specialized commands for downsampling, aggregation, and retention policies.

Q88: Explain ZREVRANK.​

Returns the rank of a member in a Sorted Set, with scores ordered from high to low. This is how you find a user's position on a leaderboard.

Q89: What is the PUBSUB command used for?​

It's an introspection command that allows you to see the state of the Pub/Sub system: which channels are active and how many subscribers each channel has.

Q90: Describe "Self-Healing" in Redis Cluster.​

If a node is alone on its side of a network partition and cannot see the majority of masters, it will automatically stop accepting writes to protect data consistency. Once the partition is resolved and it can see the majority again, it resumes normal operation.

Q91: Explain HGETALL performance.​

HGETALL is $O(N)$ where $N$ is the size of the hash. For very large hashes, it can block the server. Use HSCAN to iterate through the fields in a non-blocking way.

Q92: What is the ROLE of a "Promoted Slave"?​

When a slave is promoted to master, it generates a new Replication ID. It then starts accepting writes and becomes the source of truth for the other slaves.

Q93: How do you use CLIENT PAUSE?​

This command stops processing commands from all clients for a specified amount of time. It's useful during maintenance or when performing a manual failover to ensure that no writes are lost during the switch.

Q94: Explain BRPOP and BLPOP.​

These are "Blocking" versions of the pop commands. If the list is empty, the client blocks until an element is pushed by another client, or until a timeout is reached. This is a perfect way to implement a simple work queue.

Q95: What is the "Redis Cluster" CLUSTER NODES command?​

Returns the current cluster configuration as seen by the node you are connected to: a list of all nodes, their roles, their status, and the hash slots they own.

Q96: Describe "Quicklist" encoding for Lists.​

Introduced in Redis 3.2, a quicklist is a linked list of ziplists. This combines the memory efficiency of ziplists for small groups of elements with the flexibility of linked lists for very large collections.

Q97: How do you implement "Rate Limiting with Sliding Window"?​

Use a Sorted Set where each member is a unique request ID (or just a timestamp) and the score is the timestamp.

  1. ZREMRANGEBYSCORE to remove entries older than the window.
  2. ZCARD to count the remaining entries.
  3. If count < limit, ZADD the current request. This is much more accurate than fixed-window counting.

Q98: What is MEMORY DOCTOR?​

A diagnostic command that provides a human-readable report on the memory health of the Redis instance, pointing out issues like high fragmentation or large client buffers.

Q99: Explain SDIFF and SDIFFSTORE.​

  • SDIFF: Returns the members of the first set that are not present in any of the subsequent sets.
  • SDIFFSTORE: Same as SDIFF but stores the result in a new set.

Q100: How do you handle "Redis Version" upgrades?​

Generally, you can upgrade a replica to a newer version and then perform a failover. Redis is designed to be backward compatible, so a newer version replica can replicate from an older version master (but not vice-versa).


3. Advanced Questions​

Q101: Deep dive: Redis "Single-Threaded" Event Loop internals.​

Redis uses an I/O multiplexing library (like epoll on Linux or kqueue on BSD) to monitor multiple file descriptors (sockets) at once.

  • The Loop:
    1. The loop calls epoll_wait to find which sockets have pending data.
    2. For each active socket, it reads the request into a buffer.
    3. It parses the request and executes the command.
    4. It writes the result back to the client's output buffer.
    5. It performs periodic tasks (like deleting expired keys or checking replication status).
  • Why it's fast: No locks needed, no thread context switching, and the entire dataset is in RAM.

Q102: Explain "RDB Child Fork" memory issues.​

While Copy-on-Write (COW) is efficient, if the parent process modifies many keys while the child is writing the RDB, the OS will start duplicating many memory pages. In a worst-case scenario (every page modified), you could need 2x the RAM.

  • Tuning: Monitor latest_fork_usec and ensure the server has enough swap or free RAM to handle spikes during snapshots.

Q103: How would you implement "Real-time Leaderboard with millions of users"?​

  1. Sorted Set: Use ZADD to update scores and ZREVRANGE to get the top players.
  2. Sharding: If one node can't handle the traffic, you can't easily shard a single ZSet. Instead:
    • Use multiple ZSets for different regions.
    • Or use a hybrid approach where you keep the "Top 1000" in a central Redis node and the rest in shards.
  3. Complexity: Updating is $O(\log N)$, and getting a range is $O(\log N + M)$.

Q104: Describe "AOF Rewriting" durability risks.​

During a rewrite, if the parent process crashes after the child finished but before the parent finished appending the buffer, you could lose data. Redis mitigates this by keeping the old AOF until the new one is fully synced and renamed, ensuring there's always a valid log on disk.

Q105: Explain "Gossip Protocol" in Redis Cluster.​

Nodes in a cluster don't have a central coordinator. They communicate using a gossip protocol to share information about the state of the cluster.

  • Messages: Nodes send MEET, PING, PONG, and FAIL messages.
  • Propagation: Information about a failed node eventually spreads to the entire cluster, allowing all nodes to agree on a new topology.

Q106: How do you implement "Search-as-you-type" with Sorted Sets?​

This uses the lexicographical ordering of Sorted Sets where all members have the same score (0).

  1. ZADD autocomplete 0 "apple".
  2. Use ZRANGEBYLEX autocomplete "[app" "[app\xff". This returns all strings starting with "app". The \xff is a high-value character that defines the upper bound of the search range.

Q107: Describe "Active Defragmentation" internals.​

Redis's active defragmenter works by scanning the keyspace. If it finds a value that is stored in a fragmented memory page, it creates a new copy of that value (which the allocator will hopefully place in a more compact page) and updates the pointer. It throttles itself based on CPU usage to avoid affecting application performance.

Q108: What is the "Redis Cluster" MOVED vs ASK redirection?​

  • MOVED: The client sent a query for a slot that is permanently owned by another node. The client should update its internal mapping.
  • ASK: The client sent a query for a slot that is currently being migrated. The client should try the other node only for this specific query and not update its mapping.

Q109: Explain "Memory Optimization" for small objects in Redis.​

Redis uses specialized encodings like ziplist and intset for small collections.

  • Hashes/Lists/Sets: If they have fewer than hash-max-ziplist-entries and every value is shorter than hash-max-ziplist-value, they use the compact encoding.
  • Benefit: This can reduce memory usage by up to 10x for applications that store millions of small objects.

Q110: How does "Redlock" handle clock drift?​

Clock drift is the biggest threat to Redlock. If one node's clock moves faster than others, it might expire its lock earlier than expected, allowing another client to acquire it. Redlock mitigates this by including a "drift margin" in its validity calculations and by using a monotonic clock (if available) instead of wall-clock time.

Q111: Describe "Redis Streams" XREADGROUP and "Pread" semantics.​

When a consumer in a group reads from a stream using XREADGROUP, Redis ensures that each message is delivered to only one consumer in the group. Redis tracks "Pending" messages (delivered but not ACKed) for each consumer. This allows for reliable, at-least-once delivery of events.

Q112: Explain "Diskless Replication".​

Normally, a master creates an RDB file on disk and then sends it to replicas.

  • Diskless: The master generates the RDB and sends it directly to the socket without ever touching the disk.
  • Use Case: When the master has slow disks but a fast network, this can significantly speed up the initial synchronization of new replicas.

Q113: How do you tune maxmemory-samples?​

LRU and LFU in Redis are not exact; they are approximations. When choosing a key to evict, Redis samples a number of keys and picks the best candidate among them.

  • Tuning: Increasing maxmemory-samples (default 5) makes the algorithm more accurate (closer to real LRU) but consumes more CPU.

Q114: Explain "Lua Script" caching (SCRIPT LOAD and EVALSHA).​

Sending a large Lua script over the network for every execution is inefficient.

  1. SCRIPT LOAD: Sends the script to Redis. Redis caches it and returns a SHA1 hash.
  2. EVALSHA: Executes the script using only the hash. This saves bandwidth and parsing time on the server.

Q115: What is the "Replication Backlog"?​

The backlog is a circular buffer on the master that stores the recent stream of writes.

  • Purpose: If a replica disconnects briefly and then reconnects, it can request the missing data from the backlog (Partial Resync) instead of performing a full RDB transfer.
  • Tuning: Set repl-backlog-size based on your expected write rate and the maximum time you expect a replica might be disconnected.

Q116: Explain "Threaded I/O" configuration.​

In Redis 6.0, you enable multi-threaded I/O using io-threads.

  • io-threads-do-reads: Set to yes to enable threading for request parsing.
  • io-threads: Set to the number of threads (usually 2-4, and always less than the number of CPU cores).
  • Monitoring: Check io_threaded_reads_processed and io_threaded_writes_processed in INFO to see if the threads are actually being used.

Q117: Describe "Hash Tag" collision risks in Redis Cluster.​

While hash tags allow you to group keys on a single node, they can also lead to "hot spots". If you put all data for a single massive tenant under one hash tag {tenant_123}:*, you are effectively defeating the purpose of sharding, as all that tenant's data will be on one physical server.

Q118: How do you implement "Reliable Queues" with RPOPLPUSH?​

This command atomically pops an element from one list and pushes it to another. This is used to implement a "processing" queue:

  1. RPOPLPUSH work_queue processing_queue.
  2. Worker processes the item.
  3. Worker deletes it from processing_queue on success. If the worker crashes, the item remains in the processing_queue and can be recovered by a cleanup process.

Q119: What is "Module Persistence"?​

Redis modules can define their own custom data types. To survive restarts, the module must also provide functions to serialize and deserialize its data into the RDB and AOF files. This ensures that custom module data is just as durable as built-in Redis data.

Q120: Explain the "Client Tracking" BCAST mode.​

In BCAST (broadcast) mode, Redis sends invalidation messages for any key that matches a specific prefix, regardless of whether the client had previously read that specific key. This is useful for clients that want to maintain a local cache of an entire namespace (e.g., all configuration settings).

Q121: Describe "Redis Cluster" READONLY command.​

Replicas in a cluster usually redirect all queries to their master. If you want to scale reads, the client must first issue the READONLY command on the connection to the replica. This tells the replica that it's okay to serve GET requests for the slots it holds, even though it's not the master.

Q122: Explain "HyperLogLog" "Sparse" vs "Dense" representation.​

  • Sparse: Used for small cardinalities to save memory. It's a highly compressed representation.
  • Dense: Used once the cardinality grows. It uses a fixed 12KB bit-array. Redis automatically handles the conversion between these two as you add more elements.

Q123: How do you use SCAN with "Type" filtering?​

Introduced in Redis 6.0, you can use the TYPE argument with SCAN to only return keys of a specific type (e.g., only hashes). This is much more efficient than fetching all keys and checking their type in the application.

SCAN 0 TYPE hash MATCH user:*

Q124: What is the "Redis Sentinel" QUORUM?​

The quorum is the number of Sentinels that must agree that a master is unreachable before it is marked as ODOWN (Objectively Down) and the failover process is started. It's usually set to half the number of Sentinels plus one.

Q125: Explain "Sorted Set" LEX operations.​

If all members of a ZSet have the same score, they are ordered lexicographically. Commands like ZRANGEBYLEX, ZLEXCOUNT, and ZREMRANGEBYLEX allow you to perform range queries and deletions on the string values themselves, which is useful for things like tag searching or directory listings.

Q126: Describe "Memory Deflation" in Redis.​

This refers to the process of Redis giving memory back to the OS. Because of the way the C memory allocator works, this doesn't always happen immediately. Using a different allocator like jemalloc (the default for Redis on many platforms) helps manage memory fragmentation and reclamation more effectively.

Q127: Explain the MIGRATE command.​

MIGRATE is an atomic command that combines DUMP, RESTORE (on the target), and DEL (on the source). It's the fundamental building block for moving data between Redis instances, used extensively during Redis Cluster resharding.

Q128: How do you handle "Pub/Sub" "Slow Consumer" problems?​

If a subscriber can't keep up with the message volume, its output buffer will grow. You can set client-output-buffer-limit pubsub in redis.conf to automatically disconnect subscribers whose buffers exceed a certain size, preventing them from crashing the server.

Q129: Describe "Redis Cluster" "Manual Failover".​

You can trigger a failover manually using the CLUSTER FAILOVER command on a replica.

  • Force: If the master is down.
  • Takeover: Promotes the replica instantly without coordinating with the master.
  • Standard: Coordinates with the master to ensure no data is lost during the switch.

Q130: What is "Tracking-CACHING" mode?​

In this mode, the server only sends invalidation messages for keys that the client explicitly requested to be tracked using the CACHING command right before a GET. This gives the client fine-grained control over which parts of the dataset it wants to keep in its local cache.

Q131: Explain "Bitfield" OVERFLOW behavior.​

When an operation like INCRBY on a bitfield exceeds the specified number of bits, you can define the overflow behavior:

  • WRAP: (Default) Standard integer wrap-around.
  • SAT: Saturation - stays at the max/min value.
  • FAIL: Returns an error.

Q132: Describe "Redis Stream" XREAD "Block" vs "Non-block".​

  • Non-block: Returns immediately with any available messages.
  • Block: Blocks the client for a specified number of milliseconds (or 0 for indefinitely) until a new message is appended to the stream. This is the standard way to implement efficient long-polling for events.

Q133: Explain "Module Command" registration.​

When a module is loaded, it registers its commands using RedisModule_CreateCommand. This function defines the command name, the callback function, the required flags (e.g., write, readonly), and the key-space notification settings.

Q134: How do you monitor "Redis Cluster" Slave Lag?​

In INFO REPLICATION, look at slave_repl_offset on the master and compare it to the master's own master_repl_offset. The difference is the amount of data (in bytes) that has been written to the master but not yet received by the replica.

Q135: Describe "Redis Cluster" Replica Migration.​

This is a feature where an "orphan" master (one with no replicas) can "steal" a replica from another master that has multiple replicas. This ensures that the cluster remains robust even after multiple independent hardware failures.

Q136: Explain ZREMRANGEBYSCORE performance.​

This is $O(\log N + M)$ where $N$ is the size of the set and $M$ is the number of elements deleted. It's efficient for maintaining "sliding window" datasets where you constantly remove old records.

Q137: What is the CLIENT SETNAME command?​

Allows you to give a human-readable name to a connection. This name appears in CLIENT LIST and MONITOR output, making it much easier to identify which application or service a connection belongs to.

Q138: Describe "Redis Sentinel" TILT mode.​

If a Sentinel detects that the system time has jumped or if it hasn't been able to run its internal tasks for a while, it enters TILT mode. In this mode, it continues to monitor but stops performing failovers, as it can't trust its own sense of time or state. It exits TILT mode after 30 seconds of normal operation.

Q139: Explain HSCAN "Count" and "Match".​

  • MATCH: Filters the fields by pattern (on the server side).
  • COUNT: A hint for how much work to do in each step. Setting it higher reduces the number of round-trips but increases the execution time of a single HSCAN call.

Q140: How do you implement "Idempotent Writes" in Redis?​

  1. Conditional Sets: Use SET NX to only write if the key doesn't exist.
  2. Version Checks: Store a version number with the data and use a Lua script to only update if the version in the request matches the current version in Redis.

Q141: Describe "Redis Cluster" Slot Ownership distribution.​

Ownership is stored in a simple bitmask of 16384 bits on every node. When a node receives a query for a slot it doesn't own, it uses its own local copy of this bitmask to tell the client where to go via a MOVED error.

Q142: Explain "Redis Persistence" fsync settings.​

  • appendfsync always: Slowest, safest (fsync after every write).
  • appendfsync everysec: (Default) Good balance, max 1s of data loss.
  • appendfsync no: Fastest, least safe (leaves it to the OS).

Q143: What is MEMORY PURGE?​

A command that forces the memory allocator (usually jemalloc) to release as much unused memory back to the operating system as possible. It's a "manual" defragmentation step.

Q144: Describe "Redis Stream" XGROUP management.​

This command is used to create, destroy, and manage consumer groups for a stream. You can also use it to set the "last delivered ID" for a group, effectively allowing you to "replay" old messages for a new set of consumers.

Q145: Explain "Sorted Set" ZINTERSTORE.​

Calculates the intersection of multiple Sorted Sets. You can specify "Weights" for each set (the scores are multiplied by the weight before summing) and "Aggregate" methods (SUM, MIN, MAX).

Q146: How do you use CLIENT ID?​

Returns the unique ID of the current connection. This ID is guaranteed to be unique for the lifetime of the Redis server process and is useful for logging and tracking.

Q147: Describe "Redis Sentinel" Autodiscovery.​

Sentinels find other Sentinels for the same master by using the master's Pub/Sub system. They also find all replicas by querying the master with the INFO command. This makes adding new Sentinels or replicas to a cluster very easy.

Q148: Explain BITCOUNT on a range.​

You can specify a start and end byte range to count the set bits only in a specific part of a string. This is useful for splitting a massive user-activity bitmap into monthly or weekly chunks.

Q149: What is the ACL SETUSER command?​

The primary command for managing ACLs in Redis 6.0+. You can define the username, password, allowed commands (using patterns), and allowed keys (using patterns).

ACL SETUSER alice on >password123 +get +set ~user:*

Q150: Describe "Redis Cluster" Failover Auth.​

When a replica wants to promote itself, it asks the other masters for votes. It only becomes master if it receives votes from a majority of the masters. This prevents multiple replicas from trying to take over the same slots simultaneously.

4. Master Pack - Redis Internals and High Performance​

Q151: Explain "Hash Table Rehashing" in Redis.​

Redis uses incremental rehashing to avoid blocking the server when a hash table grows.

  1. Redis allocates a second, larger hash table.
  2. Every time a command touches the hash, Redis moves a few buckets from the old table to the new one.
  3. Redis also has a background task that performs rehashing when the server is idle.
  4. Once all buckets are moved, the old table is freed.

Q152: Deep dive: The "Listpack" encoding (Redis 7.0+).​

listpack is the modern successor to ziplist. It's a more robust and slightly more memory-efficient way to store small lists, hashes, and sorted sets in a single contiguous block of memory. It avoids the "cascading update" problem that could occasionally occur with ziplists, making updates more predictable.

Q153: Describe "I/O Thread" placement and NUMA awareness.​

In large servers with multiple CPU sockets (NUMA), memory access is faster if the thread is running on the same socket that owns the memory. While Redis core doesn't handle this automatically, performance experts often use numactl or taskset to bind the Redis process and its I/O threads to specific cores on a single socket to minimize memory latency.

Q154: How do you handle "AOF Disk Space" exhaustion?​

If the disk is full, AOF writes will fail, and Redis (by default) will stop accepting writes to prevent data corruption.

  1. Increase disk space.
  2. Or use CONFIG SET appendonly no to temporarily disable persistence (data loss risk).
  3. Monitor aof_last_write_status in INFO to detect this state.

Q155: Explain "Gossip Protocol" "Fanout" and "Convergence".​

In a large Redis Cluster (e.g., 500 nodes), gossip messages can consume significant bandwidth.

  • Fanout: Each node only PINGs a few random nodes in each step.
  • Convergence: Information about a state change (like a node failure) propagates exponentially through the cluster. The time to reach "Full Convergence" determines how fast the cluster can react to failures.

Q156: Describe the "Sorted Set" "Jump List" (Skip List) implementation.​

Redis uses a Skip List to store Sorted Set members. It's a probabilistic data structure that provides $O(\log N)$ search, insertion, and deletion. It's easier to implement and more memory-efficient than balanced trees (like AVL or Red-Black trees) for this specific use case, and it allows for efficient range queries.

Q157: What is "Active Defragmentation" and its relationship with Memory Allocators?​

Active defragmentation relies on the memory allocator (jemalloc) providing information about the physical location of memory blocks. Redis asks jemalloc if a block is in a "fragmented" page; if so, it moves the data to a new block. This is why active defragmentation is primarily supported on systems using jemalloc.

Q158: How does "Redis Cluster" handle "Key Migration" atomicity?​

Key migration uses the MIGRATE command.

  1. The source node sends the serialized key data to the target.
  2. The target receives and restores the key.
  3. The target sends an ACK.
  4. The source deletes the key. During this process, the source node blocks any other queries for that specific key to ensure atomicity.

Q159: Explain "Memory Optimization" for Boolean flags.​

Storing boolean flags as standard Strings ("true"/"false") is very expensive (dozens of bytes per key).

  1. Use Bitmaps: 1 bit per flag.
  2. Use Sets: Only store the ID if the flag is true. Bitmaps are usually the most efficient for dense datasets, while Sets are better for sparse ones.

Q160: Describe "Redlock" and the "Fencing Token" critique.​

Distributed systems expert Martin Kleppmann critiqued Redlock, arguing that it's not truly safe without "Fencing Tokens".

  • Problem: If a process holding a Redlock is paused (GC pause), its lock might expire. Another process acquires the lock. When the first process wakes up, it thinks it still has the lock and performs an update.
  • Solution: The lock service should return a monotonic "Fencing Token" that the database checks before allowing an update.

Q161: How do you implement "Reliable Task Acknowledgment" in Streams?​

Use XACK. When a consumer finishes processing a message, it calls XACK stream group id. This removes the message from that consumer's Pending Entries List (PEL). If a message stays in the PEL for too long, a monitor process can use XCLAIM to assign it to a different consumer.

Q162: Explain "Diskless Replication" and "Wait for Replicas".​

When a master is diskless, it waits a few seconds (controlled by repl-diskless-sync-delay) before starting the transfer. This allows multiple replicas to connect so the master can stream the same RDB to all of them at once, rather than starting a new generation process for each one.

Q163: Describe "LRU" vs "LFU" in a high-churn cache.​

  • LRU (Least Recently Used): Good for "temporal locality" - data accessed recently will be accessed again soon.
  • LFU (Least Frequently Used): (Redis 4.0+) Better for data that has varying popularity over long periods. It uses a "logarithmic counter" to track access frequency and a "decay" factor to ensure old hot keys eventually expire.

Q164: How do you handle "Lua Script" infinite loops?​

Redis has a lua-time-limit (default 5s). If a script runs longer than this, Redis starts accepting queries again but returns a "BUSY" error. You can then use SCRIPT KILL to stop the script if it's read-only, or SHUTDOWN NOSAVE if it has already performed writes.

Q165: Explain "Replication Backlog" "Shared usage".​

The replication backlog is shared across all connected replicas. Even if you have 10 replicas, the master only needs one backlog buffer. This is very memory-efficient for large read-scaling architectures.

Q166: Describe "Threaded I/O" "Side effects".​

While multi-threading improves throughput, it can slightly increase the latency of individual requests because of the overhead of handing data between threads. It also increases CPU usage. It should only be enabled when the single core is at 100% and network throughput is the clear bottleneck.

Q167: What is "Hash Tag" "Distribution skew"?​

If many keys use the same hash tag {user_1}:*, they will all live on the same Cluster node. If user_1 is a massive enterprise customer, that node will become a bottleneck. Always balance the need for multi-key operations (which require hash tags) against the need for even data distribution.

Q168: Explain RPOPLPUSH vs LMOVE.​

LMOVE (Redis 6.2+) is the modern replacement for RPOPLPUSH. It's more flexible because you can specify the source and destination sides (Left or Right) for both the pop and the push operations, allowing you to implement diverse queue patterns.

Q169: Describe "Module Serialization" hooks.​

A module provides rdb_load and rdb_save callbacks. During an RDB save, Redis calls the module's function, giving it a stream object to write its data. This allows modules to implement highly customized, optimized storage formats for their new data types.

Q170: Explain "Client Tracking" "Invalidation Message" format.​

Invalidation messages are sent as "Out-of-Band" data in the Redis protocol (RESP3). They contain a list of key names. The client must immediately remove these keys from its local memory cache.

Q171: Describe "Redis Cluster" REPLICAOF vs CLUSTER REPLICATE.​

  • REPLICAOF: Used in standard master-slave replication.
  • CLUSTER REPLICATE: Used in Redis Cluster. It takes a node ID instead of an IP/port and automatically handles the cluster-wide configuration update.

Q172: How do you use "HyperLogLog" for "Intersection" estimates?​

Standard HLL doesn't support intersection. However, you can use the Inclusion-Exclusion principle: $A \cap B = A + B - (A \cup B)$. You can calculate $A \cup B$ easily using PFMERGE, and use $A + B$ from individual PFCOUNT calls to estimate the intersection.

Q173: Explain SCAN "Guarantees" and "Limitations".​

  • Guarantees: It will return every element that was present from the start to the end of the scan.
  • Limitations: It might return an element multiple times if it was moved between buckets during rehashing. It might miss an element that was added after the scan started.

Q174: What is "Redis Sentinel" leader election?​

When a master is down, the Sentinels must elect one Sentinel to be the "leader" who will perform the failover. They use the Raft-like algorithm to reach a consensus. Only the leader performs the SLAVEOF NO ONE command on the chosen replica.

Q175: Explain "Sorted Set" ZREMRANGEBYLEX.​

Removes all members in a Sorted Set between two lexicographical values. This is an efficient way to "delete a folder" if you are using ZSets to represent a file system hierarchy with paths as members.

Q176: Describe "Memory Overcommit" on Linux.​

Linux's vm.overcommit_memory should be set to 1. This tells the kernel to allow all memory allocations, which is critical for Redis's fork() mechanism. If set to 0, the fork might fail if the OS thinks there isn't enough memory for a full copy, even though COW means only a tiny fraction will actually be copied.

Q177: What is "MIGRATE" "Timeout" and its impact?​

The timeout in MIGRATE is the maximum time the source node will block while waiting for the target to acknowledge. If it's too short, migrations will fail on large keys or slow networks. If it's too long, it can cause latency spikes for other clients.

Q178: Explain "Pub/Sub" "Pattern Matching" (PSUBSCRIBE).​

Clients can subscribe to channels using glob-style patterns (e.g., user.*). This is powerful but has a higher CPU cost on the server than literal subscriptions, as Redis must check every published message against all patterns.

Q179: Describe "Redis Cluster" CLUSTER FORGET.​

This command removes a node from the cluster's local routing table. It must be run on all nodes in the cluster. It's used to cleanly remove a node that is being decommissioned.

Q180: What is "Tracking-REDIRECT"?​

This allows a client to tell Redis to send invalidation messages to a different connection ID. This is useful for implementing proxy layers where one connection handles data and another handles invalidation notifications.

Q181: Explain "Bitfield" WRAP overflow internals.​

WRAP performs standard two's complement wrap-around. For an 8-bit signed integer, incrementing 127 results in -128. This is the fastest overflow method as it maps directly to CPU instructions.

Q182: Describe "Redis Stream" XREAD "Last ID" logic.​

Clients track the "Last ID" they received. When calling XREAD, they provide this ID to get only newer messages. Using the special ID $ tells Redis to only return messages that arrive after the command was issued.

Q183: What is the "Redis Module" RedisModule_OnLoad function?​

This is the entry point for every Redis module. It's where the module registers its name, version, and commands. If this function returns an error, the module fails to load and Redis continues without it.

Q184: Explain "Redis Cluster" Slave Migration Barrier.​

cluster-migration-barrier is the minimum number of replicas a master must have before one of its replicas can be migrated to an "orphan" master. This prevents a master from being left with zero replicas after a migration.

Q185: Describe "Sorted Set" ZUNIONSTORE "Weights".​

Weights allow you to multiply the scores of members in different sets before combining them. Use case: combining a "recent views" set with a "long-term popularity" set, giving more weight to the recent data.

Q186: What is the CLIENT KILL command filters?​

You can kill connections based on many criteria: IP, ID, type (normal, master, pubsub), or even "skipme" (to avoid killing yourself). This is the "hammer" for dealing with misbehaving or stuck clients.

Q187: Describe "Redis Sentinel" Configuration Epoch.​

The epoch is a version number for the cluster configuration. Every time a failover happens, the epoch is incremented. Sentinels use this to ensure they always have the most up-to-date information and to resolve conflicts if multiple failovers happen concurrently.

Q188: Explain BITCOUNT "Population Count" algorithm.​

Redis uses a highly optimized implementation of the "popcount" algorithm, often using specialized CPU instructions (like POPCNT on x86) to count set bits as fast as the hardware allows.

Q189: What is the ACL GENPASS command?​

A convenience command that generates a cryptographically strong, random password that can be used for new ACL users.

Q190: Describe "Redis Cluster" Handshake process.​

When you run CLUSTER MEET, the nodes perform a 3-way handshake (MEET-PONG-PING) to exchange their IDs and IP/ports. Once finished, they are officially part of each other's "Known Nodes" list.

Q191: Explain "Wait for Replicas" durability levels.​

Using WAIT doesn't make Redis a strictly consistent database. It only ensures that the data has reached the replicas' memory. It doesn't guarantee that the replicas have written it to disk (fsync).

Q192: Describe "Redis Cluster" REPLICAS vs SLAVES.​

The command was renamed from CLUSTER SLAVES to CLUSTER REPLICAS in Redis 5.0 to use more inclusive terminology. They both return the list of replicas for a specific master node.

Q193: Explain HSCAN "Cursor" behavior.​

The cursor is not a pointer to memory; it's a number that represents the state of the iteration. It can jump around non-linearly because of the way hash tables are structured. A cursor of 0 always means the scan is finished.

Q194: Describe "Redis Sentinel" Parallel-Syncs.​

parallel-syncs determines how many replicas can be reconfigured to point to the new master at the same time after a failover. A lower number prevents overwhelming the new master with simultaneous RDB transfers.

Q195: Explain BITOP operations.​

BITOP performs bitwise AND, OR, XOR, and NOT across multiple keys. The result is stored in a destination key. It's a powerful way to implement complex set logic on millions of users using bitmaps.

Q196: Describe "Redis Cluster" Slot-to-Key mapping.​

Every node maintains a mapping of which keys in its local database belong to which hash slots. This is used during migration to quickly find all keys that need to be moved to a new node.

Q197: Explain "Redis Sentinel" Down-After-Milliseconds.​

The time a master must be unreachable (according to a single Sentinel) before it's marked as PFAIL. Setting this too low leads to "flapping" failovers; setting it too high increases downtime.

Q198: Describe "Redis Persistence" rdbchecksum.​

A CRC64 checksum is added to the end of every RDB file. This allows Redis to detect if a backup has been corrupted during storage or transfer, ensuring data integrity during recovery.

Q199: Explain MEMORY STATS.​

Provides a detailed breakdown of memory usage: total allocated, allocator overhead, shared buffer size, and a per-database breakdown of metadata size. It's more detailed than INFO MEMORY.

Q200: Describe "Redis Stream" XINFO introspection.​

XINFO allows you to get detailed metadata about a stream, its consumer groups, and individual consumers. It's the "debug" tool for complex event-driven architectures.

5. Grandmaster Redis - High Availability, Architecture, and Performance​

Q201: Explain the concept of "Replica Priority".​

In a Sentinel setup, every replica has a replica-priority. If the master fails, Sentinel chooses the replica with the lowest priority (greater than 0) to become the new master. If multiple replicas have the same priority, it chooses the one with the most up-to-date data (highest replication offset).

Q202: Describe the "Redis Stream" XREADGROUP "ID 0" vs ">" behavior.​

  • ID >: Only receive messages that were never delivered to any other consumer in the group.
  • ID 0: Only receive messages that were already delivered to this consumer but haven't been acknowledged yet. This is used to recover from consumer crashes and finish processing pending tasks.

Q203: What is "Redis Cluster" "Partial Failover"?​

If a node only loses a few hash slots but can still see the rest of the cluster, there's no such thing as a partial failover. In Redis Cluster, failover is all-or-nothing: the entire node is marked as failed, and its replica takes over all 16384/N slots it was responsible for.

Q204: How do you handle "Redis Cluster" "Discovery" issues in Docker/Kubernetes?​

Since nodes advertise their IP addresses to each other, running them behind NAT or in separate containers can cause issues. You must use the cluster-announce-ip, cluster-announce-port, and cluster-announce-bus-port settings to tell each node exactly what IP and port it should tell other nodes to use.

Q205: Describe the "Redis Bloom Filter" "Error Rate" trade-off.​

When creating a Bloom filter (BF.RESERVE), you specify the desired error rate.

  • Lower Error Rate: Needs more bits per element (more memory) and more hash functions (more CPU).
  • Higher Error Rate: More compact and faster but yields more "false positives".

Q206: Explain "Redis Module" "Timer" APIs.​

Modules can register timers that execute a callback function after a certain delay. This allows modules to implement logic that runs independently of client commands, such as periodic cleanup or complex automated data transformations.

Q207: What is the purpose of the "Redis Sentinel" sentinel.conf MYID?​

Each Sentinel has a unique 40-character ID. This ID is saved to the configuration file. It's how Sentinels identify each other and prevent multiple Sentinels from accidentally using the same state in a distributed environment.

Q208: Describe "Redis Cluster" "Failover Prevention" (Master with no replicas).​

If a master has no replicas, it can't fail over. In a large cluster, replicas are periodically "migrated" to cover orphan masters. This is a crucial feature for maintaining the availability of the cluster as a whole.

Q209: Explain "Sorted Set" "Lexicographical Search" performance.​

Lexicographical queries (like ZRANGEBYLEX) use the underlying Skip List. Since the set is already sorted, finding the start and end points is $O(\log N)$, and reading the range is $O(M)$ where $M$ is the number of elements. This is extremely efficient for large datasets.

Q210: How do you implement "Distributed Semaphores" with Redis?​

  1. Lua Script: Use a counter key.
  2. Logic: IF counter < limit THEN INCR counter; RETURN OK ELSE RETURN ERROR.
  3. Release: DECR counter. To make it "fair", you could use a List as a queue and have clients wait for their turn.

Q211: Describe "Redis Persistence" "Fork" latency monitoring.​

Monitor the latest_fork_usec metric in INFO STATS. If this number is consistently high (e.g., > 100ms), it indicates that the OS is struggling to create the child process, which will cause a noticeable latency spike for all application requests during the fork.

Q212: What is the "Redis Cluster" cluster-node-timeout?​

The most important setting in Redis Cluster. It's the maximum time a node can be unreachable before it is considered failed. If set too low, network glitches will cause constant failovers; if too high, the cluster will take too long to recover from a real failure.

Q213: Explain "Redis Tracking" "Opt-In" vs "Opt-Out".​

  • Opt-In: Keys are not tracked unless the client sends CLIENT CACHING YES before the GET.
  • Opt-Out: All keys read by the client are tracked by default, and the client can use CLIENT CACHING NO to avoid tracking specific keys. This allows for fine-grained control over the client-side cache volume.

Q214: Describe "Redis Stream" XREAD vs XRANGE.​

  • XRANGE: A "pull" operation. Fetches a range of messages by ID. Perfect for historical lookup.
  • XREAD: A "streaming" operation. Can block until new messages arrive. Optimized for real-time consumption.

Q215: What is "Redis Sentinel" Quorum vs Majority?​

  • Quorum: The number of Sentinels needed to detect a failure (ODOWN).
  • Majority: The number of Sentinels needed to elect a leader and authorize a failover. For a cluster with 3 Sentinels, the majority is 2.

Q216: Explain "Memory Usage" of a "Large List".​

A List of a million elements isn't just the size of the strings. It includes the pointers in the quicklist and the overhead of the ziplist nodes. Redis uses a significant amount of "metadata" memory to manage these structures, which is why MEMORY USAGE is always higher than the raw data size.

Q217: Describe "Redis Cluster" CLUSTER REPLICATE internals.​

This command changes a node's identity from a master to a replica of a specific node. It wipes the node's current database, clears its slot ownership, and starts a full synchronization with the new master.

Q218: What is "Redis Sentinel" notification-script?​

You can configure Sentinel to run a shell script whenever a significant event happens (like a failover or a replica coming online). This script can be used to send alerts to PagerDuty, update external load balancer configs, or log events to a central system.

Q219: Explain "Redis Modules" "Native Type" registration.​

Modules use RedisModule_CreateDataType to register a new type. This includes defining the "type ID" (a 64-bit integer encoding the name and version) and providing the method table for RDB/AOF serialization, memory reporting, and deletion.

Q220: Describe "Redis Cluster" failover-validity-factor.​

Used to prevent "stale" replicas from being promoted. If a replica has been disconnected from its master for more than cluster-node-timeout * cluster-slave-validity-factor, it is disqualified from becoming the new master.

Q221: Explain "Sorted Set" ZREVRANGEBYLEX.​

The reverse version of ZRANGEBYLEX. It allows you to search for strings in reverse lexicographical order. This is useful for finding the "previous" item in a sorted list or for implementing backwards pagination in a file browser.

Q222: What is the "Redis Sentinel" client-reconfig-script?​

A script that Sentinel runs after a failover has been successfully completed. It receives the old and new master's details. It's often used to update an application's configuration or a Virtual IP (VIP) to point to the new master.

Q223: Describe "Redis Module" "Key" APIs.​

Modules access keys using RedisModule_OpenKey. This returns an opaque handle that the module uses to read or write the key's value. Using these handles is much faster than calling built-in Redis commands because it avoids the overhead of command parsing and dispatching.

Q224: Explain "Redis Cluster" CLUSTER RESET.​

  • Soft: Clears cluster configuration but keeps data.
  • Hard: (Default) Wipes data, clears cluster config, generates a new node ID, and removes all known nodes. It's the "factory reset" for a cluster node.

Q225: Describe "Redis Stream" XTRIM "Approximate" trimming.​

Using XTRIM stream MAXLEN ~ 1000. The ~ means the trimming is "approximate". Redis will only trim the stream when it can remove an entire internal data block (macro-node). This is much more efficient than precise trimming which would require splitting blocks.

Q226: Explain "Sorted Set" ZADD "Updates" vs "Inserts".​

ZADD returns the number of new elements added. If you update the score of an existing member, it returns 0 (by default). You can use the CH (changed) flag to make it return the total number of members that were either added or updated.

Q227: What is "Redis Sentinel" parallel-syncs impact on availability?​

Setting parallel-syncs to 1 ensures that only one replica is offline at a time while syncing with the new master. This maintains the read availability of the other replicas during the failover process, which is critical for large clusters.

Q228: Describe "Redis Module" "Blocked Client" APIs.​

Modules can block a client (e.g., waiting for an external network response) without blocking the entire Redis server. The module provides a callback that Redis will execute once the data is ready, allowing for highly efficient, asynchronous module logic.

Q229: Explain "Redis Cluster" cluster-allow-reads-when-down.​

If set to yes, nodes will continue to serve read queries even if the cluster is in a failed state (e.g., too many nodes are down). This provides "availability over consistency" during major infrastructure outages.

Q230: Describe "Redis Stream" XREAD "Timeout 0" risks.​

A timeout of 0 means the client will block indefinitely. If many clients do this on an idle stream, they will consume many open file descriptors and a small amount of memory. In a large system, it's usually better to use a reasonable timeout to allow for connection rotation and cleanup.

Q231: Explain "Sorted Set" ZRANGE "BYSCORE" performance.​

Finding the score range is $O(\log N)$ using the Skip List. Then, traversing the range is $O(M)$. This is the most efficient way to query time-series data where the score is a timestamp.

Q232: What is "Redis Sentinel" INFO gathering frequency?​

Sentinels query the master every 10 seconds (or every 1 second if the master is down) to get the list of replicas and their current offsets. This is how Sentinels keep their view of the cluster topology up-to-date.

Q233: Describe "Redis Module" "Dictionary" APIs.​

Modules can create their own private dictionaries (separate from the main Redis keyspace) to store internal metadata or state. These dictionaries provide $O(1)$ lookup and can be used to implement complex internal logic.

Q234: Explain "Redis Cluster" cluster-migration-barrier tuning.​

Setting this to a higher value ensures that masters always have a "spare" replica. This makes the cluster more resilient to multiple hardware failures but requires more physical resources (more replicas in total).

Q235: Describe "Redis Stream" XREPLY (conceptual).​

While not a command, it refers to how consumers respond to events. A common pattern is to include a reply_to stream ID in the message metadata, allowing for request-response patterns over Redis Streams.

Q236: Explain "Sorted Set" ZMSCORE (Redis 6.2+).​

Returns the scores of multiple members of a Sorted Set in a single call. This is much more efficient than calling ZSCORE multiple times, especially over a slow network.

Q237: What is "Redis Sentinel" AUTH for Sentinels?​

Sentinels can be configured to use a password when connecting to each other and to the masters. This is a critical security layer in environments where the internal network might be compromised.

Q238: Describe "Redis Module" "Thread Safe" context.​

If a module uses its own background threads, it must use the RedisModule_GetThreadSafeContext and RedisModule_ThreadSafeContextLock/Unlock functions to safely interact with the Redis core data structures without causing race conditions.

Q239: Explain "Redis Cluster" cluster-replica-no-failover.​

If set to yes, a specific replica will never try to promote itself to master. This is useful for replicas that are used purely for backups or slow analytical queries and aren't powerful enough to handle primary traffic.

Q240: Describe "Redis Stream" XCLAIM "Force" flag.​

The FORCE flag allows a consumer to claim a message even if it wasn't currently in any consumer's PEL. This can be used to manually re-assign or "rescue" messages that have been lost in the system due to low-level metadata issues.

Q241: Explain "Sorted Set" ZRANK "By Score" (Redis 7.2+).​

The BYSCORE argument in ZRANK allows you to find the rank of the first member that has a score within a specific range, even if you don't know the member's name. This is a powerful new tool for analytical queries.

Q242: What is "Redis Sentinel" static-conf-file?​

In modern cloud environments, Sentinel configuration is often managed by tools like Terraform or Kubernetes. static-conf-file tells Sentinel not to overwrite its own config file with the discovered topology, allowing for better configuration management.

Q243: Describe "Redis Module" "Event" loop integration.​

Modules can register file descriptors with the main Redis event loop. When data is available on the descriptor, Redis will call the module's callback. This allows modules to implement their own low-level networking or IPC protocols efficiently.

Q244: Explain "Redis Cluster" cluster-announce-hostname.​

Nodes in a cluster can now advertise their hostname instead of just their IP. This is essential for environments like Kubernetes where pods have stable hostnames but dynamic internal IPs.

Q245: Describe "Redis Stream" XAUTOCLAIM (Redis 6.2+).​

This command combines XPENDING and XCLAIM into a single atomic operation. It allows a consumer to automatically find and claim stale messages that have been pending for longer than a specified time, making consumer recovery much simpler.

Q246: Explain "Sorted Set" ZDIFF and ZDIFFSTORE.​

Calculates the difference between multiple Sorted Sets. Members are kept only if they are present in the first set but none of the others. This is a powerful tool for implementing complex filtering logic on ranked data.

Q247: What is "Redis Sentinel" announce-ip?​

In a multi-homed server or a container environment, Sentinel might not know which IP to tell other Sentinels to use. announce-ip allows you to explicitly set the IP address that this Sentinel will advertise to the rest of the system.

Q248: Describe "Redis Module" "String" APIs.​

Modules can create and manipulate "Redis Module Strings". These are highly optimized string objects that can be shared between the module and the Redis core without copying, maximizing performance for string-heavy module logic.

Q249: Explain "Redis Cluster" cluster-preferred-endpoint-type.​

Allows you to tell clients which address they should use to connect to the node: the advertised IP, the advertised hostname, or an "unknown" type for custom routing. This provides flexibility for complex networking architectures.

Q250: Describe "Redis Stream" XSETID.​

Allows you to manually set the "Last ID" of a stream. This is a dangerous but necessary "repair" tool for fixing streams that have become inconsistent or for manually resetting a stream's history.

6. Legendary Level Redis - The Ultimate Architecture Pack​

Q251: Explain "Redis Functions" (Redis 7.0+).​

Redis Functions are an evolution of Lua scripts. Instead of sending raw code with every request, you define a library of named functions on the server.

  • Libraries: Functions are grouped into libraries.
  • Persistence: Libraries are stored in the RDB/AOF and replicated to slaves.
  • Benefit: Much cleaner management of server-side logic compared to ephemeral scripts. It enables a "Stored Procedure" style of development for Redis.

Q252: Describe "Redis Cluster" "Partial Resync" (PSYNC2) logic.​

PSYNC2 allows a replica to perform a partial resync even if it has changed its master (e.g., after a failover). It uses the replid and replid2 fields to determine if the replica's history matches the new master's history. This prevents massive data transfers after every master switch in a large cluster.

Q253: What is "Redis Sentinel" rename-command security risk?​

While renaming dangerous commands in redis.conf is good for security, you must also tell Sentinel about the new names. If Sentinel tries to run CONFIG on a master where that command has been renamed, and it doesn't know the new name, the Sentinel will fail to monitor the node properly.

Q254: How do you handle "Redis memory fragmentation" in a Virtualized environment?​

In VMs or cloud instances, the memory allocator's behavior can be affected by the hypervisor's memory management (e.g., memory ballooning).

  • Optimization: Use jemalloc (the default) and ensure activedefrag is enabled.
  • Warning: Avoid using transparent huge pages (THP) in the OS, as they can cause significant latency spikes and increased memory fragmentation for Redis.

Q255: Describe the "Redis Stream" XREAD vs XREADGROUP internal latency.​

  • XREAD: A direct look-up on the stream. Very low latency.
  • XREADGROUP: Requires updating the consumer's PEL (Pending Entries List) and the group's "Last Delivered ID". This involves more memory operations and slightly higher latency, but provides reliability.

Q256: Explain "Redis Module" "Post-Command" hooks.​

Modules can register hooks that run immediately after a built-in Redis command finishes. This allows for powerful features like real-time data replication to external systems or implementing custom cross-key constraints within the Redis process.

Q257: What is "Redis Sentinel" resolve-hostnames (Redis 6.2+)?​

Historically, Sentinels only used IP addresses. Redis 6.2 introduced the ability for Sentinels to resolve hostnames. This is essential for modern environments where IPs are dynamic but hostnames are stable (like Kubernetes or service discovery systems).

Q258: Describe "Redis Cluster" "Scale-In" (Removing nodes) safely.​

  1. Use CLUSTER REPLICATE to move any replicas off the node being removed.
  2. Use resharding to move all 16384/N hash slots from the master to other nodes.
  3. Once the node has 0 slots, use CLUSTER FORGET on all other nodes in the cluster.
  4. Finally, shut down the node.

Q259: Explain "Sorted Set" "Lexicographical Search" with Unicode.​

Sorted Sets order members by raw byte values. For simple ASCII, this matches dictionary order. For Unicode (UTF-8), the ordering will follow the binary representation of the characters, which might not match the linguistic sort order of every language. Always test your prefix searches with the actual data types you expect.

Q260: How do you implement "Distributed Priority Queues" with Redis ZSets?​

  1. Push: ZADD queue <priority_score> <message_body>.
  2. Pop: A Lua script that calls ZRANGE queue 0 0, processes the message, and then calls ZREM.
  3. Optimized Pop: In Redis 6.2+, use ZMPOP or BZMPOP which can atomically pop the element with the lowest/highest score, avoiding the need for a Lua script.

Q261: Describe "Redis Persistence" "Sync" vs "Async" AOF.​

  • Sync: appendfsync always. The client blocks until the data is flushed to physical disk.
  • Async: appendfsync everysec. Redis flushes in a background thread once per second. The "Async" mode is 100x faster but carries a small risk of data loss. "Sync" is extremely slow because it's limited by disk I/O latency.

Q262: What is the "Redis Cluster" cluster-replica-validity-factor tuning?​

If you have a very unstable network, you might want to increase this factor to prevent replicas from being disqualified too easily. If you have a rock-solid network, you can decrease it to ensure that only the most perfectly synced replicas can ever become masters.

Q263: Explain "Redis Tracking" "Redirect" for WebSocket proxies.​

In a high-scale architecture, you might have a pool of WebSocket servers (proxies) that handle client connections. These proxies can use CLIENT TRACKING on REDIRECT <their_id> to receive invalidation messages from Redis and then propagate them only to the clients that actually need them, reducing the total bandwidth used for cache invalidation.

Q264: Describe "Redis Stream" XTRIM "MINID" strategy.​

Instead of trimming by length (MAXLEN), you can trim by message ID (MINID). This allows you to implement "Time-Based Retention" (e.g., deleting all messages older than 24 hours) by calculating the minimum allowed ID based on the current timestamp.

Q265: What is "Redis Sentinel" announce-port?​

Similar to announce-ip, this allows a Sentinel to tell other Sentinels which port they should use to reach it. This is crucial when running multiple Sentinels on the same physical host using different Docker port mappings.

Q266: Explain "Memory Usage" of "Hashes" with many small fields.​

Redis stores small hashes in a listpack. If you have millions of hashes each with 2 fields, the overhead of the key in the main dictionary can be larger than the hash data itself. In such cases, it's often more efficient to consolidate them into fewer, larger hashes.

Q267: Describe "Redis Cluster" CLUSTER KEYSLOT command.​

A simple utility that calculates the hash slot (0-16383) for a given key string. It follows the CRC16 algorithm and handles hash tags {...} correctly. It's used by client libraries to implement the routing bitmask.

Q268: What is "Redis Sentinel" parallel-syncs trade-off?​

  • Low (1): High availability for reads (only one replica offline at a time) but slow failover for the entire cluster.
  • High (N): Fast cluster-wide recovery but causes a temporary outage for all read operations as all replicas sync with the new master simultaneously.

Q269: Explain "Redis Modules" "Info" callback.​

A module can provide a function that adds custom sections to the standard INFO command. This is essential for monitoring module-specific metrics like "JSON documents processed" or "Search queries per second" using existing Redis monitoring tools.

Q270: Describe "Redis Cluster" cluster-migration-barrier defaults.​

The default is 1. This means as long as a master has at least 2 replicas, it's willing to give one up to help an orphan master. Setting it to 0 makes it extremely aggressive (leaving masters with no replicas). Setting it very high disables replica migration entirely.

Q271: Explain "Sorted Set" ZRANGE "BYLEX" performance.​

Since the members are stored in a Skip List, lex queries have $O(\log N)$ complexity to find the start point. This makes it just as fast as score-based searching. It's a "hidden gem" for implementing fast filtering and sorting on string data.

Q272: What is the "Redis Sentinel" sentinel monitor syntax?​

sentinel monitor <master-name> <ip> <port> <quorum>. This is the core command that defines which Redis master a Sentinel should watch. The "master-name" is used to identify the cluster across all Sentinels and clients.

Q273: Describe "Redis Module" "Subscription" APIs.​

Modules can subscribe to "Key-space Notifications". They receive a callback whenever a specific event happens in Redis (e.g., a key is deleted or an expire is set). This allows modules to implement complex side-effects based on standard Redis operations.

Q274: Explain "Redis Cluster" cluster-require-full-coverage.​

  • yes (Default): If any hash slot is not owned by a healthy master, the entire cluster reports as failed and stops accepting queries.
  • no: The cluster continues to work as long as at least one node is healthy, though queries for the missing slots will fail.

Q275: Describe "Redis Stream" XREAD vs XREADGROUP throughput.​

XREAD has much higher throughput because it doesn't perform any writes to the stream metadata. XREADGROUP is slower because every read is essentially a write operation (updating the PEL). Always use standard XREAD if you don't need the reliability features of consumer groups.

Q276: Explain "Sorted Set" ZADD "In-place updates".​

If a member already exists and its score changes, Redis must move it within the Skip List. This is an $O(\log N)$ operation. If the score doesn't change, the update is nearly $O(1)$. This is why updating scores in a ZSet is significantly faster than deleting and re-inserting.

Q277: What is the "Redis Sentinel" sentinel down-after-milliseconds impact?​

If this is set to 30s, and a master fails, the Sentinel will take 30s to detect the failure. Then it needs another few seconds for quorum agreement and leader election. Total downtime for the master will be ~35-40 seconds. Reducing this value reduces downtime but increases the risk of false positives.

Q278: Describe "Redis Module" "Memory Allocation" wrappers.​

Modules must use RedisModule_Alloc and RedisModule_Free instead of standard malloc/free. These wrappers ensure that module memory usage is correctly tracked by the Redis core and reported in INFO MEMORY.

Q279: Explain "Redis Cluster" cluster-announce-bus-port.​

The "Bus Port" is used for node-to-node gossip communication. By default, it's the client port + 10000. In complex network setups (firewalls, NAT), you might need to map this port explicitly to ensure the nodes can talk to each other.

Q280: Describe "Redis Stream" XREAD "Multiple Streams" support.​

A single XREAD call can monitor multiple streams at once. It will block until a message arrives in any of the specified streams. This allows a single consumer thread to handle multiple event types efficiently.

Q281: Explain "Sorted Set" ZRANGESTORE (Redis 6.2+).​

A combination of ZRANGE and SET. It calculates a range and stores it in a new key in a single atomic operation. This is useful for creating "filtered snapshots" of large leaderboards or datasets for fast access by other clients.

Q282: What is "Redis Sentinel" sentinel-user?​

You can configure a specific ACL user for Sentinel to use when connecting to other Sentinels and masters. This allows you to apply the "Least Privilege" principle to the high-availability infrastructure itself.

Q283: Describe "Redis Module" "Scan" APIs.​

Modules can implement their own SCAN-style iterators for their custom data types. This ensures that even massive custom objects can be traversed in small, non-blocking steps, maintaining the overall responsiveness of the Redis server.

Q284: Explain "Redis Cluster" cluster-allow-pubsub-shard-only.​

Introduced in Redis 7.0, this restricts Pub/Sub messages to the specific shard where they were published. This significantly improves Pub/Sub performance in massive clusters by avoiding the need to broadcast every message to every single node.

Q285: Describe "Redis Stream" XPENDING "Summary" vs "Detailed".​

  • Summary: Returns total count, min/max ID, and count per consumer. Fast.
  • Detailed: Returns every single pending message ID, its owner, and its idle time. Slow on large PELs, but necessary for manual recovery logic.

Q286: Explain "Sorted Set" ZREM performance.​

Deleting from a ZSet is $O(\log N)$ because it requires searching the Skip List and the Hash Table. It is very efficient even for sets with millions of members, as the search time grows very slowly with the size of the set.

Q287: What is "Redis Sentinel" sentinel failover-timeout?​

If a failover doesn't complete within this time, Sentinel will abort the attempt and try again later (or another Sentinel will take the lead). It's a safety mechanism to prevent the cluster from getting stuck in an intermediate state.

Q288: Describe "Redis Module" "Cluster" APIs.​

Modules can be "Cluster-aware". They can use Redis APIs to find which node owns a specific slot or to register their own cluster-wide state that is shared among all nodes in the cluster.

Q289: Explain "Redis Cluster" cluster-announce-tls-port.​

In Redis 7.0, nodes can advertise their TLS port separately. This allows for clusters where some connections (like internal gossip) happen over plaintext for speed, while client connections are forced to use TLS for security.

Q290: Describe "Redis Stream" XGROUP SETID.​

Allows you to change the "Last Delivered ID" of an existing consumer group. You can move it forward (skipping messages) or backward (replaying history). It's a powerful tool for correcting errors in event processing.

Q291: Explain "Sorted Set" ZINTER vs ZINTERSTORE.​

ZINTER (Redis 6.2+) returns the result directly to the client, while ZINTERSTORE saves it to a key. Use ZINTER when you only need the result once, to save memory and avoid the overhead of a write operation.

Q292: What is "Redis Sentinel" sentinel config-rewrite?​

Sentinel automatically writes its current state (discovered replicas, leader status, etc.) back to its configuration file. This ensures that if the Sentinel process restarts, it doesn't have to start the discovery process from scratch.

Q293: Describe "Redis Module" "RDB Save" types.​

Modules can save data as raw binary blobs or using "AOF-style" command sequences. The RDB format is usually preferred for speed, while AOF commands are easier to debug and more flexible for minor version changes.

Q294: Explain "Redis Cluster" cluster-replica-validity-factor calculation.​

The factor is multiplied by cluster-node-timeout. If the timeout is 5s and the factor is 10, a replica that has been disconnected for more than 50s is considered "too old" to become a master.

Q295: Describe "Redis Stream" XREADGROUP "BLOCK" timeout logic.​

If a timeout is reached, XREADGROUP returns an empty list. Crucially, the consumer remains part of the group. This is the recommended way for workers to "wait" for new work in a shared processing queue.

Q296: Explain "Sorted Set" ZLEXCOUNT.​

Returns the number of members in a Sorted Set between two lexicographical bounds. This is $O(\log N)$ and is much faster than fetching the range and counting the elements in the application.

Q297: What is "Redis Sentinel" sentinel flush-config?​

Forces Sentinel to write its entire current state to disk immediately. This is often used before an planned maintenance window to ensure the persisted configuration is up-to-date.

Q298: Describe "Redis Module" "Blocking Keys" APIs.​

Modules can implement their own blocking commands (similar to BRPOP). They specify which key they are waiting for, and Redis will automatically wake up the client when that key is modified, allowing for custom high-performance concurrency primitives.

Q299: Explain "Redis Cluster" cluster-migration-barrier for high availability.​

By setting this to 2, you ensure that every master has at least one backup replica left after a migration. This protects the cluster from data loss in case of a second, near-simultaneous hardware failure.

Q300: Describe "Redis Stream" XAUTOCLAIM "Count" parameter.​

This parameter limits the number of messages reclaimed in a single step. This prevents a recovering consumer from being overwhelmed by a massive burst of stale messages all at once, allowing for a more gradual, controlled recovery.

7. Redis Performance Engineering - The Deep Dive Pack​

Q301: What is "Redis Sharded Pub/Sub" (Redis 7.0+)?​

In traditional Redis Pub/Sub, every message is broadcast to every node in the cluster, which doesn't scale well.

  • Mechanism: Messages are routed only to the node that owns the hash slot of the channel name.
  • Benefit: Linear scalability of Pub/Sub throughput with the number of nodes.
  • Commands: Use SSUBSCRIBE and SPUBLISH instead of the standard versions.

Q302: Explain the "Redis Object" (robj) structure.​

Every value in Redis is wrapped in a redisObject struct.

  • type: The high-level data type (string, list, etc.).
  • encoding: The internal representation (ziplist, hashtable, etc.).
  • lru: 24 bits for the LRU/LFU metadata.
  • refcount: For memory sharing of small integers (0-9999).
  • ptr: Pointer to the actual data. Understanding this structure is key to understanding Redis memory overhead.

Q303: How do you use redis-cli --intrinsic-latency?​

This tool measures the latency introduced by the operating system kernel and hypervisor rather than Redis itself. It runs a tight loop for a few seconds and reports the maximum delay encountered. This defines the "latency floor" of your hardware; Redis can never be faster than this.

Q304: Describe the "Multi-Part AOF" (Redis 7.0+).​

Redis 7.0 split the AOF into multiple files: a base file (snapshot) and multiple incremental files.

  • Benefit: Makes the AOF rewrite process much more efficient and robust. It eliminates the need for the complex "AOF buffer" during rewrites and makes recovery faster.

Q305: Explain "Command Hints" (Redis 7.0+).​

Command hints allow a Redis server to provide metadata to client libraries about how to handle specific commands (e.g., which keys they access). This allows for smarter client-side routing and better support for future Redis features without needing a library update.

Q306: What is the purpose of server.hz?​

The hz parameter defines how many times per second Redis performs internal background tasks (like active expiry and rehashing). The default is 10. Increasing it makes Redis more responsive to expiry but consumes slightly more idle CPU.

Q307: How do you handle "Small Object Memory Overhead" with pointers?​

On a 64-bit system, every pointer consumes 8 bytes. For small objects, this overhead is significant. Redis uses "Compressed Pointers" (encoded as offsets) in structures like listpack to avoid this cost, which is one reason why it's so memory-efficient.

Q308: Describe "Redis Sentinel" leader-epoch vs config-epoch.​

  • leader-epoch: Used during the election of a Sentinel leader.
  • config-epoch: The version of the master/replica topology. By separating these two, Sentinels can agree on a leader quickly even if they haven't yet agreed on the final cluster state.

Q309: Explain "Sorted Set" "Level" distribution in Skip Lists.​

Redis uses a random function to determine the "level" of each new node in a Skip List. The probability of a node having a level $N$ is $(1/4)^{N-1}$. This ensures that the list remains balanced on average, providing $O(\log N)$ search time with very low overhead.

Q310: What is "Diskless Loading"?​

Normally, a replica saves the received RDB to disk before loading it.

  • Diskless Loading: (Redis 6.0+) The replica parses the RDB stream directly from the socket and populates its memory.
  • Benefit: Much faster synchronization for replicas with slow disks or when running in diskless environments (containers).

Q311: How do you implement "API Rate Limiting" with GETSET?​

While GETSET is deprecated in favor of SET ... GET, the pattern is classic:

  1. INCR counter.
  2. If counter is 1, EXPIRE counter 60.
  3. If counter > limit, reject. Using a Lua script to combine these steps into one atomic operation is the modern best practice.

Q312: Describe "Physical Replication" "Heartbeat" logic.​

Replicas send REPLCONF ACK <offset> to the master every second. This serves as a heartbeat and tells the master exactly how much data the replica has processed. The master uses this to decide if a replica is "lagging" or "offline".

Q313: Explain "Index De-duplication" "Space Savings".​

In a B-tree index, repeating the same key for multiple rows is wasteful. Redis's de-duplication stores the key once followed by a compressed list of row IDs. For columns with many duplicates, this can reduce index size by over 50%.

Q314: What is the "Active Defrag" "Cycle" strategy?​

The defragmenter uses a "minimum" and "maximum" CPU percentage. It starts at the minimum and increases its activity if fragmentation is high, but always stays below the maximum to ensure that user commands remain prioritized.

Q315: How do you implement "Event Sourcing" with Redis Streams?​

  1. Append: Every state change is written as a message to a stream.
  2. Replay: To rebuild the state, a consumer reads the stream from ID 0-0.
  3. Snapshots: Periodically save the current state to a standard Redis key so you don't have to replay the entire history every time.

Q316: Explain "Lua Script" "Global Variable" restriction.​

Redis prevents Lua scripts from creating global variables. This is because globals persist between script executions, which would lead to unpredictable behavior and make scripts non-deterministic (breaking replication). Always use local variables.

Q317: Describe the "TOAST"-like behavior in Redis (conceptual).​

While Redis doesn't have TOAST, it handles large values by using different encodings. A massive String will eventually be stored as a raw, contiguous buffer, while a large Hash will be stored as a complex hash table. The key difference is that Redis always keeps the entire value in RAM.

Q318: What is "JIT" in the context of Redis? (Hint: it's not core).​

Standard Redis doesn't use JIT. However, modules like RedisJSON or RediSearch might use JIT (often via LLVM) to compile complex path queries or search expressions into machine code for maximum performance.

Q319: How do you handle "Slot Migration" in a saturated cluster?​

If a node is at 100% CPU, migrating slots will be slow.

  • Optimization: Use MIGRATE with a large COUNT parameter to move many keys in a single network round-trip.
  • Tuning: Increase the timeout to avoid migration failures due to CPU starvation.

Q320: Explain "Physical Replication" "Streaming" vs "RDB".​

  • RDB: Used for the initial "Full Sync".
  • Streaming: Once the replica has the snapshot, the master sends a continuous stream of new write commands as they happen. This is what keeps the replica "live".

Q321: What is the "Redis Sentinel" down-after vs failover-timeout?​

  • down-after: Time to detect a failure.
  • failover-timeout: Time allowed for the promotion process to complete. If promotion takes too long (e.g., due to a slow sync), the failover is considered failed.

Q322: Describe "Logical Decoding" (conceptual) for Redis.​

While "Logical Decoding" is a Postgres term, Redis achieves the same result using Keyspace Notifications. You can configure Redis to publish a message to a channel whenever a key is touched by a specific command (e.g., SET, DEL).

Q323: Explain "Bitmap Index" "Bit Position" limits.​

Since Redis strings are limited to 512MB, a single bitmap can store $512 \times 1024 \times 1024 \times 8 \approx 4.29$ billion bits. This is exactly enough to handle a 32-bit integer range (like IPv4 addresses or standard user IDs).

Q324: How do you implement "Global ID Generation" with INCR?​

In a cluster, use different starting offsets:

  • Node 1: INCRBY id 10 (starts at 1) -> 1, 11, 21...
  • Node 2: INCRBY id 10 (starts at 2) -> 2, 12, 22... This ensures unique IDs across nodes without any coordination or network overhead.

Q325: Describe "Partial Index" (conceptual) in Redis.​

You can emulate partial indexes by using separate Sorted Sets. For example, instead of one massive users:score set, have one users:score:active and another users:score:inactive. This makes queries on "active" users much faster.

Q326: Explain "External Row Storage" (conceptual) for massive blobs.​

If you need to store multi-GB files, don't put them in Redis (limit is 512MB). Store the file in S3 and store the S3 URL and metadata in a Redis Hash. Use Redis for the fast lookup and S3 for the large-scale storage.

Q327: What is the "Search Path" (conceptual) for Redis Modules?​

When you call a module command, Redis first checks the built-in commands. If not found, it checks the commands registered by all loaded modules. If there's a conflict, the first module loaded "wins".

Q328: Describe "Parallel Execution" (conceptual) in Redis 6.0+.​

Redis is "Parallel for I/O" but "Serial for Logic". This is a conscious design choice: serial logic is easier to write, easier to debug, and avoids 99% of the race conditions that plague other databases.

Q329: Explain "GiST"-like (conceptual) indexing in Redis.​

Redis's Geospatial indexes (GEOADD, etc.) use a technique called Geohashing. A 2D coordinate is converted into a 1D string (a "hash"). These strings have the property that points close together have similar prefixes, allowing them to be stored and searched efficiently in a standard Sorted Set.

Q330: How do you use redis-benchmark to find bottlenecks?​

Run with the -q (quiet) and -c (connections) flags. If increasing -c doesn't increase requests-per-second, your bottleneck is likely the server's CPU or the network latency, not the client's ability to send requests.

Q331: Describe "Redis Stream" "Consumer Group" "Lag" monitoring.​

Lag is the number of messages in the stream that haven't been delivered to any consumer in the group. You can calculate this by comparing the stream's "last generated ID" with the group's "last delivered ID" using the XINFO command.

Q332: Explain "Index Re-duplication" "Memory vs CPU" trade-off.​

De-duplication saves significant memory but adds a small CPU cost during insertion and search, as the posting list must be uncompressed or traversed. In most Redis workloads, memory is the bottleneck, so this trade-off is usually a win.

Q333: What is the "Hint Bit" (conceptual) in Redis?​

Redis uses "Flags" in the internal object structure to mark things like "this string is actually an integer" or "this hash is currently a ziplist". This allows the server to skip expensive type-checking and conversion logic during every command.

Q334: Describe "Foreign Data Wrapper" (conceptual) for Redis.​

Redis can't natively query other databases. However, you can use a Lua script or a Module as a "proxy". The script makes an HTTP call to an external service or database and then processes the result directly inside Redis.

Q335: Explain "Operator Overloading" (conceptual) in Redis.​

While you can't overload standard operators, you can use Redis Modules to define entirely new commands that behave like operators for custom types (e.g., JSON.SET, JSON.GET, TS.ADD).

Q336: How do you implement "Sharding" for "Real-time Chat"?​

Shard by room_id. All messages for a room go to the same Redis node. This allows for atomic updates to the room's message list and ensures that Pub/Sub messages for that room are handled efficiently.

Q337: Describe "Logical Decoding" (conceptual) for "Database Sync".​

Use Redis Streams. Have every writer append their changes to a stream. A background process "decodes" this stream and applies the changes to your primary database (e.g., Postgres). This provides an asynchronous, high-performance way to keep two systems in sync.

Q338: Explain "Expression Indexes" (conceptual) with Lua.​

You can pre-calculate expressions and store them in a Sorted Set. For example, if you often query WHERE (price * tax) > 100, create a ZSet where the score is price * tax. This allows you to perform indexed searches on the result of the expression.

Q339: What is the "Lock Manager" (conceptual) in Redis?​

Redis has no "Lock Manager" for rows because its core is single-threaded. This is its greatest performance advantage: it never has to wait for a lock because no other thread is allowed to touch the data while a command is running.

Q340: Describe "Parallel Hash Join" (conceptual) for Redis.​

Since Redis doesn't support joins, you must perform them in the application or a Lua script. To "parallelize" this, have multiple application workers fetch the data from Redis concurrently and then perform the join logic in parallel in the application layer.

Q341: Explain "Full Page Writes" (conceptual) for "Persistence".​

In RDB persistence, Redis writes the entire dataset to a new file. This is essentially a "Full Page Write" for the entire database. This is why RDB is so robust: a failed save never corrupts the old, valid snapshot.

Q342: How do you use redis-cli --bigkeys for "Memory Recovery"?​

Identify the 10 largest keys. For each key, determine if its data is still needed. If not, use UNLINK to delete it without blocking the server. This is the fastest way to reclaim large amounts of memory in a saturated instance.

Q343: Describe "Redis Sentinel" "SDown" vs "ODOWN".​

  • SDOWN (Subjectively Down): A single Sentinel thinks the master is down.
  • ODOWN (Objectively Down): A quorum of Sentinels agree the master is down. A failover only starts when a master is ODOWN.

Q344: Explain "GIN Index" (conceptual) for "Tag Searching".​

Use Sets. Create one Set for every tag (e.g., tag:python). The members are the IDs of the items with that tag. To find items with multiple tags, use SINTER. This is the exact logical equivalent of a GIN index but implemented with native Redis sets.

Q345: What is the "Background Writer" (conceptual) for "Memory Management"?​

Redis's Active Defragmenter acts as a background writer for memory. It finds fragmented pages and "rewrites" them to more compact locations, ensuring that the physical memory usage (RSS) stays close to the actual data size.

Q346: Describe "Table Inheritance" (conceptual) in Redis.​

You can use Hashes with a "parent" field. To "inherit" values, your application first checks the child hash. If the field is missing, it follows the "parent" link to the parent hash. This allows you to implement complex hierarchical configuration systems.

Q347: Explain "GiST" (conceptual) for "Range Overlap" queries.​

Use Sorted Sets with a bit of math. For a range [start, end], store it as a member with start as the score. Finding overlaps requires querying for all ranges where start < search_end and then filtering those where end > search_start.

Q348: How do you implement "Zero-Downtime" "Redis Cluster" expansion?​

  1. Add new nodes to the cluster (CLUSTER MEET).
  2. Use a script to move hash slots from the old nodes to the new ones.
  3. Redis Cluster automatically handles the redirection (MOVED) during the migration, ensuring the application never sees an error.

Q349: Describe "Logical Decoding" (conceptual) and "Cache Invalidation".​

Use Redis Pub/Sub. When your database updates, have a trigger publish the ID of the changed record to a Redis channel. Your application listens on that channel and removes the corresponding item from its local cache.

Q350: Explain "B-Tree Index" (conceptual) "Internal Nodes" in Redis.​

Redis's Sorted Sets use a Skip List, which is a "probabilistic B-tree". The "Internal Nodes" are the upper layers of the skip list that allow the search to "jump" over large sections of the dataset, providing the same $O(\log N)$ performance as a traditional B-tree.

8. Redis Performance and Architecture Final Pack​

Q351: Explain the "Redis Object" (robj) reference counting mechanism.​

Redis uses a simple reference counting system for memory management of string objects. For example, if you set multiple keys to the same small integer (0-9999), Redis won't create multiple copies in memory. Instead, it creates one object and increments its refcount. This saves a significant amount of memory for commonly used numerical IDs.

Q352: Describe the "Redis Stream" XREADGROUP "Idle Time" tracking.​

Each entry in a consumer group's Pending Entries List (PEL) includes the timestamp of the last time it was delivered. You can use XPENDING to see the "Idle Time" of each message. If a message has been idle for too long, it indicates that the consumer responsible for it has likely crashed or hung, triggering recovery logic.

Q353: What is "Redis Cluster" "Blackout" during failover?​

When a master fails, its hash slots are unavailable until a replica is promoted. This "Blackout" typically lasts for cluster-node-timeout plus a few seconds for the election. During this time, any write or read query for those slots will return a CLUSTERDOWN error.

Q354: How do you handle "Redis slowlog" overflow?​

The slowlog is stored in a circular memory buffer of a fixed size (slowlog-max-len). Once full, the oldest entries are discarded. In high-traffic environments, you should use a background process to periodically fetch the slowlog entries and save them to a permanent log file or monitoring system for long-term analysis.

Q355: Describe the "Redis Bloom Filter" "Scaling" strategy.​

Standard Bloom filters have a fixed capacity. If you add more elements than planned, the error rate will increase. The RedisBloom module supports "Scalable Bloom Filters": when one filter fills up, it creates a new, larger filter. The check operation then checks all the filters in the chain.

Q356: Explain "Redis Module" "Command Filter" implementation.​

A module can register a filter that intercepts every command sent by a client. The filter can modify the command arguments, prevent the command from running, or even execute extra logic after the command finishes. This is a very powerful way to implement transparent data masking or auditing.

Q357: What is the purpose of the "Redis Sentinel" failover-timeout internal state?​

The failover-timeout is not just a hard deadline. It's also used to prevent Sentinels from "stepping on each other's toes". If a Sentinel starts a failover, no other Sentinel will try to fail over the same master until the timeout has passed, ensuring a single, coordinated promotion process.

Q358: Describe "Redis Cluster" "Master-Slave" locality.​

In a well-configured cluster, you should ensure that a master and its replicas are not running on the same physical hardware (e.g., different racks or different availability zones). Redis Cluster itself doesn't enforce this; it's up to the infrastructure orchestration (like Kubernetes anti-affinity rules) to ensure true high availability.

Q359: Explain "Sorted Set" "Reverse Range" performance.​

Because the Skip List is dually-linked at the bottom level, traversing it backwards (ZREVRANGE) is just as fast as traversing it forwards (ZRANGE). Both are $O(\log N + M)$ operations. This makes Sorted Sets excellent for both "Top 10" and "Bottom 10" style queries.

Q360: How do you implement "Distributed Rate Limiting with Penalty"?​

  1. Limit Check: Use the standard sliding window with a Sorted Set.
  2. Penalty: If a user exceeds the limit, set a "block" key with a TTL.
  3. Check: Every request first checks if the "block" key exists. If it does, the request is rejected immediately without even checking the window, saving CPU cycles for malicious traffic.

Q361: Describe "Redis Persistence" "Incremental AOF" benefits.​

Incremental AOF (introduced in Redis 7.0) avoids the need to rewrite the entire AOF file every time. It keeps a base file and a series of small, append-only files. This drastically reduces the disk I/O spikes and the CPU overhead associated with the traditional AOF rewrite process.

Q362: What is the "Redis Cluster" cluster-replica-no-failover use case?​

You might have a replica that is located in a distant data center for DR (Disaster Recovery) purposes. Because of the high latency, you don't want this replica to ever become a master during a normal failover. Setting this flag ensures that only local, low-latency replicas are considered for promotion.

Q363: Explain "Redis Tracking" "Prefix" mode.​

In prefix mode, a client can request to be notified of changes to any key that starts with a specific string (e.g., user_settings:). This is much more efficient than tracking thousands of individual keys, as it reduces the amount of state Redis needs to maintain for each client connection.

Q364: Describe "Redis Stream" XREAD vs XREVRANGE for history.​

  • XREAD: Used for processing new messages in arrival order.
  • XREVRANGE: Used for fetching the most recent history in reverse order (e.g., showing the last 50 messages in a chat room UI). It's much faster than fetching the whole stream and reversing it in the app.

Q365: What is "Redis Sentinel" parallel-syncs impact on network bandwidth?​

If you have a massive dataset and set parallel-syncs to a high number, multiple replicas will start downloading the RDB from the new master at the same time. This can saturate the master's network link, potentially affecting the performance of the actual application traffic. Always tune this based on your network capacity.

Q366: Explain "Memory Usage" of "Sorted Sets" with many small scores.​

Each member in a Sorted Set is stored in both a Hash Table (for $O(1)$ score lookup) and a Skip List (for range queries). This means every member consumes a significant amount of memory for pointers. If you only need to store unique elements without scores, a Set is about 50% more memory-efficient.

Q367: Describe "Redis Cluster" CLUSTER REPLICAS vs INFO REPLICATION.​

  • CLUSTER REPLICAS: Returns the cluster-wide view of which nodes are replicas of which masters based on the gossip protocol.
  • INFO REPLICATION: Returns the low-level socket status of currently connected replicas for the specific node you are talking to. The cluster view is eventually consistent; the INFO view is the immediate reality of that node.

Q368: What is "Redis Sentinel" sentinel monitor "Hostname" support?​

Since Redis 6.2, you can use hostnames instead of IP addresses in the monitor command. This is vital for environments where the Redis server's IP might change (e.g., after a pod restart in Kubernetes), but the internal DNS name remains the same.

Q369: Explain "Redis Modules" "Context" safety.​

When a module callback is executed, it is given a RedisModuleCtx. This context represents the state of the current command execution. The module must use this context for all interactions with the Redis core to ensure that atomicity, logging, and replication are handled correctly by the server.

Q370: Describe "Redis Cluster" failover-validity-factor tuning for global clusters.​

In a cluster spread across geographic regions, network latency can be high. You should increase the failover-validity-factor to allow replicas that are slightly behind (due to light speed limits) to still be eligible for failover, preventing a scenario where no replica is "fresh" enough to take over.

Q371: Explain "Sorted Set" ZMSCORE vs ZSCORE throughput.​

ZMSCORE is a "vectorized" operation. It reduces the overhead of the Redis command parser and the internal function dispatching logic by processing multiple keys in a single pass. For bulk lookups, it can be 2-3x faster than individual ZSCORE calls.

Q372: What is the "Redis Sentinel" client-reconfig-script environment variables?​

When Sentinel runs this script, it populates environment variables with the master name, the old master's IP/port, and the new master's IP/port. The script can use these to perform actions like updating a local hosts file or notifying a configuration management system.

Q373: Describe "Redis Module" "Low-level" vs "High-level" Key access.​

  • High-level: Using RedisModule_Call to run standard Redis commands. Easy to use but slower.
  • Low-level: Using RedisModule_OpenKey and direct type-specific functions (like RedisModule_ListPop). Harder to write but significantly faster as it avoids the command dispatch layer.

Q374: Explain "Redis Cluster" CLUSTER RESET "Hard" vs "Soft" use cases.​

  • Soft: Use when you want to re-organize the cluster (e.g., moving a node to a different shard) without losing the data currently stored on that node.
  • Hard: Use when a node has become corrupted or when you want to reuse a server for a completely different Redis cluster.

Q375: Describe "Redis Stream" XTRIM "Exact" vs "Approximate" use cases.​

  • Exact: Use when you have a strict legal or business requirement for data retention (e.g., "we must never store more than 10,000 logs").
  • Approximate (~): Use for general performance management. It's much faster because it avoids splitting internal data pages, leading to better overall throughput for the Redis server.

Q376: Explain "Sorted Set" ZADD "NX" and "XX" flags.​

  • NX: Only add new elements. Don't update existing ones.
  • XX: Only update existing elements. Don't add new ones. These flags allow you to implement different business logic (like "only update a score if the user already exists") without having to perform a separate EXISTS check.

Q377: What is "Redis Sentinel" parallel-syncs impact on Master CPU?​

When multiple replicas sync simultaneously, the master must generate and stream multiple copies of the RDB. This is CPU and I/O intensive. If the master is already under heavy load, setting parallel-syncs too high can degrade the performance of the live application traffic.

Q378: Describe "Redis Module" "Authenticating" clients.​

Modules can implement their own custom authentication logic. For example, a module could verify a JWT token from an external identity provider before allowing the client to execute any other commands, providing a bridge between Redis and modern auth systems.

Q379: Explain "Redis Cluster" cluster-migration-barrier for orphan protection.​

Orphan protection is the mechanism that moves a replica from a "healthy" master to a master that has lost all its replicas. The migration-barrier ensures that we don't create a new orphan while trying to fix an old one, maintaining a minimum level of redundancy across the entire cluster.

Q380: Describe "Redis Stream" XREAD "Multiple Streams" ID matching.​

When monitoring multiple streams (e.g., XREAD STREAMS s1 s2 0 0), you must provide a "Last ID" for each stream. Redis will return messages from any stream that has an ID greater than the one provided for that specific stream.

Q381: Explain "Sorted Set" ZMSCORE (Redis 6.2+) implementation.​

Internally, ZMSCORE performs a hash table lookup for every member requested. Since hash table lookups are $O(1)$, the total complexity is $O(M)$ where $M$ is the number of members. It is the most efficient way to get scores for a batch of users.

Q382: What is "Redis Sentinel" sentinel monitor "Quorum" best practices?​

For a cluster of $N$ Sentinels, the quorum should usually be $\lfloor N/2 \rfloor + 1$. This ensures that a majority must agree on a failure, preventing a single faulty Sentinel from triggering a false failover. For 3 Sentinels, a quorum of 2 is the standard.

Q383: Describe "Redis Module" "Automatic Memory Management" (AMM).​

If a module enables AMM for a context, Redis will automatically free any module-allocated strings or objects when the callback function returns. This drastically simplifies module code and prevents the most common types of memory leaks.

Q384: Explain "Redis Cluster" cluster-announce-ip for NAT traversal.​

If your Redis nodes are in a private network but clients connect via a public Load Balancer, the nodes must "announce" the Load Balancer's IP address, not their internal one. This ensures that the MOVED and ASK errors contain an IP that the client can actually reach.

Q385: Describe "Redis Stream" XAUTOCLAIM (Redis 6.2+) "JustID" flag.​

The JUSTID flag tells XAUTOCLAIM to only return the IDs of the reclaimed messages, not the full message bodies. This is much faster and uses less bandwidth if the consumer already knows how to fetch the data from another source or only needs the IDs for logging.

Q386: Explain "Sorted Set" ZDIFF performance.​

ZDIFF is $O(L + (N-K)\log K)$ where $L$ is the number of elements in the first set and $K$ is the size of the subsequent sets. It is highly optimized to use the smallest possible number of Skip List lookups to find the differences, making it very efficient for large-scale data filtering.

Q387: What is "Redis Sentinel" sentinel announce-ip use case?​

If you run Sentinel in a container, it might see its own IP as the container's internal bridge IP (e.g., 172.17.0.x). You must use announce-ip to tell it to advertise the host's actual IP address so that other Sentinels and clients can find it.

Q388: Describe "Redis Module" "Scanning" with RedisModule_Scan.​

This function allows a module to iterate through all keys in a database. It works just like the SCAN command: it returns a cursor and processes a small batch of keys in each call, ensuring that the module can perform global operations without blocking the server.

Q389: Explain "Redis Cluster" cluster-replica-no-failover for "Cold Standbys".​

You might keep a replica in a different region that is running on much cheaper, slower hardware. By setting no-failover, you ensure that this "cold" standby is never promoted to master, where it would be unable to handle the production traffic load.

Q390: Describe "Redis Stream" XSETID "Entries Added" counter.​

XSETID allows you to set the entries-added metadata for a stream. This counter is used by consumers to estimate their "lag" in terms of message count. Manually adjusting this is usually only necessary when performing complex data migrations or stream merging.

Q391: Explain "Sorted Set" ZINTER "Aggregate" methods.​

  • SUM: (Default) Adds the scores of the matching members.
  • MIN: Keeps the lowest score.
  • MAX: Keeps the highest score. This allows you to implement different ranking logic (e.g., "user must have a high score in BOTH category A and B" vs "user needs a high score in EITHER").

Q392: What is "Redis Sentinel" sentinel flush-config frequency?​

Sentinel typically flushes its configuration to disk every time it detects a state change (e.g., a replica's offset changes or a master's status changes). You can also trigger it manually if you've made manual changes to the sentinel.conf file that you want to persist immediately.

Q393: Describe "Redis Module" "Blocking" on "Keys" vs "Clients".​

  • Blocking on Clients: The module itself handles the waiting logic (e.g., waiting for an external network response).
  • Blocking on Keys: The module tells Redis to wake up the client as soon as a specific key is modified. This leverages Redis's built-in signaling system for maximum efficiency.

Q394: Explain "Redis Cluster" cluster-migration-barrier for "Multi-Master" setups.​

While Redis Cluster is multi-master, each master is independent. Orphan protection and the migration barrier work at the shard level (one master and its replicas). They ensure that the redundancy of each shard is maintained, protecting against data loss for any specific subset of the hash slots.

Q395: Describe "Redis Stream" XREADGROUP "Noack" flag.​

The NOACK flag tells Redis that the message should not be added to the consumer's PEL. This is used for "fire-and-forget" style processing within a consumer group, where you want the load-balancing benefits of consumer groups but don't need the reliability of acknowledgments.

ZLEXCOUNT uses the Skip List to find the two boundary nodes. Because the Skip List nodes are linked, it can then count the number of nodes between them in $O(\log N)$ time (by using the "span" of the skip list levels). This is incredibly efficient.

Q397: What is "Redis Sentinel" sentinel auth-pass?​

This is the password the Sentinel uses when connecting to the Redis master and replicas. If your Redis servers require a password (requirepass), you MUST provide the same password to Sentinel using this command, or the Sentinel will be unable to monitor them.

Q398: Describe "Redis Module" "Dictionary" iterators.​

A module can create an iterator for its private dictionaries. This allows the module to process its internal state in small chunks, maintaining the "non-blocking" spirit of Redis even when performing complex internal data management.

Q399: Explain "Redis Cluster" cluster-preferred-endpoint-type for "Hybrid Clouds".​

In a hybrid cloud, some clients might be in the same VPC as Redis (using private IPs), while others are external (using public IPs/Hostnames). This setting allows you to control which address type is returned in the MOVED and ASK errors to ensure all clients can connect.

Q400: Describe "Redis Stream" XSETID "Last ID" vs "Entries".​

When you use XSETID, you define the new "boundary" of the stream. Any messages added after this call will have an ID greater than the one you set. This is a "surgical" operation that should be used with extreme caution as it can break consumer expectations.

9. Redis Ultimate Mastery Pack - The Final 200 Lines​

Q401: Explain the "Redis Object" (robj) type-specific encoding transitions.​

Redis automatically upgrades the encoding of an object as it grows.

  • Hash: Starts as listpack. If it exceeds hash-max-listpack-entries or any value is longer than hash-max-listpack-value, it converts to hashtable.
  • Set: Starts as intset if it only contains small integers. Once it contains a string or exceeds set-max-intset-entries, it converts to hashtable.
  • ZSet: Starts as listpack. Converts to skiplist + hashtable when it gets too large.

Q402: Describe the "Redis Stream" XREADGROUP "History Replay" strategy.​

To replay the entire history for a new consumer group:

  1. Create the group using ID 0.
  2. Consumers call XREADGROUP with ID >. To only process new messages but allow for recovery:
  3. Create the group using ID $.
  4. Consumers use ID > for new work and ID 0 to recover their own pending messages after a crash.

Q403: What is "Redis Cluster" "Manual Failover" "Takeover" mode?​

In "Takeover" mode (CLUSTER FAILOVER TAKEOVER), the replica promotes itself immediately without coordinating with the current master and without waiting for a majority of other masters to vote. This should only be used in extreme disaster recovery scenarios where the rest of the cluster is partitioned or dead.

Q404: How do you handle "Redis memory fragmentation" with MALLOC_CONF?​

If you are using jemalloc (the default), you can provide environment variables to tune its behavior. For example, MALLOC_CONF="narenas:1" can reduce memory overhead in systems with few CPU cores, while other settings can change the decay rate of dirty memory pages to reclaim RAM more aggressively.

Q405: Describe the "Redis Stream" XINFO GROUPS output.​

This command returns a list of all consumer groups for a stream. For each group, it shows the name, the number of consumers, the "pending" count (total messages in all PELs for this group), and the ID of the last message delivered to this group. It's the primary way to monitor group-level lag.

Q406: Explain "Redis Module" "Command Replication" options.​

A module can choose how its commands are replicated:

  • Default: The original command is sent to the AOF and replicas.
  • Verbatim: The command is replicated exactly as received.
  • Effects-based: The module manually emits standard Redis commands (like SET or DEL) to represent the side-effects of the custom module command.

Q407: What is "Redis Sentinel" sentinel monitor "Auth" interaction?​

Sentinel doesn't just need the master's password to connect. It also needs it to reconfigure other nodes. If you have different passwords on different nodes (which is discouraged), Sentinel will struggle to perform a successful failover unless you use the newer ACL-based authentication.

Q408: Describe "Redis Cluster" "Slot Migration" "Async" nature.​

While the MIGRATE command is atomic for a single key, moving a whole slot (which can contain thousands of keys) is a multi-step, asynchronous process managed by an external script or tool (like redis-cli --cluster reshard). The cluster remains fully operational during this process.

Q409: Explain "Sorted Set" "Lexicographical Search" bounds.​

  • (: Exclusive bound (e.g., (apple).
  • [: Inclusive bound (e.g., [apple).
  • -: Negative infinity (start of set).
  • +: Positive infinity (end of set). These symbols allow for precise range control in lexicographical queries, making them much more powerful than simple glob patterns.

Q410: How do you implement "Distributed Semaphores" with "Fairness"?​

  1. Queue: Use a List as a "Wait Queue".
  2. Lock: Use a standard distributed lock for the semaphore state.
  3. Logic: A Lua script pops from the wait queue and grants the semaphore only when a slot is free, ensuring that clients get access in the order they requested it.

Q411: Describe "Redis Persistence" "Fork" failure scenarios.​

If the fork() call fails (e.g., due to ENOMEM), Redis will log a critical error. Crucially, Redis will stop accepting writes if the failure happened during a background save that was configured as "essential". This is a safety mechanism to prevent running a database without any persistence.

Q412: What is the "Redis Cluster" cluster-migration-barrier "Hysteresis"?​

Hysteresis (a lag in reaction) is effectively built into the migration process. Replicas don't instantly migrate as soon as a master becomes an orphan; they wait for a random delay. This prevents multiple replicas from different masters all trying to migrate to the same orphan at the same time.

Q413: Explain "Redis Tracking" "Redirect" for "Nginx" load balancers.​

An advanced pattern where an Nginx proxy (using the njs module or a custom plugin) maintains its own client-side cache. It uses a single connection to Redis with TRACKING on REDIRECT to receive invalidation messages for all the data it has cached across all its incoming client requests.

Q414: Describe "Redis Stream" XREAD vs XREVRANGE memory overhead.​

  • XREAD: Uses a small amount of memory for the blocking client state.
  • XREVRANGE: Requires no extra state, but fetching large ranges can increase the output buffer size. In terms of server-side memory, both are very efficient because they read directly from the stream's internal radix tree.

Q415: What is "Redis Sentinel" parallel-syncs impact on Slave disk I/O?​

If multiple replicas start syncing with the new master, they are all writing the new RDB to their local disks simultaneously. On a shared storage system (like some cloud EBS volumes), this can lead to an I/O bottleneck that slows down the entire failover process.

Q416: Explain "Memory Usage" of "Sorted Sets" vs "Hashes".​

For the same number of fields/members:

  • ZSet: Larger overhead because it maintains both a Hash Table and a Skip List.
  • Hash: Smaller overhead because it only uses a Hash Table (or listpack). Always choose a Hash unless you specifically need the ranking or range query capabilities of a Sorted Set.

Q417: Describe "Redis Cluster" CLUSTER REPLICAS "Sync" status.​

The command returns the list of replicas, but it also includes a flag showing if the replica is currently "online" (connected and synced) or "handshaking" or "failed". This is the first place to check if you suspect your cluster's redundancy is compromised.

Q418: What is "Redis Sentinel" sentinel monitor "Default" values?​

  • down-after-milliseconds: 30,000 (30s)
  • parallel-syncs: 1
  • failover-timeout: 180,000 (3m) Understanding these defaults is critical because they determine the baseline behavior of your high-availability system before any tuning.

Q419: Explain "Redis Modules" "Context" dictionary access.​

Modules can access the main Redis dictionary directly using RedisModule_GetSelectedDb and then use RedisModule_Scan or RedisModule_OpenKey. This allows modules to build cross-key logic (like "if key A changes, update key B") with maximum performance.

Q420: Describe "Redis Cluster" failover-validity-factor and "Clock Skew".​

If nodes have significantly different system clocks, the failover-validity-factor calculation might be slightly off, as the "last time seen" is based on the local node's clock. Always use NTP or a similar service to keep all nodes in a Redis cluster perfectly synchronized.

Q421: Explain "Sorted Set" ZMSCORE (Redis 6.2+) error handling.​

If you call ZMSCORE with a member that doesn't exist, it returns a nil (Null) value for that specific member in the resulting list, but it doesn't fail the entire command. This allows you to check for the existence of multiple users and get their scores in one go.

Q422: What is the "Redis Sentinel" client-reconfig-script "Exit Codes"?​

Sentinel ignores the exit code of the script. If the script fails, Sentinel logs the error but continues with the failover process. This means your script must handle its own retries and error reporting; it can't rely on Sentinel to retry it.

Q423: Describe "Redis Module" "Detached Context" for background threads.​

If a module wants to perform a long-running task (like a complex calculation) without blocking Redis, it creates a "Detached Context". The background thread uses this context to read data from Redis. Once finished, it uses a "Thread Safe Context" to write the final result back to the keyspace.

Q424: Explain "Redis Cluster" CLUSTER RESET "Epoch" behavior.​

A HARD reset sets the node's configEpoch to 0. This is important because when the node rejoins a cluster, it will always "lose" to nodes with a higher epoch, ensuring that its old, potentially stale configuration doesn't accidentally overwrite the current cluster state.

Q425: Describe "Redis Stream" XTRIM "No-split" optimization.​

Trimming a stream is expensive if you have to split an internal node. Redis 6.2 introduced a "no-split" optimization where it only removes entire nodes. While this makes the trimming less "precise" (the stream might be slightly larger than requested), it makes it significantly faster.

Q426: Explain "Sorted Set" ZADD "GT" and "LT" flags (Redis 6.2+).​

  • GT: Only update the score if the new score is Greater Than the current score.
  • LT: Only update if the new score is Less Than the current score. These flags are perfect for implementing "High Score" leaderboards or "Best Time" tracking without needing complex Lua scripts.

Q427: What is "Redis Sentinel" parallel-syncs impact on Replica Memory?​

During synchronization, a replica must hold the incoming RDB in memory (if using diskless loading) or on disk. If parallel-syncs is high, multiple replicas will be consuming these resources simultaneously, which can be an issue on memory-constrained hardware.

Q428: Describe "Redis Module" "Native Data Type" versioning.​

When registering a type, you provide a version number. When loading an RDB, Redis passes this version to your module's rdb_load function. This allows your module to handle data saved by older versions of itself, providing a path for schema evolution.

Q429: Explain "Redis Cluster" cluster-migration-barrier and "Node Health".​

Orphan protection only considers "Healthy" replicas. If a replica is lagging significantly or has a connection issue, it won't be migrated to cover an orphan master, ensuring that we only move replicas that are actually capable of taking over.

Q430: Describe "Redis Stream" XREAD "Message ID" structure.​

An ID consists of <millisecondsTime>-<sequenceNumber>. The time is the server time when the message was added. The sequence number is used to distinguish messages added within the same millisecond. This ensures that IDs are always strictly increasing and unique.

Q431: Explain "Sorted Set" ZMSCORE (Redis 6.2+) "Null" vs "Error".​

The command returns a list. If the key itself doesn't exist, it returns an empty list or a null depending on the client library. If the key exists but is not a Sorted Set, it returns a standard "WRONGTYPE" error. Always check the key type before bulk operations.

Q432: What is "Redis Sentinel" sentinel monitor "Quorum" and "Partition" resilience?​

If you have 5 Sentinels and a quorum of 3, the cluster can survive the loss of 2 Sentinels. If a network partition splits them into 2 and 3, only the side with 3 Sentinels can perform a failover, preventing a "Split Brain" scenario where both sides try to promote a new master.

Q433: Describe "Redis Module" "Command Alias".​

Modules can register multiple names for the same command callback. This allows you to provide "Short names" for frequent operations or to maintain backward compatibility if you decide to rename a command in a newer version of the module.

Q434: Explain "Redis Cluster" cluster-announce-ip and "DNS" issues.​

Redis Cluster currently does not support DNS names in the internal gossip protocol (only IP addresses). The cluster-announce-ip is what's used by other nodes to find you. If you use a DNS name, it must resolve to the IP you've announced.

Q435: Describe "Redis Stream" XAUTOCLAIM "Consumer Name".​

When you call XAUTOCLAIM, you specify a consumer name. Any messages that are reclaimed are automatically assigned to this consumer and their "idle time" is reset. This is the atomic way to say "I'm taking over this stale work".

Q436: Explain "Sorted Set" ZDIFF "Empty Set" behavior.​

If the first set in ZDIFF is empty, the result is always an empty set, regardless of the contents of the other sets. If subsequent sets are empty, they are ignored and the result is just the contents of the first set.

Q437: What is "Redis Sentinel" sentinel announce-ip for "Virtual IPs"?​

If you use a Keepalived or similar VIP for your Sentinels, you should set announce-ip to the VIP address. This ensures that even if a Sentinel process moves to a different physical server, other Sentinels and clients can still reach it at the same address.

Q438: Describe "Redis Module" "Scanning" and "Key Space Notifications".​

Modules can register for notifications and then use the Scan API to perform an action on a large group of keys. This allows for implementing "Reactive" logic that can scale to millions of keys without blocking the server.

Q439: Explain "Redis Cluster" cluster-replica-no-failover for "Reporting" nodes.​

You might have a node that is dedicated to running heavy SCAN or HGETALL operations for reporting. By setting no-failover, you ensure this node (which might be under high CPU load from reporting) is never promoted to be the primary production master.

Q440: Describe "Redis Stream" XSETID "ID 0-0" risk.​

Setting the Last ID to 0-0 effectively allows you to add messages with any ID, but it can confuse consumers who expect IDs to be increasing. It should only be used when you are manually "re-seeding" a stream from an external source.

Q441: Explain "Sorted Set" ZINTER "Weight" defaults.​

The default weight for every set in an intersection is 1.0. If you don't provide the WEIGHTS argument, the scores of matching members are simply added together.

Q442: What is "Redis Sentinel" sentinel flush-config and "Read-only" filesystems?​

If Sentinel is running on a read-only filesystem (e.g., in some restricted container environments), flush-config will fail. This prevents Sentinel from persisting the discovered cluster state, meaning it will have to re-discover everything every time it restarts.

Q443: Describe "Redis Module" "Blocked Keys" and "Multiple Clients".​

When multiple clients are blocked on the same key (e.g., BRPOP), Redis wakes them up in the order they arrived (FIFO). Modules can implement the same "Fairness" by using the built-in Redis blocking APIs.

Q444: Explain "Redis Cluster" cluster-migration-barrier for "Master Consolidation".​

In a cluster that has been over-provisioned, you can use the migration barrier to consolidate replicas onto fewer masters, allowing you to safely decommission some servers without reducing the cluster's overall fault tolerance.

Q445: Describe "Redis Stream" XREADGROUP "BLOCK" and "Multiple Consumers".​

If multiple consumers in the same group are blocked on the same stream, Redis will deliver new messages to them in a round-robin fashion, ensuring an even distribution of work across your worker pool.

Q446: Explain "Sorted Set" ZLEXCOUNT vs ZCARD.​

  • ZCARD: $O(1)$ Returns the total number of members.
  • ZLEXCOUNT: $O(\log N)$ Returns the count of a specific string range. Use ZCARD for general set size and ZLEXCOUNT only when you need to filter by name.

Q447: What is "Redis Sentinel" sentinel auth-pass and "Default User"?​

If you don't specify a sentinel-user, Sentinel uses the "default" user to connect to Redis. This means the "default" user on your Redis master must have the necessary permissions for Sentinel to run INFO, CONFIG, and SLAVEOF.

Q448: Describe "Redis Module" "Dictionary" types.​

Modules can create dictionaries that store either "Module Strings" or "Raw C Strings" as keys. This gives module authors the flexibility to optimize their internal data structures for either memory efficiency or ease of integration with external C libraries.

Q449: Explain "Redis Cluster" cluster-preferred-endpoint-type and "TLS" termination.​

If TLS is terminated at a proxy, the Redis node might see incoming connections as plaintext. This setting allows the node to still tell clients to use the "hostname" endpoint, which the client will then resolve to the TLS-enabled proxy.

Q450: Describe "Redis Stream" XSETID and "History Truncation".​

If you set the ID to a value that is larger than the current last ID, you effectively "truncate" the future of the stream until the wall-clock time catches up to that ID. This is a very rare operation used for fixing extreme clock-jump issues.

10. Redis Advanced Interview Pack​

Q451: When is Redis a better choice than a relational database?​

Technical answer: Redis is better when the workload needs very low latency, ephemeral state, counters, queues, or cache-style access patterns rather than durable relational querying. Example: SET session:123 "data" EX 3600 Interviewer notes: Strong candidates explain that Redis usually complements, not replaces, a primary database. Red flags: Calling Redis a general-purpose replacement for every datastore.

Q452: What is the difference between a Redis hash and a JSON document?​

Technical answer: A hash is a field-value map optimized for flat attributes, while JSON is usually stored as a string unless you manage structure at the application layer. Example: HSET user:1 name "Alice" age 30 Interviewer notes: Ask about field-level updates and memory efficiency. Red flags: Treating hashes as nested documents.

Q453: How do strings fit into Redis design?​

Technical answer: Strings are the simplest Redis type and can hold text, numbers, serialized payloads, or binary data. Example: SET cart:42 "{...}" Interviewer notes: Good answers mention that many other structures are implemented on top of string-like encodings internally. Red flags: Thinking strings are only human-readable text.

Q454: What are common list operations used for queues?​

Technical answer: Use LPUSH/RPUSH to enqueue and LPOP/RPOP to dequeue, often with blocking variants for worker queues. Example: LPUSH jobs "job-1" Interviewer notes: Candidates should know lists are useful but not the same as Streams. Red flags: Recommending lists for complex consumer-group workflows.

Q455: What is the best use case for sets?​

Technical answer: Sets are ideal when uniqueness and fast membership or set algebra matter. Example: SADD user:1:tags "sports" "music" Interviewer notes: Ask about intersection, union, and difference use cases. Red flags: Storing ordered data in sets.

Q456: What is the best use case for sorted sets?​

Technical answer: Sorted sets are ideal for leaderboards, priority queues, and ranked retrieval based on a score. Example: ZADD leaderboard 1200 user:1 Interviewer notes: Good answers mention score ties and lexicographic tie-breaking. Red flags: Using sorted sets when ordering is irrelevant.

Q457: How does Pub/Sub differ from Streams?​

Technical answer: Pub/Sub is transient broadcast messaging with no persistence, while Streams provide durable log-like storage, consumer groups, and replay. Example: PUBLISH notifications "hello" Interviewer notes: Strong candidates know Pub/Sub loses messages if consumers are offline. Red flags: Using Pub/Sub for reliable task delivery.

Q458: What is a Redis Stream consumer group?​

Technical answer: A consumer group lets multiple consumers share work from the same stream while tracking pending messages and acknowledgments. Example: XGROUP CREATE mystream workers $ MKSTREAM Interviewer notes: Ask about at-least-once delivery and pending entries. Red flags: Saying streams automatically guarantee exactly-once processing.

Q459: What problem does XAUTOCLAIM solve?​

Technical answer: It helps reclaim stale pending stream entries from crashed or slow consumers without manual pending-list scanning. Example: XAUTOCLAIM mystream workers c1 60000 0-0 COUNT 10 Interviewer notes: Good candidates explain recovery and idle-time handling. Red flags: Ignoring stuck pending messages.

Q460: Why is TTL important in Redis caching?​

Technical answer: TTL keeps cache entries bounded in time, reducing stale data risk and controlling memory growth. Example: SET product:99 "..." EX 300 Interviewer notes: Ask about cache invalidation and refresh strategy. Red flags: Caching without an expiration policy.

Q461: What are Redis eviction policies?​

Technical answer: Eviction policies determine which keys Redis removes when memory is full, such as LRU, LFU, or volatile-only strategies. Example: maxmemory-policy allkeys-lru Interviewer notes: Strong answers relate policy choice to cache semantics. Red flags: Not knowing what happens when memory runs out.

Q462: When should you use allkeys-lru versus volatile-ttl?​

Technical answer: Use allkeys-lru when the whole dataset is cacheable and eviction should consider every key; use volatile-ttl when only expiring keys may be evicted. Example: A pure cache often uses allkeys-lru. Interviewer notes: Ask whether non-cache keys must be protected. Red flags: Choosing a policy without understanding key classes.

Q463: What is maxmemory for?​

Technical answer: It caps memory usage so Redis can start evicting keys before the process or host runs out of RAM. Example: CONFIG SET maxmemory 2gb Interviewer notes: Good candidates mention that overhead and fragmentation still matter. Red flags: Leaving memory unlimited in production.

Q464: What is memory fragmentation in Redis?​

Technical answer: Fragmentation is the gap between allocated memory and memory actually usable by data, often caused by allocation patterns and object churn. Example: A workload with many small keys and frequent deletes can fragment memory. Interviewer notes: Ask about allocator tuning and active defragmentation. Red flags: Confusing dataset size with RSS.

Q465: Why is active defragmentation useful?​

Technical answer: It moves data around in memory to reduce fragmentation and reclaim wasted space without stopping the server. Example: Enable active defrag for churn-heavy workloads. Interviewer notes: Good answers mention it costs CPU. Red flags: Assuming it is free.

Q466: What is the difference between RDB and AOF?​

Technical answer: RDB is point-in-time snapshotting, while AOF records writes incrementally for better durability. Example: Use both for complementary recovery properties. Interviewer notes: Strong candidates discuss restart speed versus data loss window. Red flags: Treating them as interchangeable.

Q467: What is AOF rewrite trying to improve?​

Technical answer: It compacts the append-only file by rewriting it into a minimal sequence that represents current data state. Example: Rewrite removes redundant historical writes. Interviewer notes: Ask how rewrite affects latency and disk usage. Red flags: Ignoring rewrite cost in write-heavy systems.

Q468: What is the purpose of SAVE and BGSAVE?​

Technical answer: SAVE blocks until a snapshot finishes, while BGSAVE creates the snapshot in the background. Example: Prefer BGSAVE for production. Interviewer notes: Candidates should know BGSAVE is the practical default. Red flags: Running blocking persistence commands casually.

Q469: How does replication work in Redis?​

Technical answer: Replication asynchronously copies data from a primary to replicas so they can serve reads or take over during failover. Example: REPLICAOF master-host 6379 Interviewer notes: Good answers mention eventual consistency. Red flags: Calling replicas synchronous by default.

Q470: What is Redis Sentinel responsible for?​

Technical answer: Sentinel monitors masters and replicas, decides when a master is down, and coordinates automatic failover. Example: Sentinel promotes a replica when quorum agrees the master is unavailable. Interviewer notes: Ask about quorum and split brain. Red flags: Treating Sentinel as a data replication mechanism.

Q471: What is Redis Cluster responsible for?​

Technical answer: Cluster shards keys across nodes using hash slots and provides distributed high availability. Example: Keys are routed based on hash slot ownership. Interviewer notes: Strong candidates mention multi-key constraints and slot locality. Red flags: Saying Cluster is just Sentinel plus sharding.

Q472: Why do hash tags matter in Cluster?​

Technical answer: Hash tags force related keys to land in the same slot so multi-key operations can work. Example: user:{42}:profile and user:{42}:orders Interviewer notes: Good answers explain co-location for transactions or Lua scripts. Red flags: Ignoring slot placement in clustered designs.

Q473: What is a common Redis transaction misconception?​

Technical answer: Redis transactions are a queued batch with atomic execution, but they do not provide rollback on runtime errors inside the batch. Example: MULTI ... EXEC Interviewer notes: Candidates should mention WATCH for optimistic concurrency. Red flags: Believing Redis transactions behave like SQL transactions.

Q474: What does WATCH enable?​

Technical answer: WATCH tracks key changes so a transaction can abort if the watched keys are modified before EXEC. Example: WATCH balance:1 Interviewer notes: Ask for optimistic locking use cases. Red flags: Thinking WATCH locks keys physically.

Q475: Why are pipelines useful?​

Technical answer: Pipelines batch commands to reduce round-trips, which improves throughput when network latency is significant. Example: Send many SET commands in one network exchange. Interviewer notes: Good answers separate pipelining from transactions. Red flags: Confusing batching with atomicity.

Q476: What is a common Lua scripting use case?​

Technical answer: Lua is useful when multiple Redis operations must run atomically with server-side logic. Example: Atomic rate limiting or inventory decrement. Interviewer notes: Ask about deterministic scripts and blocking behavior. Red flags: Using Lua for heavy computation.

Q477: Why can Lua scripts be dangerous in production?​

Technical answer: Scripts run on the Redis main thread, so long scripts block all other commands. Example: Avoid loops over large keyspaces inside Lua. Interviewer notes: Strong candidates mention bounded script runtime. Red flags: Treating scripts like a general application runtime.

Q478: What is a distributed lock pattern in Redis?​

Technical answer: Use a unique token plus expiry so a lock can be safely acquired and released without stale ownership. Example: SET lock:job42 token NX PX 30000 Interviewer notes: Good answers mention verifying the token before delete. Red flags: Deleting locks without ownership checks.

Q479: Why is SET NX PX preferred over SETNX plus EXPIRE?​

Technical answer: It is atomic, so you do not risk creating a lock without a TTL if the process dies between commands. Example: SET resource:lock abc NX PX 10000 Interviewer notes: Candidates should know this is the standard lock acquisition pattern. Red flags: Using multiple commands for lock setup.

Q480: What is a cache stampede?​

Technical answer: It happens when many clients miss the same key at once and all regenerate the value simultaneously. Example: Use jittered TTLs or single-flight refresh logic. Interviewer notes: Ask for mitigation strategies. Red flags: Ignoring thundering herd effects.

Q481: What is a cache aside pattern?​

Technical answer: The application reads from cache first, falls back to the database on miss, and populates Redis after fetching. Example: Check GET user:42, then load from DB if missing. Interviewer notes: Good answers mention invalidation complexity. Red flags: Confusing cache aside with write-through.

Q482: What is write-through caching?​

Technical answer: Writes go to the cache and the backing store together so cached data stays immediately current. Example: Update DB, then update Redis in the same request flow. Interviewer notes: Ask about failure handling and consistency. Red flags: Calling every post-write cache set write-through.

Q483: What is a rate limiting pattern in Redis?​

Technical answer: Use counters, expirations, or sorted sets to track requests over time windows and reject excess traffic. Example: INCR api:ip:1.2.3.4 with EXPIRE on first hit. Interviewer notes: Strong candidates compare fixed-window, sliding-window, and token bucket. Red flags: Counting requests without TTL.

Q484: Why are sorted sets useful for sliding windows?​

Technical answer: Scores can represent timestamps, making it easy to add events, remove old ones, and count the current window. Example: ZADD hits <timestamp> request-id Interviewer notes: Ask about trimming old entries. Red flags: Using lists where timestamp ordering matters.

Q485: What is Pub/Sub best for?​

Technical answer: Pub/Sub is best for ephemeral fan-out notifications where missing messages is acceptable. Example: SUBSCRIBE alerts Interviewer notes: Candidates should know it is not durable. Red flags: Using Pub/Sub for guaranteed delivery.

Q486: What is the cost of using large keys?​

Technical answer: Large keys and values increase memory, network transfer, and replication overhead, and they can make latency spikes worse. Example: Avoid storing megabyte-sized JSON blobs when only a few fields are needed. Interviewer notes: Good answers discuss key and value size both. Red flags: Treating value size as irrelevant.

Q487: How does Redis handle persistence during background saving?​

Technical answer: Redis uses fork-based copy-on-write, so the child process writes the snapshot while the parent continues serving traffic. Example: BGSAVE triggers a child snapshot. Interviewer notes: Strong candidates mention memory spikes from copy-on-write. Red flags: Saying persistence is always free in the background.

Q488: What is the danger of a hot key?​

Technical answer: A hot key can become a bottleneck because many clients contend for the same object and the same shard or node. Example: A global counter updated on every request. Interviewer notes: Ask about sharding counters or local aggregation. Red flags: Ignoring key-level contention.

Q489: What is a common mitigation for hot counters?​

Technical answer: Use striped counters or per-node counters and aggregate them periodically. Example: Maintain counter:shard:0..n instead of one global counter. Interviewer notes: Good answers mention eventual aggregation. Red flags: Using one atomic key for all traffic.

Q490: What is SCAN for?​

Technical answer: SCAN iterates keys incrementally without blocking the server like KEYS can. Example: SCAN 0 MATCH user:* COUNT 1000 Interviewer notes: Candidates should know it is cursor-based and may return duplicates. Red flags: Using KEYS in production.

Q491: Why is KEYS dangerous in production?​

Technical answer: It performs a blocking full keyspace scan, which can stall Redis on large datasets. Example: Prefer SCAN for incremental iteration. Interviewer notes: Ask for safer admin tooling patterns. Red flags: Recommending KEYS for runtime queries.

Technical answer: DEL frees memory synchronously, while UNLINK unlinks keys and frees memory asynchronously to reduce blocking. Example: UNLINK big:key Interviewer notes: Good answers know UNLINK is useful for very large values. Red flags: Ignoring synchronous free costs.

Q493: Why does Redis use single-threaded command execution?​

Technical answer: Single-threaded execution simplifies concurrency and avoids lock contention, while high throughput comes from efficient in-memory operations. Example: The event loop serializes commands. Interviewer notes: Mention IO threads only as a networking optimization. Red flags: Thinking Redis cannot scale because it is single-threaded.

Q494: What is a common production mistake with maxmemory?​

Technical answer: Setting it too close to physical RAM leaves no room for overhead, fragmentation, or replication buffers. Example: Leave headroom for OS and Redis internal structures. Interviewer notes: Ask how to size memory safely. Red flags: Allocating all host RAM to Redis.

Q495: What is the benefit of HSCAN over HGETALL?​

Technical answer: HSCAN iterates incrementally, so it is safer for large hashes and avoids blocking on a full materialization. Example: HSCAN user:1 0 COUNT 100 Interviewer notes: Good answers mention cursor behavior and partial results. Red flags: Using HGETALL on very large hashes blindly.

Q496: When are hashes a poor fit?​

Technical answer: Hashes are less suitable when you need deep nesting, ordered data, or operations spanning many members. Example: Avoid using a hash as a full document store for complex nested objects. Interviewer notes: Good answers know the limit of flat field/value design. Red flags: Treating hashes like arbitrary JSON trees.

Q497: What is the purpose of INCR and DECR?​

Technical answer: They provide atomic counters, which are useful for metrics, sequence numbers, and rate limiting. Example: INCR page:view:today Interviewer notes: Ask about TTL pairing and overflow awareness. Red flags: Using read-modify-write in the client for counters.

Q498: How do you implement a session store in Redis?​

Technical answer: Store session state under a namespaced key with TTL, and refresh or invalidate it as users interact. Example: SET session:abc123 '{...}' EX 1800 Interviewer notes: Good answers mention serialization format and invalidation. Red flags: Keeping sessions forever.

Q499: What is the right mindset for Redis durability?​

Technical answer: Decide how much data loss is acceptable, then choose RDB, AOF, or both with that recovery objective in mind. Example: Cache workloads can tolerate more loss than queues. Interviewer notes: Ask about RPO and RTO. Red flags: Assuming in-memory automatically means unacceptable loss.

Q500: Why are Streams better than Lists for work queues?​

Technical answer: Streams support consumer groups, pending entries, replay, and explicit acknowledgments, which lists lack. Example: XREADGROUP GROUP workers c1 COUNT 10 STREAMS jobs > Interviewer notes: Candidates should understand delivery semantics. Red flags: Using lists when reprocessing matters.

Q501: What is a pending entries list?​

Technical answer: It is the set of stream messages delivered but not yet acknowledged by a consumer group member. Example: Inspect pending entries when a worker crashes. Interviewer notes: Good answers mention recovery workflows. Red flags: Ignoring unacked messages.

Q502: What is the purpose of XACK?​

Technical answer: It acknowledges that a consumer processed a stream message so Redis can remove it from the pending set. Example: XACK jobs workers 169...-0 Interviewer notes: Ask what happens if ack is forgotten. Red flags: Treating delivery as automatically completed.

Q503: How do you use sorted sets for leaderboards?​

Technical answer: Store each member with its score, then query top ranks or rank positions with sorted-set commands. Example: ZREVRANGE leaderboard 0 9 WITHSCORES Interviewer notes: Good answers mention updating scores atomically. Red flags: Trying to emulate ranking with lists.

Q504: What is ZREM used for?​

Technical answer: It removes a member from a sorted set, which is useful for score expiration or removing inactive entries. Example: ZREM leaderboard user:42 Interviewer notes: Ask about cardinality changes and cleanup. Red flags: Leaving stale ranked entries forever.

Q505: How do you implement a queue with blocking pops?​

Technical answer: Use a blocking list pop command so workers sleep until work arrives instead of polling aggressively. Example: BRPOP jobs 0 Interviewer notes: Candidates should know this is simpler than Streams but less capable. Red flags: Busy-wait polling in a worker loop.

Q506: What is the value of SET ... GET?​

Technical answer: It atomically sets a string and returns the previous value, which is useful for compare-and-swap-like flows. Example: SET key value GET Interviewer notes: Ask how it differs from separate GET and SET commands. Red flags: Replacing transactional logic with multiple round trips.

Q507: How does Redis handle expirations?​

Technical answer: It combines passive expiration on access with active background sampling to remove stale keys. Example: TTL cache:item:1 Interviewer notes: Good answers mention that expired keys may survive briefly until accessed or sampled. Red flags: Assuming expiration is instant at the exact second.

Q508: What is lazy freeing?​

Technical answer: Lazy freeing defers releasing memory for large values to background work so command latency stays lower. Example: UNLINK can trigger lazy freeing behavior. Interviewer notes: Candidates should connect it to user-facing latency. Red flags: Ignoring background memory reclamation cost.

Q509: What is the risk of using Redis as the source of truth?​

Technical answer: Redis can be durable, but it is often tuned like a cache, so relying on it as the only durable system increases operational risk. Example: Keep authoritative order data in a durable primary database. Interviewer notes: Ask about backup, failover, and recovery confidence. Red flags: Treating ephemeral memory semantics as equivalent to a transactional database.

Q510: Why can replication lag matter even for caches?​

Technical answer: Lag can expose stale data to readers on replicas, which matters when cached values drive user-visible behavior. Example: A session revoked on the primary may still be readable on a lagging replica. Interviewer notes: Strong candidates explain staleness tolerance. Red flags: Assuming replicas are immediately current.

Q511: What is the purpose of WAIT?​

Technical answer: WAIT blocks until a write is replicated to a minimum number of replicas or a timeout is reached. Example: WAIT 1 100 Interviewer notes: Good answers mention stronger durability with added latency. Red flags: Using it everywhere without latency awareness.

Q512: What is a common Redis cluster failure mode?​

Technical answer: Network partitions or slot migration issues can make nodes temporarily unreachable or inconsistent from the client’s perspective. Example: Clients must follow cluster redirects. Interviewer notes: Ask about MOVED and ASK replies. Red flags: Ignoring client cluster awareness.

Q513: What are MOVED and ASK redirects?​

Technical answer: MOVED means a slot permanently belongs elsewhere, while ASK means a slot is being migrated and needs temporary redirection. Example: Cluster-aware clients update their slot cache after redirects. Interviewer notes: Strong candidates know clients must handle both. Red flags: Retrying blindly without redirect logic.

Q514: Why is HMSET less important now?​

Technical answer: Modern Redis accepts variadic HSET, so separate legacy multi-field commands are mostly historical. Example: HSET user:1 name Alice age 30 Interviewer notes: Candidates should know command evolution. Red flags: Overemphasizing deprecated naming.

Q515: What is the tradeoff of enabling AOF every write?​

Technical answer: It improves durability but increases latency and fsync overhead. Example: appendfsync always Interviewer notes: Good answers discuss everysec as a common compromise. Red flags: Choosing maximum durability without measuring cost.

Q516: What is the role of INFO in troubleshooting?​

Technical answer: INFO gives a quick snapshot of memory, persistence, replication, CPU, and keyspace health. Example: INFO memory Interviewer notes: Ask which subsection they check first under pressure. Red flags: Ignoring built-in observability.

Q517: How do you reduce memory usage for small values?​

Technical answer: Use compact encodings and avoid excessive key overhead, long key names, and unnecessary wrappers. Example: Keep key names short and value structures flat where possible. Interviewer notes: Good answers mention overhead per key matters a lot. Red flags: Thinking only payload size matters.

Q518: What is the risk of large hash fields or stream entries?​

Technical answer: Very large items can increase copy cost, latency spikes, and fragmentation, especially during persistence or replication. Example: Split huge records when practical. Interviewer notes: Ask about operational limits and object sizing. Red flags: Creating giant monolithic values by default.

Q519: What is a Lua lock-release pattern?​

Technical answer: Use a script to verify the stored token before deleting the lock key so only the owner can release it. Example: Compare token, then DEL in one script. Interviewer notes: Strong candidates know why this prevents accidental unlocks. Red flags: Releasing locks with plain DEL.

Q520: What is the main reason to shard Redis workloads?​

Technical answer: Sharding distributes memory, CPU, and traffic so no single node becomes the bottleneck. Example: Redis Cluster spreads hash slots across nodes. Interviewer notes: Ask about hot keys and slot-aware design. Red flags: Sharding without thinking about key access patterns.

Q521: Why can PUBLISH fan-out become expensive?​

Technical answer: Every subscriber receives the message, so large fan-out increases CPU and network cost. Example: Broadcast alerts to only the channels that need them. Interviewer notes: Good answers compare channel design to throughput. Red flags: Broadcasting everything to everyone.

Q522: What is a common production tuning mistake with Redis?​

Technical answer: People tune only memory or eviction while ignoring persistence, replication, latency, and client behavior together. Example: A fast cache still fails if persistence settings are unsafe for the workload. Interviewer notes: Strong candidates think end-to-end. Red flags: Optimizing one metric in isolation.

Q523: Why is pipeline depth important?​

Technical answer: Too little pipelining wastes network round-trips, but too much can increase memory usage and latency spikes in clients. Example: Batch commands in moderate chunks. Interviewer notes: Ask how they balance throughput and responsiveness. Red flags: Sending unbounded pipelines.

Q524: What is a reasonable way to store counters by tenant?​

Technical answer: Namespace them by tenant and shard if needed, so one tenant cannot monopolize a single hot counter. Example: tenant:42:counter:events Interviewer notes: Good answers mention isolation and cleanup. Red flags: One global counter for all tenants.

Q525: What should you watch during failover?​

Technical answer: Monitor failover time, replica offset, client reconnection, and whether the promoted node has enough recent data. Example: Sentinel promotion after master outage. Interviewer notes: Strong candidates mention testing failover before production incidents. Red flags: Assuming failover is always seamless.

Q526: Why is MONITOR dangerous?​

Technical answer: It streams every command in real time and can create major overhead, so it is only for short-lived debugging. Example: Use it sparingly on noncritical systems. Interviewer notes: Ask for safer diagnostics first. Red flags: Running MONITOR on a hot production node for long periods.

Q527: What is the best practice for key naming?​

Technical answer: Use predictable namespaces, avoid excessive length, and design keys to reflect access patterns and lifecycle. Example: app:tenant:entity:id Interviewer notes: Good answers connect naming to operability and bulk deletion. Red flags: Inconsistent ad hoc key names.

Q528: Why can FLUSHALL be catastrophic?​

Technical answer: It deletes everything in the selected database or all databases, which is usually irreversible without backups. Example: Guard destructive admin commands carefully. Interviewer notes: Candidates should know the operational risk. Red flags: Treating it like a safe cleanup command.

Q529: What is the benefit of EXPIRE plus jitter?​

Technical answer: Jitter spreads expirations over time and reduces synchronized cache misses and eviction storms. Example: Randomize TTL by a small percentage. Interviewer notes: Strong answers connect this to stampede prevention. Red flags: Using identical TTLs for millions of keys.

Q530: What is the best single Redis habit for production safety?​

Technical answer: Match the data structure, persistence mode, and eviction policy to the workload before shipping. Example: Cache, queue, and lock patterns should not share the same assumptions. Interviewer notes: Good candidates reason from workload to config. Red flags: Copying a generic Redis config without workload analysis.


Redis Advanced Patterns​

Q531: What is the N+1 problem in Redis and how do you avoid it?​

Technical answer: The N+1 problem occurs when an application issues N individual GET commands in a loop instead of batching them. This causes N round-trips instead of one. Fix: use MGET for multiple keys, or pipeline commands, or use hashes to group related data. Example:

# Bad: N+1 round-trips
for key in keys:
value = redis.get(key)

# Good: 1 round-trip
values = redis.mget(keys)

# Better: use hash for related data
redis.hgetall(f"user:{user_id}")

Interviewer notes: Strong candidates mention both MGET and hashes as solutions. Red flags: Not seeing the round-trip cost; ignoring pipeline/MGET.

Q532: When should you use MGET vs pipeline vs hash in Redis?​

Technical answer: Use MGET for independent keys — one round-trip, returns list. Use pipeline for mixed commands or when you need to batch writes and reads together. Use hashes when keys are logically grouped under one parent and you often fetch/update the whole group or several fields together. Example:

# MGET — independent keys
redis.mget(["user:1", "user:2", "user:3"])

# Pipeline — mixed ops
pipe = redis.pipeline()
pipe.get("user:1")
pipe.set("counter", 10)
pipe.execute()

# Hash — grouped fields
redis.hset("user:1", {"name": "Alice", "age": 30})
redis.hmget("user:1", "name", "age")

Interviewer notes: Good answers pick the right tool per access pattern. Red flags: Using flat keys for everything; not understanding when hashes save round-trips.

Q533: What is a race condition in Redis and how do you prevent it?​

Technical answer: A race condition occurs when multiple clients read-modify-write the same key concurrently and the last write wins, losing earlier updates. Prevent with atomic operations: INCR/DECR for counters, SET with NX/XX for locks, Lua scripts for complex read-modify-write, or Redis transactions (WATCH/MULTI/EXEC). Example:

# Race condition
balance = redis.get("account:1")
new_balance = int(balance) - 100
redis.set("account:1", new_balance) # Lost update!

# Atomic fix
redis.decrby("account:1", 100)

Interviewer notes: Strong candidates explain the read-modify-write gap. Red flags: GET + SET without atomicity for counters or balances.

Q534: How does WATCH/MULTI/EXEC prevent race conditions?​

Technical answer: WATCH observes a key. If the key changes before EXEC, the transaction aborts with a WatchError. The client retries the read-modify-write cycle. This is optimistic concurrency control. Example:

while True:
redis.watch("inventory:1")
stock = int(redis.get("inventory:1"))
if stock < 1:
redis.unwatch()
raise OutOfStock()
pipe = redis.pipeline()
pipe.multi()
pipe.decr("inventory:1")
try:
pipe.execute()
break
except WatchError:
continue

Interviewer notes: Good candidates mention retry loop and WatchError. Red flags: Using MULTI/EXEC without WATCH and thinking it is atomic.

Q535: When should you use a Lua script in Redis?​

Technical answer: Use Lua scripts for compound operations that must be atomic but cannot be expressed with single Redis commands. Lua runs atomically in Redis, blocking other commands during execution. Keep scripts short and fast. Example:

-- rate_limit.lua
local current = redis.call('GET', KEYS[1])
if current and tonumber(current) >= tonumber(ARGV[1]) then
return 0
end
redis.call('INCR', KEYS[1])
redis.call('EXPIRE', KEYS[1], ARGV[2])
return 1

Interviewer notes: Strong candidates mention atomicity and keep-scripts-short rule. Red flags: Long-running Lua scripts blocking the event loop.

Q536: How do you design Redis for multi-tenant SaaS?​

Technical answer: Isolate tenants via key prefixing or separate Redis databases/clusters. Prefixing: tenant:{id}:{resource}. For strong isolation, use separate Redis databases (SELECT) or separate instances per tenant tier. Add TTLs and memory limits per tenant to prevent one tenant from exhausting Redis. Example:

# Key prefixing
key = f"tenant:{tenant_id}:user:{user_id}"
redis.set(key, value, ex=3600)

# Separate DB per tenant
redis.select(tenant_db_id)
redis.set("user:1", value)

Interviewer notes: Good answers mention isolation levels and noisy-neighbor protection. Red flags: All tenants sharing one flat keyspace with no limits.

Q537: What is the noisy-neighbor problem in Redis and how do you mitigate it?​

Technical answer: One tenant or client issuing many commands can saturate Redis, starving others. Mitigate via: key-prefix isolation with per-tenant rate limits, Redis maxmemory policies, separate instances for premium tenants, client-side timeouts, and command-level rate limiting (CLIENT SETNAME + MONITOR or proxy). Example:

# Per-tenant rate limit
key = f"ratelimit:tenant:{tenant_id}"
count = redis.incr(key)
if count == 1:
redis.expire(key, 60)
if count > MAX_TENANT_COMMANDS:
raise TenantQuotaExceeded()

Interviewer notes: Strong candidates connect this to SaaS operational safety. Red flags: No per-tenant limits; one tenant can OOM Redis.

Q538: How do you handle key expiration at scale in Redis?​

Technical answer: Redis expires keys in two ways: active expiration (on access) and periodic expiration (background sampled scan). For large datasets with many expirations, use jittered TTLs to avoid expiring too many keys at once. Also set maxmemory-policy to evict old data when memory is full. Example:

# Jittered TTL
base_ttl = 3600
jitter = random.randint(-60, 60)
redis.set(key, value, ex=base_ttl + jitter)

Interviewer notes: Good answers mention expiration storms. Red flags: Identical TTLs for millions of keys.

Q539: What is a cache stampede and how do you prevent it?​

Technical answer: A cache stampede occurs when a popular key expires and many clients try to recompute and write it simultaneously, overwhelming the backend. Prevent with: probabilistic early expiration (add jitter before TTL), single-flight/mutex lock (only one client recomputes), or never-expire with background refresh. Example:

# Single-flight pattern
lock_key = f"lock:{key}"
if redis.set(lock_key, "1", nx=True, ex=10):
value = recompute(key)
redis.set(key, value, ex=ttl)
redis.delete(lock_key)
return value
else:
time.sleep(0.1)
return redis.get(key) or default

Interviewer notes: Strong candidates mention mutex or early-expiration strategies. Red flags: No protection against thundering herd.

Q540: How do you implement a distributed lock in Redis?​

Technical answer: Use SET with NX and EX options to acquire a lock with TTL. Release by deleting the key. For safety, use a lock token and compare before delete (or Lua script) to avoid deleting another client's lock. Redlock algorithm for multi-node safety. Example:

# Acquire
lock_key = "lock:resource"
token = str(uuid.uuid4())
acquired = redis.set(lock_key, token, nx=True, ex=30)

# Release (safe)
if acquired:
lua = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
"""
redis.eval(lua, 1, lock_key, token)

Interviewer notes: Good candidates mention token-based release and Redlock. Red flags: DEL without token check; no TTL on lock.

Technical answer: DEL is synchronous and blocks the event loop while freeing memory for large values. UNLINK is asynchronous — it queues the key for background deletion and returns immediately. Use UNLINK for large values to avoid latency spikes. Example:

# Synchronous — blocks on large value
redis.delete("big_key")

# Asynchronous — returns immediately
redis.unlink("big_key")

Interviewer notes: Strong candidates know the blocking behavior of DEL. Red flags: Using DEL on large values and not understanding latency impact.

Q542: How do you handle Redis failover in production?​

Technical answer: Use Redis Sentinel for automatic failover with one master and multiple replicas. Sentinel monitors the master, promotes a replica on failure, and updates DNS/config. For Redis 6+ Cluster, use cluster mode with automatic sharding and failover. Applications must handle MOVED/ASK redirects. Example:

# Sentinel connection
redis = redis.Sentinel([('sentinel1', 26379), ('sentinel2', 26379)])
master = redis.master_for('my-master', socket_timeout=0.5)
replica = redis.slave_for('my-master')

Interviewer notes: Good answers mention both Sentinel and Cluster modes. Red flags: No HA plan; single Redis instance in production.

Q543: What is Redis Cluster and when should you use it?​

Technical answer: Redis Cluster shards data across multiple nodes using hash slots (0-16383). Each node owns a subset of slots. Clients route commands to the correct node using cluster slots. Use when dataset exceeds single-node memory or throughput exceeds single-core capacity. Multi-key operations require keys in the same hash slot (same hash tag). Example:

# Hash tag forces keys into same slot
MSET {user:123}:name "Alice" {user:123}:age 30

Interviewer notes: Strong candidates mention hash tags for multi-key ops. Red flags: Using Cluster without understanding slot routing; multi-key ops across slots.

Q544: How do you monitor Redis performance?​

Technical answer: Monitor: hit rate (keyspace_hits / (keyspace_hits + keyspace_misses)), memory usage (used_memory, used_memory_peak), connected clients, command latency (LATENCY HISTOGRAM in Redis 7+), slow log (SLOWLOG GET), replication lag, evictions (evicted_keys), and blocked clients. Example:

# Redis CLI
INFO stats
INFO memory
SLOWLOG GET 10
LATENCY HISTOGRAM

Interviewer notes: Good candidates know which metrics indicate real problems. Red flags: Only checking if Redis is up, not performance metrics.

Q545: What is the maxmemory policy and when do you use each eviction strategy?​

Technical answer: maxmemory caps Redis memory. When full, eviction policies kick in:

  • noeviction: reject writes with error (default, safest for data integrity)
  • allkeys-lru: evict least recently used key across all keyspace
  • volatile-lru: evict LRU only among keys with EXPIRE
  • allkeys-random: random eviction across all keys
  • volatile-random: random eviction among expiring keys
  • volatile-ttl: evict shortest TTL first among expiring keys Use allkeys-lru for pure caches, noeviction for data stores. Interviewer notes: Strong candidates match policy to workload. Red flags: Using noeviction for a cache and wondering why writes fail.

Q546: What is Redis Streams and how is it different from Pub/Sub?​

Technical answer: Redis Streams is a log-like data structure that persists messages. Unlike Pub/Sub (fire-and-forget, no persistence), Streams store messages durably, support consumer groups, and allow replay. Use Streams when you need guaranteed delivery, history, or consumer group processing. Example:

# Producer
redis.xadd("events", {"type": "order_created", "order_id": "123"})

# Consumer group
redis.xgroup_create("events", "order-processors", id="0")
redis.xreadgroup("order-processors", "worker-1", {"events": ">"}, count=10)

Interviewer notes: Good answers mention persistence and consumer groups. Red flags: Using Pub/Sub when you need guaranteed delivery and replay.

Q547: How do you prevent Redis from becoming a single point of failure?​

Technical answer: Use Redis Sentinel for automatic failover with replicas. Or use Redis Cluster for sharding + failover. At the application level, implement connection retries and exponential backoff. Use proxies like Twemproxy or Envoy for connection pooling and automatic routing. Example:

# With Sentinel — auto-failover
redis = redis.Sentinel([('sentinel', 26379)])
master = redis.master_for('my-master')

Interviewer notes: Strong candidates mention both Sentinel and Cluster. Red flags: Single Redis node; no failover plan.

Q548: What is the difference between Redis replication and Redis Cluster?​

Technical answer: Replication copies data from master to replicas for read scaling and HA. It is single-master, async by default. Cluster shards data across multiple masters using hash slots, enabling horizontal scaling. Replication is within one shard; Cluster is multi-shard with automatic failover per shard. Interviewer notes: Good answers distinguish replication (read scaling) from Cluster (sharding). Red flags: Thinking Cluster is just "more replicas".

Q549: How do you handle Redis memory leaks?​

Technical answer: Identify with INFO memory, MEMORY DOCTOR, MEMORY USAGE per key. Common causes: large values, unbounded lists/sets/zsets, cached objects that should have TTLs, and memory fragmentation. Fix by setting maxmemory, using eviction policies, adding TTLs, and using smaller data structures. Example:

# Find biggest keys
redis-cli --bigkeys
MEMORY USAGE big_list

Interviewer notes: Strong candidates use Redis memory introspection tools. Red flags: Ignoring memory until OOM.

Q550: What is a safe way to delete large Redis keys without blocking?​

Technical answer: Use UNLINK instead of DEL for async deletion. For very large keys (lists, sets, zsets), use SCAN to iterate and delete in small batches. Redis 6+ has background deletion for expired keys. Avoid DEL on large values during peak traffic. Example:

# Async unlink
redis.unlink("large_key")

# Batch delete by pattern
for key in redis.scan_iter(pattern="cache:*", count=100):
redis.unlink(key)

Interviewer notes: Good answers mention UNLINK and batched deletion. Red flags: DEL on a 1GB key during peak load.

Q551: What is Redis WAIT and when should you use it?​

Technical answer: WAIT blocks the current client until previous writes are replicated to the specified number of replicas. It provides synchronous replication semantics at the application level. Use for critical writes where you need durability confirmation before returning. Example:

redis.set("payment:id", data)
redis.wait(1, 5000) # Wait for 1 replica, timeout 5s

Interviewer notes: Strong candidates know WAIT is not full sync replication. Red flags: Using WAIT as a substitute for proper replication setup.

Q552: How do you handle Redis key naming at scale?​

Technical answer: Use a consistent naming scheme: entity:id:field or tenant:id:entity. Use colons as separators (namespace-like). Avoid very long keys (memory overhead) or very short keys (collisions). Include TTL strategy in naming convention if needed. Example:

# Good
f"tenant:{tenant_id}:user:{user_id}:session:{session_id}"

# Bad
"data_12345" # unclear purpose

Interviewer notes: Good answers mention discoverability and tooling. Red flags: Inconsistent naming; no namespace for multi-tenant.

Q553: What is a Redis Lua script and why is it useful for atomicity?​

Technical answer: Redis executes Lua scripts atomically — no other commands run during execution. This makes Lua ideal for read-modify-write operations that must be atomic but cannot be expressed with single commands. Keep scripts short to avoid blocking the event loop. Example:

-- Atomic withdraw
local balance = redis.call('GET', KEYS[1])
if not balance or tonumber(balance) < tonumber(ARGV[1]) then
return 0
end
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1

Interviewer notes: Strong candidates mention atomicity and event-loop blocking. Red flags: Long-running Lua scripts; not knowing atomicity guarantee.

Q554: How do you safely increment a counter in Redis?​

Technical answer: Use INCR, INCRBY, or INCRBYFLOAT. These are atomic — no race condition between GET and SET. For counters with expiration, use INCR + EXPIRE together, or a Lua script to set TTL only on first increment. Example:

# Atomic counter
redis.incr("page:views:product:123")

# Counter with TTL (Lua)
redis.eval("""
if redis.call('EXISTS', KEYS[1]) == 0 then
redis.call('INCR', KEYS[1])
redis.call('EXPIRE', KEYS[1], ARGV[1])
else
redis.call('INCR', KEYS[1])
end
""", 1, "counter:product:123", 3600)

Interviewer notes: Good answers mention INCR atomicity and TTL race fix. Red flags: GET + 1 + SET for counters.

Q555: What is Redis OBJECT ENCODING and why does it matter?​

Technical answer: Redis optimizes storage by choosing internal encodings based on data size and type. For example, small hashes use ziplist, large hashes use hashtable. Small integers use integer encoding. Use OBJECT ENCODING key to inspect. Understanding encodings helps with memory estimation and performance tuning. Example:

> HSET user:1 name "Alice" age 30
> OBJECT ENCODING user:1
"ziplist" # small hash — memory efficient

Interviewer notes: Strong candidates know ziplist, hashtable, and skiplist encodings. Red flags: Not knowing Redis changes encoding based on size.

Q556: How do you implement rate limiting with Redis?​

Technical answer: Use sliding window log (sorted set per user with timestamps, remove old entries, count) or sliding window counter (sorted set or multiple keys). Simplest: fixed window with INCR + EXPIRE. For distributed: Redis is shared across instances. Return 429 when limit exceeded. Example:

# Fixed window
key = f"ratelimit:user:{user_id}:{window}"
count = redis.incr(key)
if count == 1:
redis.expire(key, 60)
if count > LIMIT:
return HTTPException(429)

Interviewer notes: Good answers mention sliding window vs fixed window trade-offs. Red flags: In-memory rate limiting only; no distributed coordination.

Q557: What is Redis security hardening in production?​

Technical answer: Enable authentication (requirepass), bind to internal IP only (bind 127.0.0.1), disable dangerous commands (RENAME-COMMAND or ACL for KEYS, FLUSHALL, CONFIG), use TLS for client connections, enable AUTH for Sentinel and Cluster bus, and set protected-mode yes. Example:

# redis.conf
requirepass strong-password
bind 10.0.0.1
rename-command KEYS ""
rename-command FLUSHALL ""
rename-command CONFIG ""

Interviewer notes: Strong candidates mention authentication, network binding, and command disabling. Red flags: Running Redis without authentication; exposed to public internet.

Q558: How do you use Redis for leader election?​

Technical answer: Use a sorted set where score = timestamp, member = instance ID. The instance with the lowest score (earliest timestamp) is the leader. Workers periodically refresh their score. If a leader fails to refresh, another takes over. Use a short TTL to auto-expire stale leaders. Example:

# Try to become leader
redis.zadd("leaderboard", {instance_id: time.time()})

# Check if leader
leader = redis.zrange("leaderboard", 0, 0)
is_leader = leader[0] == instance_id

Interviewer notes: Good answers mention TTL and refresh mechanism. Red flags: No TTL; stale leader never expires.

Q559: What is Redis Streams consumer group and why is it useful?​

Technical answer: Consumer groups allow multiple consumers to share the work of processing a stream. Each message is delivered to only one consumer in the group. Redis tracks delivery state (pending, acknowledged). This enables load balancing and fault-tolerant processing. Example:

# Create consumer group
redis.xgroup_create("orders", "order-processors", id="0", mkstream=True)

# Read as group member
redis.xreadgroup("order-processors", "worker-1",
{"orders": ">"}, count=10, block=5000)

# Acknowledge processed message
redis.xack("orders", "order-processors", msg_id)

Interviewer notes: Strong candidates mention message acknowledgment and replay. Red flags: Using Pub/Sub when Streams + consumer groups are needed.

Q560: What are Redis SCAN and HSCAN and when should you use them?​

Technical answer: SCAN iterates over keys in the keyspace without blocking. HSCAN iterates over hash fields. SSCAN/ZSCAN iterate over set/sorted set members. Use SCAN instead of KEYS/ SMEMBERS in production because SCAN is incremental and non-blocking. Example:

for key in redis.scan_iter(pattern="user:*", count=100):
redis.unlink(key)

Interviewer notes: Good answers mention non-blocking and cursor-based iteration. Red flags: Using KEYS in production; blocking commands on large datasets.

Q561: How do you prevent Redis from running out of memory?​

Technical answer: Set maxmemory in redis.conf. Choose an eviction policy (allkeys-lru, volatile-lru, noeviction, etc.). Monitor memory usage with INFO memory. Use TTLs to expire old data. Avoid caching large objects without limits. Use MEMORY USAGE to inspect per-key memory. Example:

# redis.conf
maxmemory 4GB
maxmemory-policy allkeys-lru

Interviewer notes: Strong candidates mention eviction policies and monitoring. Red flags: No maxmemory set; unbounded cache.

Q562: What is the Redis MONITOR command and why is it dangerous in production?​

Technical answer: MONITOR logs every command Redis processes in real-time. It is extremely expensive — it blocks the event loop and degrades throughput. Never use it in production for extended periods. Use it briefly for debugging. Example:

redis-cli MONITOR # Outputs every command

Interviewer notes: Good candidates know the performance impact. Red flags: Leaving MONITOR running in production.

Q563: What is a Redis slowlog and how do you use it?​

Technical answer: The slowlog records commands that exceed a configured execution time threshold. Use it to identify expensive commands (KEYS, large SMEMBERS, unbounded LRANGE) and optimize them. Example:

SLOWLOG GET 10 # Show last 10 slow commands
SLOWLOG RESET # Clear slowlog
CONFIG SET slowlog-log-slower-than 10000 # Log commands > 10ms

Interviewer notes: Strong candidates use slowlog for performance debugging. Red flags: Not knowing slowlog exists; ignoring it.

Q564: How do you handle Redis connection pooling?​

Technical answer: Redis clients maintain connection pools. Configure max connections per client, connection timeout, and health checks. For high-throughput apps, reuse connections instead of creating per-request. Monitor connection count with INFO clients. Example:

pool = redis.ConnectionPool(max_connections=50, socket_timeout=5)
redis_client = redis.Redis(connection_pool=pool)

Interviewer notes: Good answers mention pool sizing and timeout configuration. Red flags: Creating new connections per request; no pool limits.

Q565: How do you test Redis-backed code reliably?​

Technical answer: Use a dedicated test Redis instance or fakeredis for unit tests. For integration tests, spin up Redis in Docker. Test cache hits, misses, TTL expiration, and error handling. Avoid hitting production Redis from tests. Example:

import fakeredis
redis = fakeredis.FakeRedis()

def test_cache():
redis.set("key", "value", ex=60)
assert redis.get("key") == b"value"

Interviewer notes: Good answers separate unit and integration test strategies. Red flags: Tests hitting production Redis; no TTL testing.


Q566: Cache stampede — thousands of requests hit DB at once after expiry​

Level: Senior

Scenario: A popular product page is cached in Redis with TTL 60 seconds. When it expires, 2000 concurrent requests all miss the cache and hit the database simultaneously to recompute the value.

Impact: Database spike. Query latency jumps. Possible DB outage. Users see slow or failed page loads.

Root Cause: No single-flight / locking. All concurrent requests see the missing key and all regenerate it.

Simple explanation: The store runs out of bread. 2000 customers all ask the baker to bake more at once instead of one person baking and sharing.

Technical Answer:

  1. Use a short local lock (Redis SET NX with short TTL) so only one request regenerates; others wait briefly and read the fresh value.
  2. Use probabilistic early expiration: recompute cache slightly before TTL expires (stale-while-revalidate).
  3. Serve stale data while background regenerates (stale-while-revalidate pattern).

Code/Syntax Justification:

import redis, time, json

r = redis.Redis()

def get_product(product_id):
key = f"product:{product_id}"
cached = r.get(key)
if cached:
return json.loads(cached)

lock_key = f"lock:{key}"
acquired = r.set(lock_key, "1", nx=True, ex=10)
if acquired:
try:
value = expensive_db_lookup(product_id)
r.setex(key, 60, json.dumps(value))
return value
finally:
r.delete(lock_key)
else:
time.sleep(0.2)
cached = r.get(key)
if cached:
return json.loads(cached)
return expensive_db_lookup(product_id)

Workflow Diagram:

Request A and B arrive together (cache expired)
|
v
Both check cache -> MISS
|
v
A: SET NX lock -> OK (regenerates)
B: SET NX lock -> FAIL (lock held)
|
v
A: compute value -> write cache (TTL 60s) -> delete lock
B: wait 200ms -> read cache HIT -> return fresh value
|
v
DB hit once instead of twice

🔍 Behind the Question: Cache stampede, single-flight locking, stale-while-revalidate.

❌ The Red Flags: No lock on regeneration; all clients hit DB on expiry; long lock TTL blocking others.


Q567: Redis single-threaded bottleneck under high command rate​

Level: Senior

Scenario: A Redis instance handles 100k+ commands/second. CPU on one core hits 100%. Latency climbs. Redis is single-threaded for command execution, so one core becomes the limit.

Impact: Increased command latency. Timeouts. Application slowdowns.

Root Cause: Redis processes commands sequentially on one thread (IO threads in Redis 6+ handle networking only, not command execution). High command rate saturates that one core.

Simple explanation: One cashier scans every item for every customer. Line grows because only one person works the register.

Technical Answer:

  1. Shard data across multiple Redis instances (Redis Cluster or client-side sharding) so each core handles a subset of keys.
  2. Offload read-heavy workloads to read replicas.
  3. Pipeline commands to reduce round-trips.
  4. Expensive commands (KEYS, SMEMBERS on large sets, FLUSHALL) must be avoided or moved to SCAN/off-peak.

Code/Syntax Justification:

# Pipeline: batch multiple commands into one round-trip
pipe = r.pipeline()
for user_id in user_ids:
pipe.get(f"session:{user_id}")
results = pipe.execute() # one network round-trip

Workflow Diagram:

Without sharding: With sharding (Cluster):
All keys -> Redis Node 1 Keys A-M -> Node 1
(one core bottleneck) Keys N-Z -> Node 2
(two cores, 2x throughput)

🔍 Behind the Question: Redis threading model, sharding, pipelining, avoiding blocking commands.

❌ The Red Flags: Running KEYS in production; single large Redis under high write rate; not pipelining batched commands.


Q568: Cache invalidation — stale data after database update​

Level: Principal

Scenario: A user updates their email in PostgreSQL. The Redis cache still holds the old email. The user logs in with the old email and cannot access their account.

Impact: Data inconsistency. Users see outdated information. Confusion and support tickets.

Root Cause: The database was updated but the cache was not invalidated or updated. No strategy for keeping cache and DB in sync.

Simple explanation: You change your address at the post office, but your neighbor's address book still has your old address. They send mail to the wrong place.

Technical Answer:

  1. Write-through: update DB and cache in the same transaction/logical unit.
  2. Cache-aside with invalidation: update DB first, then delete (not update) the cache key; next read repopulates from DB.
  3. Use short TTL as a safety net so stale data self-heals.
  4. For critical data, use versioned keys or write-through with Redis as the source of truth for reads.

Code/Syntax Justification:

# Cache-aside: delete cache after DB update (safe, simple)
def update_email(user_id, new_email):
db.update_user_email(user_id, new_email)
r.delete(f"user:email:{user_id}") # delete stale cache
# Next read repopulates from DB

Workflow Diagram:

Update Email
|
v
Update PostgreSQL (source of truth)
|
v
DELETE Redis cache key (invalidate)
|
v
Next READ: cache MISS -> read from PostgreSQL -> repopulate Redis
|
v
Consistent data

🔍 Behind the Question: Cache invalidation strategies (cache-aside, write-through, write-behind), TTL safety nets, consistency trade-offs.

❌ The Red Flags: Updating cache before DB (race); no TTL safety net; never invalidating cache.


Q569: Redis persistence and data loss after restart​

Level: Principal

Scenario: Redis restarts after a crash. Data written in the last 5 minutes is gone because only RDB snapshots (every 1 hour) are used, and AOF is disabled.

Impact: Lost sessions, lost rate-limit counters, lost in-flight data. Application errors.

Root Cause: RDB snapshots are point-in-time and can lose up to the last snapshot window. AOF (Append Only File) logs every write for better durability.

Simple explanation: You save your notebook once per hour. If the notebook is lost between saves, you lose everything written since the last save.

Technical Answer:

  1. Enable AOF with appendfsync everysec (good balance of durability and performance) or always (maximum durability, slower).
  2. Use RDB + AOF together for fast restarts and durability.
  3. For critical data (sessions, money), do not rely solely on in-memory Redis; replicate to a durable store.
  4. Use Redis Sentinel or Cluster for high availability.

Code/Syntax Justification:

# redis.conf
appendonly yes
appendfsync everysec # fsync once per second (lose max 1s on crash)
save 900 1 # RDB snapshot: 900s if 1+ key changed
save 300 10
save 60 10000

Workflow Diagram:

Write: SET key value
|
v
Redis memory updated
|
+-- appendfsync everysec --> written to AOF within 1s
|
+-- RDB snapshot (hourly) --> point-in-time backup
|
v
Crash restart: load RDB + replay AOF since snapshot
|
v
Data loss window: only last 1 second (with everysec)

🔍 Behind the Question: Persistence options (RDB vs AOF), durability vs performance trade-offs, HA with Sentinel/Cluster.

❌ The Red Flags: RDB-only with long snapshot window for critical data; no AOF; no replication for HA.


Q570: Split-brain in Redis Cluster after network partition​

Level: Principal

Scenario: A Redis Cluster with 3 masters and 3 replicas suffers a network partition. One side has 2 masters + 1 replica, the other has 1 master + 2 replicas. Clients on both sides can write to different masters. When the network heals, data conflicts.

Impact: Data divergence. Lost writes. Inconsistent state. Manual reconciliation needed.

Root Cause: Redis Cluster does not prevent writes on the minority side during a partition (no built-in fencing by default). Each partition continues accepting writes.

Simple explanation: Two offices lose phone contact. Both keep taking orders. When phones return, they have different order lists for the same customers.

Technical Answer:

  1. Use cluster-require-full-coverage yes so the cluster stops accepting writes when not all hash slots are covered.
  2. Ensure quorum: odd number of masters, cluster-node-timeout tuned.
  3. Use Redis Sentinel with a quorum for failover decisions.
  4. For strong consistency, accept writes only on the primary side verified by a consensus layer (or use a CP system like etcd for coordination).

Code/Syntax Justification:

# redis.conf (on each cluster node)
cluster-enabled yes
cluster-require-full-coverage yes # stop writes if slots uncovered
cluster-node-timeout 5000

Workflow Diagram:

Network Partition
|
v
Side A (2 masters, 1 replica) Side B (1 master, 2 replicas)
accepts writes accepts writes
| |
v v
Data diverges (conflicting writes)
|
v
Network heals -> cluster-require-full-coverage yes -> rejects writes until healed
|
v
Manual reconciliation or last-write-wins

🔍 Behind the Question: CAP theorem for Redis Cluster, split-brain, quorum, consistency vs availability trade-offs.

❌ The Red Flags: Assuming Redis Cluster prevents split-brain by default; writing to both partitions; no quorum/failover tuning.



Senior / Principal — Real World Scenarios​

Q571: Cache stampede — thousands of requests hit DB at once after expiry​

Level: Senior

Scenario: A popular product page is cached in Redis with TTL 60 seconds. When it expires, 2000 concurrent requests all miss the cache and hit the database simultaneously to recompute the value.

Impact: Database spike. Query latency jumps. Possible DB outage. Users see slow or failed page loads.

Root Cause: No single-flight / locking. All concurrent requests see the missing key and all regenerate it.

Simple explanation: The store runs out of bread. 50 customers all ask the baker to bake more at once instead of one person baking and sharing.

Fix:

  1. Use a short local lock (Redis SET NX with short TTL) so only one request regenerates; others wait briefly and read the fresh value.
  2. Use probabilistic early expiration: recompute cache slightly before TTL expires (stale-while-revalidate).
  3. Serve stale data while background regenerates (stale-while-revalidate pattern).

Code:

import redis, time, json

r = redis.Redis()

def get_product(product_id):
key = f"product:{product_id}"
cached = r.get(key)
if cached:
return json.loads(cached)

# Try to acquire regeneration lock
lock_key = f"lock:{key}"
acquired = r.set(lock_key, "1", nx=True, ex=10) # 10s lock
if acquired:
try:
value = expensive_db_lookup(product_id)
r.setex(key, 60, json.dumps(value))
return value
finally:
r.delete(lock_key)
else:
# Another request is regenerating; wait briefly then retry
time.sleep(0.2)
cached = r.get(key)
if cached:
return json.loads(cached)
return expensive_db_lookup(product_id) # fallback

Workflow diagram:

Request A and B arrive together (cache expired)
|
v
Both check cache -> MISS
|
v
A: SET NX lock -> OK (regenerates)
B: SET NX lock -> FAIL (lock held)
|
v
A: compute value -> write cache (TTL 60s) -> delete lock
B: wait 200ms -> read cache HIT -> return fresh value
|
v
DB hit once instead of twice

Interviewer notes: Tests cache stampede, single-flight locking, and stale-while-revalidate.

Red flags: No lock on cache regeneration; all clients hit DB on expiry; long lock TTL blocking others.


Q572: Redis single-threaded bottleneck under high command rate​

Level: Senior

Scenario: A Redis instance handles 100k+ commands/second. CPU on one core hits 100%. Latency climbs. Redis is single-threaded for command execution, so one core becomes the limit.

Impact: Increased command latency. Timeouts. Application slowdowns.

Root Cause: Redis processes commands sequentially on one thread (IO threads in Redis 6+ handle networking only, not command execution). High command rate saturates that one core.

Simple explanation: One cashier scans every item for every customer. Line grows because only one person works the register.

Fix:

  1. Shard data across multiple Redis instances (Redis Cluster or client-side sharding) so each core handles a subset of keys.
  2. Offload read-heavy workloads to read replicas.
  3. Pipeline commands to reduce round-trips.
  4. Expensive commands (KEYS, SMEMBERS on large sets, FLUSHALL) must be avoided or moved to SCAN/off-peak.

Code:

# Pipeline: batch multiple commands into one round-trip
pipe = r.pipeline()
for user_id in user_ids:
pipe.get(f"session:{user_id}")
results = pipe.execute() # one network round-trip

Workflow diagram:

Without sharding: With sharding (Cluster):
All keys -> Redis Node 1 Keys A-M -> Node 1
(one core bottleneck) Keys N-Z -> Node 2
(two cores, 2x throughput)

Interviewer notes: Tests Redis threading model, sharding, pipelining, and avoiding blocking commands.

Red flags: Running KEYS in production; single large Redis under high write rate; not pipelining batched commands.


Q573: Cache invalidation — stale data after database update​

Level: Principal

Scenario: A user updates their email in PostgreSQL. The Redis cache still holds the old email. The user logs in with the old email and cannot access their account.

Impact: Data inconsistency. Users see outdated information. Confusion and support tickets.

Root Cause: The database was updated but the cache was not invalidated or updated. No strategy for keeping cache and DB in sync.

Simple explanation: You change your address at the post office, but your neighbor's address book still has your old address. They send mail to the wrong place.

Fix:

  1. Write-through: update DB and cache in the same transaction/logical unit.
  2. Cache-aside with invalidation: update DB first, then delete (not update) the cache key; next read repopulates from DB.
  3. Use short TTL as a safety net so stale data self-heals.
  4. For critical data, use versioned keys or write-through with Redis as the source of truth for reads.

Code:

# Cache-aside: delete cache after DB update (safe, simple)
def update_email(user_id, new_email):
db.update_user_email(user_id, new_email)
r.delete(f"user:email:{user_id}") # delete stale cache
# Next read repopulates from DB

Workflow diagram:

Update Email
|
v
Update PostgreSQL (source of truth)
|
v
DELETE Redis cache key (invalidate)
|
v
Next READ: cache MISS -> read from PostgreSQL -> repopulate Redis
|
v
Consistent data

Interviewer notes: Tests cache invalidation strategies (cache-aside, write-through, write-behind), TTL safety nets, and consistency trade-offs.

Red flags: Updating cache before DB (race); no TTL safety net; never invalidating cache.


Q574: Redis persistence and data loss after restart​

Level: Principal

Scenario: Redis restarts after a crash. Data written in the last 5 minutes is gone because only RDB snapshots (every 1 hour) are used, and AOF is disabled.

Impact: Lost sessions, lost rate-limit counters, lost in-flight data. Application errors.

Root Cause: RDB snapshots are point-in-time and can lose up to the last snapshot window. AOF (Append Only File) logs every write for better durability.

Simple explanation: You save your notebook once per hour. If the notebook is lost between saves, you lose everything written since the last save.

Fix:

  1. Enable AOF with appendfsync everysec (good balance of durability and performance) or always (maximum durability, slower).
  2. Use RDB + AOF together for fast restarts and durability.
  3. For critical data (sessions, money), do not rely solely on in-memory Redis; replicate to a durable store.
  4. Use Redis Sentinel or Cluster for high availability.

Code:

# redis.conf
appendonly yes
appendfsync everysec # fsync once per second (lose max 1s on crash)
save 900 1 # RDB snapshot: 900s if 1+ key changed
save 300 10
save 60 10000

Workflow diagram:

Write: SET key value
|
v
Redis memory updated
|
+-- appendfsync everysec --> written to AOF within 1s
|
+-- RDB snapshot (hourly) --> point-in-time backup
|
v
Crash restart: load RDB + replay AOF since snapshot
|
v
Data loss window: only last 1 second (with everysec)

Interviewer notes: Tests persistence options (RDB vs AOF), durability vs performance trade-offs, and HA with Sentinel/Cluster.

Red flags: RDB-only with long snapshot window for critical data; no AOF; no replication for HA.


Q575: Split-brain in Redis Cluster after network partition​

Level: Principal

Scenario: A Redis Cluster with 3 masters and 3 replicas suffers a network partition. One side has 2 masters + 1 replica, the other has 1 master + 2 replicas. Clients on both sides can write to different masters. When the network heals, data conflicts.

Impact: Data divergence. Lost writes. Inconsistent state. Manual reconciliation needed.

Root Cause: Redis Cluster does not prevent writes on the minority side during a partition (no built-in fencing by default). Each partition continues accepting writes.

Simple explanation: Two offices lose phone contact. Both keep taking orders. When phones return, they have different order lists for the same customers.

Fix:

  1. Use cluster-require-full-coverage yes so the cluster stops accepting writes when not all hash slots are covered.
  2. Ensure quorum: odd number of masters, cluster-node-timeout tuned.
  3. Use Redis Sentinel with a quorum for failover decisions.
  4. For strong consistency, accept writes only on the primary side verified by a consensus layer (or use a CP system like etcd for coordination).

Code:

# redis.conf (on each cluster node)
cluster-enabled yes
cluster-require-full-coverage yes # stop writes if slots uncovered
cluster-node-timeout 5000

Workflow diagram:

Network Partition
|
v
Side A (2 masters, 1 replica) Side B (1 master, 2 replicas)
accepts writes accepts writes
| |
v v
Data diverges (conflicting writes)
|
v
Network heals -> cluster-require-full-coverage yes -> rejects writes until healed
|
v
Manual reconciliation or last-write-wins

Interviewer notes: Tests CAP theorem for Redis Cluster, split-brain, quorum, and consistency vs availability trade-offs.

Red flags: Assuming Redis Cluster prevents split-brain by default; writing to both partitions; no quorum/failover tuning.