Top 50 Redis Interview Questions & Answers (2026)
About Redis
Top 50 Redis interview questions covering data structures, caching, persistence, clustering, and real-world use cases. Companies hiring for Redis roles test this knowledge at every stage — from first-round screens that check the basics to final-round conversations about real-world trade-offs.
What to Expect in a Redis Interview
Expect a mix of conceptual and practical Redis questions: clear definitions and core-concept checks for junior roles, hands-on scenario questions for mid-level roles, and architecture or trade-off discussions for senior roles. Interviewers usually move from foundational topics toward the kind of problems you'd actually face on the job.
How to Use This Guide
Work through the Redis questions in order — Beginner, then Intermediate, then Advanced — so each concept builds on the last. Every question has its own page; bookmark the ones that trip you up and revisit them the day before your interview.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
Core concepts every Redis developer must know.
01
What is Redis?
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and queue. It was created by Salvatore Sanfilippo in 2009 and is now maintained by Redis Ltd. Redis stores all data in RAM, which makes reads and writes extremely fast — typically under a millisecond. It supports a wide variety of data structures including strings, lists, sets, sorted sets, hashes, streams, bitmaps, and HyperLogLogs, going far beyond a simple key-value store. It is one of the most popular tools in modern backend architecture for caching, session storage, and real-time processing.
02
How is Redis different from a traditional disk-based database?
The fundamental difference is storage location: traditional databases (PostgreSQL, MySQL) store data on disk and load pages into memory on demand, while Redis stores the entire dataset in RAM. This makes Redis orders of magnitude faster — disk reads are measured in milliseconds, while Redis operations typically complete in under 100 microseconds. The tradeoff is that Redis is limited by available RAM and data is at risk of loss on a crash (mitigated by persistence options). Redis is therefore used as a complement to disk databases: the disk database is the source of truth; Redis serves as a high-speed cache layer. Redis also supports optional persistence to disk via RDB snapshots and AOF logging.
03
What are the five core Redis data types?
Redis supports five core data types. String: the simplest type, stores text, integers, or binary data up to 512MB — used for caching, counters, and flags. List: an ordered, doubly linked list of strings supporting push/pop from both ends — used for queues, activity feeds, and recent items. Set: an unordered collection of unique strings — used for tags, unique visitors, and social graph relationships. Sorted Set: like a Set but each member has a score (float) and members are ordered by score — used for leaderboards and priority queues. Hash: a map of field-value pairs within one key — used to represent objects like user profiles. Each type has its own set of atomic commands optimized for its use case.
04
What do the SET and GET commands do in Redis?
SET key value stores a string value under the given key, overwriting any existing value. GET key retrieves the value for a key, returning nil if the key doesn't exist. SET also supports several important options in one atomic command: EX seconds sets a Time-To-Live (TTL) so the key expires automatically, NX only sets the key if it doesn't already exist (useful for distributed locks), and XX only sets it if the key already exists. Example: SET session:user123 "data" EX 3600 NX atomically creates a session key that expires in one hour only if it doesn't already exist — a single-command distributed locking primitive.
05
How does TTL (Time-To-Live) work in Redis?
TTL in Redis allows keys to automatically expire and be deleted after a set duration, which is fundamental to cache management. EXPIRE key seconds sets a TTL on an existing key. TTL key returns the remaining time in seconds (-1 means no expiry; -2 means the key doesn't exist). PERSIST key removes the TTL, making the key permanent again. You can also use EXPIREAT key unix-timestamp to expire at a specific absolute time, or PEXPIRE/PTTL for millisecond precision. Redis uses a combination of passive expiration (detected on access) and active expiration (background sampling) to evict expired keys without scanning the entire keyspace on every cycle.
06
What is the difference between Redis and Memcached?
Both Redis and Memcached are in-memory caches, but Redis is significantly more capable. Data types: Memcached only supports plain string key-value pairs; Redis supports Strings, Lists, Sets, Sorted Sets, Hashes, Streams, and more. Persistence: Memcached has no persistence — all data is lost on restart; Redis supports RDB snapshots and AOF logs. Replication and clustering: Redis has built-in primary-replica replication and Cluster mode; Memcached requires client-side sharding. Atomic operations: Redis supports complex atomic operations like INCR, LPUSH, Lua scripts, and transactions; Memcached only has add/incr/decr. Choose Memcached only for the simplest caching use case where you need multi-threaded memory efficiency; choose Redis for almost everything else.
07
What are the Redis persistence options (RDB and AOF)?
Redis provides two persistence mechanisms. RDB (Redis Database) takes point-in-time snapshots of the entire dataset and saves them to disk as a compact binary .rdb file, configured with rules like "save every 60 seconds if at least 100 keys changed." RDB is fast to restore, produces small files, but can lose up to several minutes of data. AOF (Append-Only File) logs every write command in a text file. On restart, Redis replays the log to reconstruct the dataset. AOF is more durable (can be configured to fsync on every write) but produces larger files and slower restarts. You can enable both simultaneously for maximum durability — Redis will use the AOF for recovery because it's more complete. A third option since Redis 7 is RDB+AOF hybrid persistence.
08
What is Redis Pub/Sub?
Redis Pub/Sub (Publish/Subscribe) is a messaging pattern where publishers send messages to channels and subscribers receive all messages published to the channels they are subscribed to. Use SUBSCRIBE channel to subscribe, PUBLISH channel message to send, and UNSUBSCRIBE to unsubscribe. Subscribers receive messages in real time. A key limitation of Redis Pub/Sub is that messages are fire-and-forget — if a subscriber is offline when a message is published, it never receives it, and messages are not persisted. For durable messaging where consumers need to process messages reliably even after reconnecting, use Redis Streams instead. Pub/Sub is suitable for real-time notifications, live chat, and live dashboards.
09
What are common real-world use cases for Redis?
Redis is versatile and used in many production scenarios. Caching: storing results of expensive database queries, API responses, or rendered HTML fragments to serve subsequent requests in microseconds. Session storage: web application sessions stored in Redis with a TTL, enabling stateless application servers and horizontal scaling. Rate limiting: using INCR with EXPIRE to count requests per IP per minute. Leaderboards: Sorted Sets power real-time game scoreboards with ZADD and ZRANGE. Queues and job management: Lists used as FIFO queues for background job processing (Laravel Queue, Sidekiq). Pub/Sub messaging: broadcasting real-time notifications to connected clients. Distributed locking: using SET NX EX to ensure only one process performs a critical operation at a time.
10
What is Redis pipelining?
Redis pipelining allows a client to send multiple commands to the server without waiting for the reply to each one, then read all replies in one batch. Without pipelining, each command incurs a round-trip network latency (RTT). With pipelining, you send N commands in one network trip and receive N replies at once, dramatically reducing the total time when performing many operations. Pipelining is a client-side optimization — the Redis server still processes commands one by one. For example, inserting 1,000 cache keys individually might take 1,000 × 0.5ms = 500ms in latency alone; pipelining reduces this to approximately one RTT regardless of batch size. All major Redis client libraries support pipelining.
11
What does it mean that Redis operations are atomic?
Redis is single-threaded for command processing — it executes one command at a time, in order, with no concurrent interleaving. This means every Redis command is inherently atomic: either it fully executes or it doesn't; no two commands can execute simultaneously and interfere with each other's state. This makes Redis ideal for implementing distributed counters, rate limiters, and locks. For example, INCR atomically reads a value, increments it, and writes it back — in any other system this read-modify-write would require a lock to prevent race conditions. Lua scripts and MULTI/EXEC transactions extend this atomicity to groups of commands that must execute without interruption.
12
What are the INCR and DECR commands in Redis?
INCR key atomically increments the integer value of a key by 1 and returns the new value. If the key doesn't exist, it is initialized to 0 before the operation, so INCR on a non-existent key returns 1. DECR key decrements by 1. INCRBY key amount and DECRBY key amount allow incrementing/decrementing by arbitrary integers. INCRBYFLOAT works with decimal numbers. These commands are the foundation for many Redis patterns: page view counters (INCR page:home:views), rate limiting (INCR + EXPIRE on a per-minute key), inventory management (decrement stock atomically), and generating auto-incrementing IDs for distributed systems where a central counter is acceptable.
13
What are LPUSH, RPUSH, LPOP, and RPOP in Redis?
These commands operate on Redis Lists. LPUSH key val inserts one or more values at the head (left) of the list, while RPUSH key val inserts at the tail (right). LPOP key removes and returns the first (leftmost) element; RPOP key removes and returns the last (rightmost) element. By combining these, you implement common data structures: RPUSH + LPOP gives a FIFO queue (enqueue on the right, dequeue from the left). RPUSH + RPOP gives a LIFO stack. LRANGE key 0 -1 retrieves all elements without consuming them. BLPOP/BRPOP are the blocking variants — the client waits until an element is available, useful for job queues.
14
What are SADD and SMEMBERS in Redis?
SADD key member [member ...] adds one or more members to a Redis Set, silently ignoring duplicates (Sets only store unique values). SMEMBERS key returns all members of the Set in an arbitrary order. Redis Sets support powerful set-theory operations: SUNION (union of multiple sets), SINTER (intersection), SDIFF (difference). These make Sets ideal for social features: "mutual friends" is SINTER of two friend sets; "you may know" is SDIFF; "combined tags" is SUNION. SISMEMBER key member checks membership in O(1) time. For very large sets where memory is a concern and approximate answers are acceptable, consider HyperLogLog instead of Sets for counting unique elements.
15
What are ZADD and ZRANGE in Redis?
ZADD key score member adds a member with a numeric score to a Redis Sorted Set. Members are unique but scores can repeat; members are always stored in ascending score order. ZRANGE key start stop retrieves members by index range in ascending score order; add REV for descending. For leaderboards, ZREVRANGE key 0 9 returns the top 10 highest-scoring members. ZRANK key member returns a member's rank (0-based). ZSCORE key member gets a member's score. ZINCRBY key amount member atomically updates a score, making it perfect for live leaderboards where game scores update frequently. Sorted Sets are the go-to data structure for any ranking, scoring, or priority queue use case in Redis.
16
What are HSET and HGET in Redis?
HSET key field value [field value ...] sets one or more field-value pairs in a Redis Hash. HGET key field retrieves the value of one field. HGETALL key returns all field-value pairs as a flat list. Hashes are ideal for representing objects: instead of serializing a user object to JSON (a String), you store each attribute as a Hash field — HSET user:42 name "Alice" email "alice@example.com" age 30. This lets you read or update individual fields without fetching and re-serializing the entire object. HINCRBY key field amount atomically increments a numeric field, useful for per-user counters. Redis internally uses a compact encoding (listpack) for small hashes, making them very memory-efficient for caching object data.
17
What are Redis SELECT databases?
Redis supports multiple logical databases within a single server instance, numbered 0 through 15 by default (configurable with databases in redis.conf). The SELECT index command switches the current connection to the specified database. Each database is completely isolated — keys in database 0 are not visible in database 1. By default, connections start on database 0. However, Redis Cluster does not support multiple databases — it only uses database 0. In practice, using multiple databases to separate concerns (e.g., cache in DB 0, sessions in DB 1) is generally discouraged in modern usage; running separate Redis instances or using key prefixes (e.g., cache:, session:) is preferred for clarity and compatibility with Cluster mode.
18
How does Redis AUTH work?
Redis AUTH provides password-based authentication. Set a password in redis.conf with requirepass yourpassword. Clients must then send AUTH yourpassword before any other command or they receive a NOAUTH error. Redis 6+ introduced ACL (Access Control Lists), which is a major upgrade: you can create multiple users (ACL SETUSER) with different passwords and fine-grained command and key permissions — e.g., a read-only user that can only run GET and HGET on keys matching cache:*. ACLs are the modern, recommended approach over the legacy single-password requirepass for any production deployment. Always use TLS (via stunnel or Redis 6's native TLS) alongside AUTH when Redis is exposed over a network.
19
What does FLUSHDB do in Redis?
FLUSHDB deletes all keys in the currently selected database. FLUSHALL deletes all keys across all databases on the Redis server. Both commands are synchronous by default (blocking until complete) and accept an ASYNC modifier (FLUSHDB ASYNC) to perform deletion in a background thread so the server remains responsive during the operation — important on large datasets. These are destructive operations with no confirmation prompt, so they must be used with extreme caution in production environments. Many teams restrict access to these commands via ACLs. Common legitimate uses: resetting a test/staging environment, clearing a cache namespace during a deployment, or recovering from corrupted state.
20
What does the Redis INFO command return?
The INFO command returns a large block of key-value statistics about the Redis server, organized into sections. Key sections: server (Redis version, OS, uptime), clients (number of connected clients, blocked clients), memory (used_memory, max_memory, memory fragmentation ratio — critical for capacity planning), stats (total_commands_processed, keyspace_hits, keyspace_misses — use misses/hits to calculate cache hit rate), replication (role: master/replica, connected replicas, replication lag), keyspace (per-database key counts with TTL statistics). You can request a specific section: INFO memory or INFO replication. This is the first command to run when diagnosing Redis performance or capacity issues.
Practical knowledge for developers with hands-on experience.
01
What is Redis Cluster and how does it shard data?
Redis Cluster is Redis's built-in horizontal scaling solution that automatically partitions data across multiple nodes. It uses a fixed keyspace of 16,384 hash slots. When a key is written, Redis computes CRC16(key) % 16384 to determine the slot. Each master node owns a range of slots — in a 3-master cluster, node A owns slots 0–5460, node B 5461–10922, node C 10923–16383. Each master has one or more replicas for high availability. The client is redirected with a MOVED response if it hits the wrong node. Cluster also supports hash tags: keys with the same content inside {} always land on the same slot, enabling multi-key operations like MSET {user:1}:name and {user:1}:email to coexist on one node.
02
What is the difference between Redis Sentinel and Redis Cluster?
Redis Sentinel provides high availability for a single Redis dataset — it monitors master and replica nodes, automatically promotes a replica to master if the master fails, and updates clients via a service discovery mechanism. It does NOT partition data across nodes — the entire dataset lives on one master. Redis Cluster provides both high availability and horizontal scalability by partitioning the dataset across multiple master nodes, each with its own replicas. Use Sentinel when your dataset fits on one node and you primarily need automatic failover. Use Cluster when your dataset is too large for one node or you need write throughput across multiple nodes. Sentinel is simpler to operate; Cluster adds complexity but enables true scale-out.
03
How do MULTI and EXEC work in Redis transactions?
MULTI begins a Redis transaction. All commands issued after MULTI are queued but not executed immediately — the server responds with QUEUED for each. EXEC atomically executes all queued commands in order and returns an array of results. DISCARD cancels the transaction and discards the queue. Important caveats: Redis transactions provide atomicity (all commands execute in sequence without interruption) but NOT rollback — if a command fails mid-transaction (e.g., wrong type for an operation), the other commands still execute. This is unlike SQL transactions. Also, MULTI/EXEC does not provide isolation from reads in other clients during the queuing phase — use WATCH for optimistic locking. Lua scripts via EVAL are an alternative that provides stronger atomicity guarantees.
04
What is WATCH and optimistic locking in Redis?
WATCH key [key ...] implements optimistic locking in Redis. After calling WATCH, if any watched key is modified by another client before EXEC is called, the transaction is aborted — EXEC returns nil instead of executing the queued commands. The typical pattern is: (1) WATCH a key, (2) read its value, (3) start MULTI, (4) queue write commands based on the read value, (5) EXEC — if it returns nil, retry from step 1. This implements a check-and-set (CAS) operation, enabling race-free read-modify-write cycles without pessimistic locking. Use WATCH for low-contention scenarios like updating a user's balance based on its current value. Under high contention (many concurrent retries), Lua scripting is more efficient as it runs atomically without needing retries.
05
What is Lua scripting in Redis and when should you use it?
Redis supports executing Lua scripts atomically on the server via EVAL script numkeys key [key ...] arg [arg ...]. The entire script runs as a single atomic unit — no other command can execute between Lua operations. This is stronger than MULTI/EXEC because Lua allows conditional logic: you can read a value inside the script and branch based on it before writing, which is impossible in a MULTI block (where all commands are queued before any result is known). Common uses: complex atomic operations like "check inventory and decrement if available," rate limiting with fine-grained logic, and distributed lock implementation. Use EVALSHA to execute a pre-loaded script by its SHA1 hash, avoiding repeated network transfer of the script body.
06
What are Redis eviction policies?
When Redis reaches its maxmemory limit, it must evict keys to free space. The eviction policy is set via maxmemory-policy in redis.conf. Key policies: noeviction (default) — returns an error on writes instead of evicting, safe but breaks your app when full. allkeys-lru — evicts the least recently used key across all keys, best for general caching. volatile-lru — LRU eviction only among keys with a TTL set, preserving keys without expiry. allkeys-lfu — evicts the least frequently used key (Redis 4+), better than LRU for skewed access patterns. volatile-ttl — evicts keys with the shortest remaining TTL first. allkeys-random/volatile-random — random eviction. For a pure cache where all data is re-fetchable, allkeys-lru or allkeys-lfu is recommended.
07
What is HyperLogLog in Redis?
HyperLogLog is a probabilistic data structure in Redis that estimates the cardinality (number of unique elements) of a set with very low memory usage — approximately 12KB per HyperLogLog, regardless of the number of unique elements counted. PFADD key element [element ...] adds elements; PFCOUNT key [key ...] returns the estimated unique count. The error rate is approximately 0.81%. This is ideal for counting unique page views, unique visitors, or unique searches at massive scale where storing every individual user ID in a Set would consume enormous memory. For example, counting unique daily visitors across millions of users uses 12KB instead of potentially gigabytes. PFMERGE merges multiple HyperLogLogs, enabling counting unique visitors across date ranges.
08
What are Redis Streams?
Redis Streams (introduced in Redis 5.0) is a persistent, append-only log data structure similar to Apache Kafka, but built into Redis. Each entry has an auto-generated ID (timestamp-sequence, e.g., 1700000000000-0) and contains field-value pairs. XADD stream * field value appends an entry. XREAD COUNT 10 STREAMS stream 0 reads entries. Key features: Consumer Groups (XGROUP) allow multiple consumers to process different entries from the same stream in parallel, with acknowledgement (XACK) to track processed entries — similar to Kafka consumer groups. This enables reliable, at-least-once processing of events, overcoming the fire-and-forget limitation of Pub/Sub. Use Streams for event sourcing, activity feeds, and durable inter-service messaging within a Redis environment.
09
What are Redis Geospatial commands?
Redis has built-in geospatial support using a Sorted Set internally, where the score is a Geohash encoding of the longitude and latitude. GEOADD key lon lat member adds a location. GEODIST key member1 member2 [unit] returns the distance between two members in meters, kilometers, miles, or feet. GEOPOS key member returns the coordinates of a member. GEORADIUS and GEOSEARCH (Redis 6.2+, preferred) find members within a given radius of a point or bounding box, with optional sorting and limiting. Practical use cases: finding nearby stores, drivers, or restaurants within 5km; proximity-based matching in ride-sharing apps; location-aware search. The underlying Geohash provides approximately 0.6m precision at maximum resolution.
10
What is RedisBloom (Bloom Filter in Redis)?
A Bloom Filter is a probabilistic data structure that answers "Is this element in the set?" with either definitely not or probably yes. It uses a fixed amount of memory and has zero false negatives but a configurable false positive rate. RedisBloom is a Redis module (part of Redis Stack) that adds Bloom Filters natively. BF.ADD key element adds to the filter; BF.EXISTS key element checks membership. Bloom Filters are ideal for cache-miss optimization: before hitting the database for a key, check the Bloom Filter — if it says "not present," skip the database entirely, preventing cache penetration attacks (malicious requests for non-existent keys). They are also used in duplicate URL detection, username availability checks at scale, and spam filtering.
11
How do you implement rate limiting in Redis?
A simple Redis rate limiter uses INCR and EXPIRE. For each request, INCR user:$id:requests:$minute atomically increments the count. On the first request of each minute, set EXPIRE user:$id:requests:$minute 60 to reset automatically. If the count exceeds the limit, reject the request. A more robust approach uses a Lua script to make the increment + TTL check atomic and avoid the race condition where a key might be incremented but EXPIRE never called. The Sliding Window Log pattern (using a Sorted Set with timestamps as scores and ZRANGEBYSCORE to count recent requests within the window) is more accurate but uses more memory. The Token Bucket / Leaky Bucket algorithms can also be implemented via Lua scripts for smooth rate control.
12
How does distributed locking work in Redis?
A Redis distributed lock uses the atomic SET key value NX PX milliseconds command (Set if Not eXists, with expiry). If it returns OK, the caller acquired the lock; if nil, the lock is held by someone else. The value should be a unique random token (UUID) per lock holder, so only the holder can release it. To release, a Lua script atomically checks that the key's value matches the caller's token before deleting — preventing a process from releasing another's lock. The expiry is a safety net: if the lock holder crashes, the lock auto-expires and prevents deadlock. Redlock is Redis's algorithm for distributed locking across multiple independent Redis nodes (typically 5), providing stronger guarantees when no single Redis instance should be a single point of failure. Libraries like Redisson (Java) and node-redlock implement this.
13
What is the cache-aside pattern vs write-through caching?
Cache-aside (lazy loading): the application checks Redis first; on a miss, it reads from the database and writes the result into Redis before returning it. The cache is populated on demand. Pros: only requested data is cached, cache is small. Cons: the first request always hits the database (cold start), and cache and database can be briefly inconsistent. Write-through: every write goes to the cache and the database simultaneously (or the cache proxies the database write). Pros: cache is always consistent with the database; no cold-start miss. Cons: every write is slower (two writes), and infrequently read data wastes cache space. Write-behind (write-back): writes go to the cache first and are asynchronously written to the database later — fastest writes but risk of data loss if the cache crashes before syncing. Cache-aside is by far the most common pattern in practice.
14
How does Redis replication work?
Redis replication uses a primary-replica (formerly master-slave) model. A replica connects to a primary with REPLICAOF primary-ip port. On initial sync, the primary forks, saves an RDB snapshot, and sends it to the replica, which loads it. After that, the primary sends a stream of write commands to the replica in real time. Replication is asynchronous by default — the primary doesn't wait for replicas to confirm writes before responding to clients. This means replicas can lag behind the primary. WAIT numreplicas timeout blocks until at least N replicas have acknowledged all previous writes. Replicas are read-only by default, offloading read traffic from the primary. One primary can have multiple replicas, and replicas can themselves have sub-replicas, forming a tree topology for large-scale read distribution.
15
What is the Redis slow log?
The Redis slow log records commands that exceed a configurable execution time threshold (slowlog-log-slower-than, in microseconds, default 10,000 = 10ms; set to 0 to log all, -1 to disable). SLOWLOG GET [count] retrieves the most recent slow entries, showing the command, arguments, timestamp, and execution duration. SLOWLOG LEN shows the number of entries; SLOWLOG RESET clears it. The slow log is essential for diagnosing performance issues — common findings include: KEYS * or SMEMBERS on huge sets blocking the server, unindexed range scans, or excessive Lua script execution time. Unlike application-level logging, the slow log measures pure server-side processing time, excluding network I/O.
16
What is OBJECT ENCODING in Redis?
OBJECT ENCODING key returns the internal memory encoding Redis is using for a key's value. Redis automatically selects the most memory-efficient encoding based on the value's size and content. For example, a Hash with fewer than 128 fields and values under 64 bytes uses listpack (formerly ziplist), a very compact contiguous memory format. Once it grows beyond those thresholds, it is converted to hashtable, which is faster but uses more memory. Strings use int encoding for integers, embstr for short strings (≤44 bytes), and raw for longer strings. Understanding encodings is important for memory optimization — keeping your data structures below the threshold limits (tunable with hash-max-listpack-entries, etc.) keeps them compact and cache-friendly.
17
What are Redis keyspace notifications?
Keyspace notifications allow clients to subscribe to Pub/Sub channels that publish events when certain Redis operations occur on keys. Enable them in redis.conf with notify-keyspace-events (e.g., KEA for all events). Two types of notifications are published: keyspace notifications (on channel __keyspace@db__:key, receive the event name) and keyevent notifications (on channel __keyevent@db__:event, receive the key name). Common use cases: triggering application logic when a key expires (expired event) — implementing a delayed job queue or session expiry cleanup; auditing which keys are being accessed; invalidating application-level caches in other systems when data changes. Note that expired event notifications have a small delay and are not guaranteed to fire exactly at expiry time.
18
What are CLIENT commands in Redis?
Redis provides a family of CLIENT commands for managing client connections. CLIENT LIST returns information about all connected clients (ID, address, name, command, age, idle time, flags, memory usage) — essential for debugging connection leaks or finding rogue long-running commands. CLIENT SETNAME name assigns a human-readable name to the current connection, which appears in CLIENT LIST output and makes monitoring easier. CLIENT KILL terminates a specific client connection by ID or address. CLIENT PAUSE milliseconds temporarily stops processing client commands, useful during maintenance. CLIENT NO-EVICT ON protects a connection from being killed when Redis is under memory pressure and killing idle clients. CLIENT GETNAME returns the current connection's name.
19
What is CLIENT TRACKING in Redis (client-side caching)?
Client-side caching (introduced in Redis 6) allows application-level caches that are automatically invalidated by Redis. When a client opts in with CLIENT TRACKING ON, Redis records which keys each client has read. When any of those keys are modified, Redis sends an invalidation message to the client via a dedicated invalidation channel, telling it to evict its local copy. This enables a two-tier cache: the local in-process cache (nanosecond access) backed by Redis (sub-millisecond access) without stale data risk. Two modes: default mode (Redis tracks per-connection), and broadcasting mode (Redis sends invalidations for all writes to a key prefix, simpler but higher network overhead). This is one of Redis 6's most powerful features for ultra-high-performance applications.
20
How do you work around cross-slot transaction limitations in Redis Cluster?
Redis Cluster restricts multi-key commands (MGET, MSET, SUNION, MULTI/EXEC with multiple keys) to keys that reside in the same hash slot. The primary workaround is hash tags: enclose the common part of the key name in {} — e.g., {user:42}:profile and {user:42}:settings both hash on user:42, guaranteeing they land on the same slot. This allows atomic multi-key operations on logically related data. Alternative approaches: (1) redesign to avoid multi-key operations, using a single Hash for related fields instead of multiple keys. (2) Use Lua scripts — EVAL can access multiple keys only if they all hash to the same slot (enforced by Cluster). (3) Use Redis Cluster's WAIT and application-level coordination for operations that genuinely span slots, accepting eventual consistency.
Deep expertise questions for senior and lead roles.
01
How does Redis Cluster sharding and the hash slot algorithm work in detail?
Redis Cluster divides the keyspace into exactly 16,384 hash slots. For a given key, the slot is computed as CRC16(keyname) % 16384. If the key contains a hash tag (text inside {}), only the content within the braces is hashed — this is the mechanism for co-locating related keys. Slots are assigned to master nodes in ranges; when a node is added or removed, slots are migrated atomically using the CLUSTER SETSLOT MIGRATING and IMPORTING states. During migration, the server returns an ASK redirect for keys in a migrating slot, which differs from a permanent MOVED redirect. Smart clients maintain a slot-to-node map, updating it on MOVED responses. The choice of 16,384 (not a larger number) was a deliberate trade-off: the cluster gossip protocol heartbeat includes the full slot bitmap — at 16,384 bits, this is 2KB, an acceptable overhead; at 65,536 it would be 8KB, too large for frequent gossip messages between all nodes.
02
What is consistent hashing and how does it compare to Redis Cluster's approach?
Consistent hashing places both nodes and keys on a conceptual ring. Each key is assigned to the nearest node clockwise on the ring. When a node is added or removed, only the keys on one segment of the ring are remapped — O(K/N) keys on average, rather than remapping all keys. This minimizes data movement on topology changes. Redis Cluster uses a different approach: fixed hash slots assigned to nodes. When a node joins, an administrator explicitly migrates a subset of slots to it. This gives more predictable, operator-controlled data distribution. The tradeoff: consistent hashing is more self-organizing; Redis Cluster's slot model is more explicit and compatible with the CRC16 + modulo calculation that all clients implement deterministically. Redis intentionally chose fixed slots over consistent hashing for simpler, auditable behavior and to enable hash tags for key co-location.
03
What is memory optimization in Redis (ziplist, listpack, and encoding thresholds)?
Redis uses compact internal encodings for small data structures to minimize memory overhead. The listpack (replacing the older ziplist in Redis 7+) is a contiguous memory block storing elements back-to-back with length prefixes. Lists, Hashes, Sets, and Sorted Sets use listpack when they are small (controlled by configuration thresholds like hash-max-listpack-entries 128 and hash-max-listpack-value 64). Once a structure exceeds the threshold, it is converted to a more memory-hungry but faster-access structure (hashtable, skiplist). The skiplist powers Sorted Sets at larger sizes — it provides O(log N) operations with a linked-list structure that allows range queries, unlike a hashtable. Memory fragmentation is another concern: the mem_fragmentation_ratio in INFO memory above 1.5 indicates Redis is using much more RAM than the dataset requires, often resolved by restarting Redis or using MEMORY PURGE to return freed memory to the OS (Redis 4+ with jemalloc).
04
How does AOF rewrite work and how does it compare to RDB performance?
The AOF (Append-Only File) grows indefinitely as every write command is appended. AOF rewrite compacts it by writing the minimal set of current commands that reproduces the current dataset, discarding superseded commands. It runs in a background fork: the child process writes a new, compact AOF from the current in-memory dataset while the parent continues serving commands and buffers new writes. When the child finishes, the buffer is appended and the new file atomically replaces the old one — zero downtime. Configured via auto-aof-rewrite-min-size and auto-aof-rewrite-percentage. Compared to RDB: RDB produces a compact binary snapshot and restarts are fast (load the snapshot). AOF restores by replaying commands — much slower on large datasets. However, AOF with appendfsync everysec loses at most 1 second of data on crash, while RDB can lose minutes. The hybrid RDB+AOF persistence format (Redis 4+) starts AOF restoration from an embedded RDB snapshot, combining fast load with durable logging.
05
What are Redis Functions (replacing Lua scripts in Redis 7+)?
Redis Functions, introduced in Redis 7.0, replace the EVAL-based Lua scripting model with a more robust, library-oriented approach. With EVAL, scripts are loaded and executed per-request, requiring the script body or its SHA to be sent each time. Functions are persistent: you upload a named library with FUNCTION LOAD, and the functions persist across restarts (stored in the RDB/AOF). You call them with FCALL function_name numkeys keys args. Functions support multiple entry points in one library, versioning, and metadata. They currently support Lua (the default engine) with a planned JavaScript engine. The key advantages over EVAL: functions are first-class entities with names and documentation, they survive restart without re-uploading, and they integrate with RDB/AOF persistence. Redis encourages migration from EVAL-based scripts to Functions for all production use cases.
06
What is Redis Stack and what does it add to vanilla Redis?
Redis Stack is a Redis distribution that bundles the core Redis server with several powerful modules: RedisJSON — native JSON document storage with path-based queries using JSONPath syntax, eliminating the need to serialize/deserialize JSON strings. RediSearch — a full-text search engine with secondary indexing, enabling SQL-like queries and full-text search on Redis data without scanning all keys. RedisBloom — probabilistic data structures (Bloom filters, Cuckoo filters, Count-Min sketch, Top-K). RedisTimeSeries — optimized storage for time-series data with downsampling, aggregation, and retention rules. RedisGraph (deprecated in favor of FalkorDB) — a graph database using the Cypher query language. Redis Stack is available as a Docker image or self-managed download, and Redis Cloud supports it. It positions Redis as a multi-model database for use cases beyond simple key-value caching.
07
What are large key anti-patterns in Redis and how do you fix them?
A large key (also called "big key" or "hot key") is a key whose value is very large or whose collection contains too many members. Examples: a String value of 10MB, a Hash with 5 million fields, a Set with 1 million members, a List used as an unbounded queue. Problems: serializing/deserializing large values consumes significant CPU and memory on the client. Operations on large collections (like HGETALL on a million-field hash) block the single Redis thread for milliseconds, causing latency spikes for all other clients. To detect big keys: redis-cli --bigkeys scans the keyspace, or scan with SCAN + OBJECT ENCODING/MEMORY USAGE. Fixes: (1) Split large collections using key sharding (e.g., hash:bucket:{key % N}). (2) Use smaller page sizes and cursor-based iteration (HSCAN, SSCAN, ZSCAN). (3) Set a max size and use LTRIM to cap list growth. (4) Store large blobs in object storage (S3) and keep only the reference in Redis. (5) Compress values before storing.
08
What is CRDT support in Redis and how does it relate to Active-Active geo-distribution?
CRDTs (Conflict-free Replicated Data Types) are data structures that can be replicated across nodes and updated independently, with a mathematically guaranteed merge algorithm that resolves conflicts without coordination. They are used in Redis Enterprise's Active-Active (formerly CRDT) geo-distribution feature, where multiple Redis databases exist in different geographic regions and all accept writes simultaneously. Each region handles local writes at low latency; changes are asynchronously replicated to other regions. When concurrent writes to the same key happen in two regions, the CRDT algorithm deterministically resolves the conflict — for counters, both increments are summed; for sets, the union is taken; for LWW (Last-Write-Wins) registers, the highest-timestamp value wins. This provides multi-master replication with local read/write latency across datacenters. Open-source Redis does not include CRDT support; it is a Redis Enterprise feature for globally distributed applications.
09
How do you optimize Redis memory usage for a large-scale deployment?
Optimizing Redis memory at scale requires strategies at multiple levels. Data structure encoding: keep collections below listpack thresholds by chunking large structures. Key naming: use short, consistent key names — long key names waste memory; u:42:sess is more efficient than user:42:session at scale. Expiry policy: always set TTLs on cache keys; monitor the keyspace for keys without TTL using DEBUG SLEEP and custom scanning. Serialization: use compact binary formats (MessagePack, Protocol Buffers) instead of JSON for String values — JSON is verbose. maxmemory and eviction: set maxmemory to leave 10–25% of RAM free for OS and Redis internal overhead; choose allkeys-lfu for caches. Memory analysis: use MEMORY USAGE key, redis-cli --memkeys, or tools like RedisInsight to find the largest consumers. Redis modules: RedisJSON stores JSON more compactly than a serialized String. Monitor mem_fragmentation_ratio and schedule restarts if fragmentation is severe (>1.5).
10
How does Redis handle high availability in production and what are the failure modes to understand?
In production, Redis high availability is implemented through Sentinel or Cluster, each with distinct failure modes. With Sentinel: the primary fails → Sentinels detect it via PING failure and quorum voting → the majority-elect Sentinel promotes the replica with the least lag → updates clients via Sentinel's service-discovery API. Key failure mode: split-brain — if the primary is network-partitioned (reachable by clients but not Sentinels), it continues accepting writes that will be lost when Sentinels promote a replica and the old primary rejoins as a replica and discards its diverged data. Mitigation: min-replicas-to-write 1 makes the primary reject writes if no replicas are connected. With Cluster: a master node fails → its replicas detect it via gossip → an automatic failover promotes the best replica (most up-to-date) → the cluster reconfigures slot ownership. Failure mode: if a shard's master and all its replicas fail simultaneously, that portion of the keyspace becomes unavailable. cluster-require-full-coverage no allows the rest of the cluster to continue serving. Always monitor replication lag (INFO replication) and test failover procedures regularly in staging.