Redis
Redis Interview Questions and Answers
-
What is Redis? – Redis is an in-memory, key-value data store known for high performance, supporting data structures such as strings, hashes, lists, sets, sorted sets.
-
What data types does Redis support? – Strings, Lists, Sets, Sorted Sets (zsets), Hashes, Bitmaps, HyperLogLogs, Streams, and Geospatial indexes.
-
How do you configure Redis to require a password?
requirepass yourpassword
-
What is the default Redis port?
Answer: 6379
-
How do you secure Redis from external access?
-
Bind Redis to 127.0.0.1
-
Use firewalls to block the port externally
-
Set requirepass
-
Rename or disable dangerous commands with rename-command
Section 2: Persistence and Backup
-
Explain RDB vs AOF persistence. – RDB saves snapshots at intervals; AOF logs every write operation. AOF provides better durability; RDB is faster on recovery.
-
How does Redis handle persistence if both AOF and RDB are enabled?
Answer: Redis loads AOF at startup if both exist.
-
How do you backup a Redis instance? – Copy dump.rdb
and/or appendonly.aof
files.
-
What is copy-on-write (COW) in Redis? – Technique used during BGSAVE
or BGREWRITEAOF
where parent process forks a child; parent continues while child writes snapshot.
-
How do you trigger manual persistence?
SAVE # synchronous save
BGSAVE # asynchronous save
Section 3: Replication and High Availability
-
How does Redis replication work? – Replicas connect to master, sync DB snapshot, then receive ongoing changes.
-
How to configure a replica?
replicaof master_ip master_port
-
How do you enforce read-only replicas?
replica-read-only yes
-
What is Redis Sentinel? – Sentinel monitors masters, performs failover, notifies clients.
-
Explain failover delay settings in Sentinel. – Controls how long Sentinel waits before initiating failover.
Section 4: Clustering
-
What is Redis Cluster? – Redis Cluster provides sharding and replication across multiple nodes for scalability and HA.
-
Explain the role of hash slots. – 16,384 hash slots partition keys across nodes; each node owns a subset.
-
How to check if a node is in a cluster?
CLUSTER INFO
-
How do you list cluster nodes?
CLUSTER NODES
-
What is CLUSTER FAILOVER
? – Command to promote a replica to master.
Section 5: Key Management and Expiration
-
How to set a key with expiration?
SET mykey value EX 60
-
How do you expire keys by pattern?
redis-cli --scan --pattern "prefix:*" | xargs redis-cli DEL
-
What happens when Redis memory is exhausted? – Redis evicts keys based on eviction policy.
-
Explain eviction policies. – e.g., volatile-lru
, allkeys-lru
, noeviction
, volatile-ttl
.
-
What is lazy freeing? – Keys are deleted asynchronously to avoid blocking main thread.
Section 6: Transactions and Atomicity
-
Explain Redis transactions. – Group multiple commands with MULTI
/EXEC
; queued and executed sequentially.
-
How to perform check-and-set (CAS)?
WATCH mykey
MULTI
SET mykey newval
EXEC
-
What is DISCARD
? – Cancels a transaction after MULTI
.
-
What happens if a command fails in MULTI
? – Other commands still run; no rollback.
-
How to atomically fetch and delete a key?
GETDEL mykey
Section 7: Advanced Data Structures
-
Explain sorted sets. – Like sets, but each member has a score for ordering.
-
How does ZPOPMIN
work? – Removes and returns member with smallest score.
-
What is ZLEXCOUNT
? – Counts members within a lex range.
-
What is a Redis GEO command?
GEOADD locations 13.361389 38.115556 "Palermo"
GEORADIUS locations 15 37 200 km
-
What is BITFIELD
used for? – Operates on individual bits or ranges in a string.
Section 8: Streams and Pub/Sub
-
What is Redis Streams? – A data structure for append-only log with IDs.
-
How to read from a stream?
XREAD COUNT 1 STREAMS mystream >
-
Explain XREADGROUP
. – Read from a stream as part of a consumer group.
-
What is a pending entry? – A message delivered but not acknowledged in a consumer group.
-
How to claim pending messages?
XCLAIM mystream mygroup myconsumer 0 ID
Section 9: Monitoring and Debugging
-
How do you measure latency?
LATENCY DOCTOR
LATENCY LATEST
-
What is INFO commandstats
? – Shows statistics per command.
-
What is CLIENT LIST
used for? – Displays connected clients and their info.
-
How to check replication lag?
INFO replication
-
How to inspect memory usage of a key?
MEMORY USAGE mykey
Section 10: Performance and Scaling
-
What is MEMORY DOCTOR
? – Analyzes memory for inefficiencies.
-
How to handle hot keys? – Cache busting, sharding, or client-side caching.
-
How to benchmark Redis?
redis-benchmark
-
What is WAIT
command? – Ensures writes propagate to replicas.
-
Explain Redis modules. – Loadable extensions to add new commands.
Section 11: Security and ACL
-
How to rename dangerous commands?
rename-command FLUSHALL ""
-
How to enable ACL?
ACL SETUSER alice on >password ~* +@all
-
How to disable a user?
ACL SETUSER alice off
-
How does Redis handle unauthorized access? – Returns NOAUTH
error.
-
What is AUTH
command? – Authenticate a client.
Section 12: Miscellaneous
-
What is SWAPDB
? – Swaps two databases.
-
How does UNLINK
differ from DEL
? – UNLINK
deletes asynchronously.
-
How to migrate keys?
MIGRATE host port key dest-db timeout
-
What is MODULE LOAD
? – Loads a Redis module.
-
What is RedisTimeSeries? – Module for storing time-series data.
What is Redis? – Redis is an in-memory, key-value data store known for high performance, supporting data structures such as strings, hashes, lists, sets, sorted sets.
What data types does Redis support? – Strings, Lists, Sets, Sorted Sets (zsets), Hashes, Bitmaps, HyperLogLogs, Streams, and Geospatial indexes.
How do you configure Redis to require a password?
requirepass yourpassword
What is the default Redis port?
Answer: 6379
How do you secure Redis from external access?
-
Bind Redis to
127.0.0.1
-
Use firewalls to block the port externally
-
Set
requirepass
-
Rename or disable dangerous commands with
rename-command
Explain RDB vs AOF persistence. – RDB saves snapshots at intervals; AOF logs every write operation. AOF provides better durability; RDB is faster on recovery.
How does Redis handle persistence if both AOF and RDB are enabled?
Answer: Redis loads AOF at startup if both exist.
How do you backup a Redis instance? – Copy dump.rdb
and/or appendonly.aof
files.
What is copy-on-write (COW) in Redis? – Technique used during BGSAVE
or BGREWRITEAOF
where parent process forks a child; parent continues while child writes snapshot.
How do you trigger manual persistence?
SAVE # synchronous save
BGSAVE # asynchronous save
How does Redis replication work? – Replicas connect to master, sync DB snapshot, then receive ongoing changes.
How to configure a replica?
replicaof master_ip master_port
How do you enforce read-only replicas?
replica-read-only yes
What is Redis Sentinel? – Sentinel monitors masters, performs failover, notifies clients.
Explain failover delay settings in Sentinel. – Controls how long Sentinel waits before initiating failover.
What is Redis Cluster? – Redis Cluster provides sharding and replication across multiple nodes for scalability and HA.
Explain the role of hash slots. – 16,384 hash slots partition keys across nodes; each node owns a subset.
How to check if a node is in a cluster?
CLUSTER INFO
How do you list cluster nodes?
CLUSTER NODES
What is CLUSTER FAILOVER
? – Command to promote a replica to master.
How to set a key with expiration?
SET mykey value EX 60
How do you expire keys by pattern?
redis-cli --scan --pattern "prefix:*" | xargs redis-cli DEL
What happens when Redis memory is exhausted? – Redis evicts keys based on eviction policy.
Explain eviction policies. – e.g., volatile-lru
, allkeys-lru
, noeviction
, volatile-ttl
.
What is lazy freeing? – Keys are deleted asynchronously to avoid blocking main thread.
Explain Redis transactions. – Group multiple commands with MULTI
/EXEC
; queued and executed sequentially.
How to perform check-and-set (CAS)?
WATCH mykey
MULTI
SET mykey newval
EXEC
What is DISCARD
? – Cancels a transaction after MULTI
.
What happens if a command fails in MULTI
? – Other commands still run; no rollback.
How to atomically fetch and delete a key?
GETDEL mykey
Explain sorted sets. – Like sets, but each member has a score for ordering.
How does ZPOPMIN
work? – Removes and returns member with smallest score.
What is ZLEXCOUNT
? – Counts members within a lex range.
What is a Redis GEO command?
GEOADD locations 13.361389 38.115556 "Palermo"
GEORADIUS locations 15 37 200 km
What is BITFIELD
used for? – Operates on individual bits or ranges in a string.
What is Redis Streams? – A data structure for append-only log with IDs.
How to read from a stream?
XREAD COUNT 1 STREAMS mystream >
Explain XREADGROUP
. – Read from a stream as part of a consumer group.
What is a pending entry? – A message delivered but not acknowledged in a consumer group.
How to claim pending messages?
XCLAIM mystream mygroup myconsumer 0 ID
How do you measure latency?
LATENCY DOCTOR
LATENCY LATEST
What is INFO commandstats
? – Shows statistics per command.
What is CLIENT LIST
used for? – Displays connected clients and their info.
How to check replication lag?
INFO replication
How to inspect memory usage of a key?
MEMORY USAGE mykey
What is MEMORY DOCTOR
? – Analyzes memory for inefficiencies.
How to handle hot keys? – Cache busting, sharding, or client-side caching.
How to benchmark Redis?
redis-benchmark
What is WAIT
command? – Ensures writes propagate to replicas.
Explain Redis modules. – Loadable extensions to add new commands.
How to rename dangerous commands?
rename-command FLUSHALL ""
How to enable ACL?
ACL SETUSER alice on >password ~* +@all
How to disable a user?
ACL SETUSER alice off
How does Redis handle unauthorized access? – Returns NOAUTH
error.
What is AUTH
command? – Authenticate a client.
What is SWAPDB
? – Swaps two databases.
How does UNLINK
differ from DEL
? – UNLINK
deletes asynchronously.
How to migrate keys?
MIGRATE host port key dest-db timeout
What is MODULE LOAD
? – Loads a Redis module.
What is RedisTimeSeries? – Module for storing time-series data.
Section 13: Redis Scripting and Lua
-
What is Redis scripting? – Ability to run Lua scripts atomically in Redis.
-
How do you execute a Lua script?
EVAL "return redis.call('get', KEYS[1])" 1 mykey
-
What are the advantages of Redis scripting? – Atomicity, reduced network round-trips, complex operations.
-
Explain EVALSHA
. – Executes a cached script by SHA1 hash instead of the full script.
-
How do you preload a script?
SCRIPT LOAD "return redis.call('set', KEYS[1], ARGV[1])"
Section 14: Redis Internals and Memory Management
-
How does Redis handle memory allocation? – Uses jemalloc by default for efficiency.
-
What is maxmemory-policy
? – Defines eviction policy when maxmemory
is reached.
-
What is an object encoding? – Internal representation of Redis data (e.g., ziplist, hashtable).
-
How to inspect object encoding?
OBJECT ENCODING mykey
-
Explain lazy deletion vs active expiration. – Lazy deletion removes expired keys upon access; active expiration scans keys periodically.
Section 15: Redis Troubleshooting and Recovery
-
How do you fix LOADING Redis is loading the dataset
? – Wait for load or restart if stuck.
-
What causes OOM command not allowed
? – Memory limit reached with noeviction
policy.
-
How to recover a corrupted AOF
? – Use redis-check-aof --fix
.
-
How to recover a corrupted RDB
? – Use redis-check-rdb
.
-
What is INFO persistence
for? – Provides details about background saves.
Section 16: Redis Cluster Advanced Topics
-
What is a cluster failover vs manual failover? – Automatic failover is triggered by failure detection; manual initiated via CLUSTER FAILOVER
.
-
Explain migrating slots. – CLUSTER SETSLOT
commands move ownership.
-
How do you rebalance a Redis Cluster? – Use redis-cli --cluster rebalance
.
-
What is CLUSTER BUMPEPOCH
? – Forces an epoch increment to resolve conflicts.
-
How does Redis handle split-brain in cluster mode? – Majority vote prevents conflicting masters.
Section 17: Redis Pub/Sub Advanced
-
What happens to published messages when no subscribers? – Messages are discarded.
-
How to unsubscribe from a channel?
UNSUBSCRIBE mychannel
-
Can Pub/Sub be persisted? – No; messages are ephemeral.
-
What is keyspace notification?
CONFIG SET notify-keyspace-events Ex
SUBSCRIBE "__keyevent@0__:expired"
-
How to monitor all Pub/Sub channels?
PSUBSCRIBE *
Section 18: Redis Development and Integration
-
How do you connect to Redis in Python?
import redis
r = redis.Redis(host='localhost', port=6379)
r.set('foo', 'bar')
-
What Java library is popular for Redis? – Jedis or Lettuce.
-
Explain Redis pipelining. – Send multiple commands without waiting for replies to reduce latency.
-
What is Redis client-side caching? – Allows clients to locally cache data with invalidation support.
-
How to use Redis with Node.js?
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value');
Section 19: Redis Benchmarking and Tuning
-
What is latency-monitor-threshold
? – Threshold in microseconds for latency monitoring.
-
How to profile command performance? – Use MONITOR
or LATENCY GRAPH
.
-
How to disable saving snapshots? – Remove save
lines in redis.conf
.
-
What does hash-max-ziplist-entries
control? – Threshold to switch hash encoding.
-
How to detect large keys?
MEMORY USAGE key
SCAN + MEMORY USAGE
Section 20: Redis Limitations and Alternatives
-
What are Redis single-thread limitations? – Only one command processed at a time per instance.
-
How to horizontally scale beyond Redis Cluster? – Use proxies like Twemproxy or client-side sharding.
-
When is Redis not a good fit? – Large dataset requiring disk-based queries; complex joins.
-
What is an alternative to Redis for persistence? – RocksDB, PostgreSQL, or Cassandra.
-
How to migrate from Redis to another store? – Use DUMP
and restore logic or ETL tools.
What is Redis scripting? – Ability to run Lua scripts atomically in Redis.
How do you execute a Lua script?
EVAL "return redis.call('get', KEYS[1])" 1 mykey
What are the advantages of Redis scripting? – Atomicity, reduced network round-trips, complex operations.
Explain EVALSHA
. – Executes a cached script by SHA1 hash instead of the full script.
How do you preload a script?
SCRIPT LOAD "return redis.call('set', KEYS[1], ARGV[1])"
How does Redis handle memory allocation? – Uses jemalloc by default for efficiency.
What is maxmemory-policy
? – Defines eviction policy when maxmemory
is reached.
What is an object encoding? – Internal representation of Redis data (e.g., ziplist, hashtable).
How to inspect object encoding?
OBJECT ENCODING mykey
Explain lazy deletion vs active expiration. – Lazy deletion removes expired keys upon access; active expiration scans keys periodically.
How do you fix LOADING Redis is loading the dataset
? – Wait for load or restart if stuck.
What causes OOM command not allowed
? – Memory limit reached with noeviction
policy.
How to recover a corrupted AOF
? – Use redis-check-aof --fix
.
How to recover a corrupted RDB
? – Use redis-check-rdb
.
What is INFO persistence
for? – Provides details about background saves.
What is a cluster failover vs manual failover? – Automatic failover is triggered by failure detection; manual initiated via CLUSTER FAILOVER
.
Explain migrating slots. – CLUSTER SETSLOT
commands move ownership.
How do you rebalance a Redis Cluster? – Use redis-cli --cluster rebalance
.
What is CLUSTER BUMPEPOCH
? – Forces an epoch increment to resolve conflicts.
How does Redis handle split-brain in cluster mode? – Majority vote prevents conflicting masters.
What happens to published messages when no subscribers? – Messages are discarded.
How to unsubscribe from a channel?
UNSUBSCRIBE mychannel
Can Pub/Sub be persisted? – No; messages are ephemeral.
What is keyspace notification?
CONFIG SET notify-keyspace-events Ex
SUBSCRIBE "__keyevent@0__:expired"
How to monitor all Pub/Sub channels?
PSUBSCRIBE *
How do you connect to Redis in Python?
import redis
r = redis.Redis(host='localhost', port=6379)
r.set('foo', 'bar')
What Java library is popular for Redis? – Jedis or Lettuce.
Explain Redis pipelining. – Send multiple commands without waiting for replies to reduce latency.
What is Redis client-side caching? – Allows clients to locally cache data with invalidation support.
How to use Redis with Node.js?
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value');
What is latency-monitor-threshold
? – Threshold in microseconds for latency monitoring.
How to profile command performance? – Use MONITOR
or LATENCY GRAPH
.
How to disable saving snapshots? – Remove save
lines in redis.conf
.
What does hash-max-ziplist-entries
control? – Threshold to switch hash encoding.
How to detect large keys?
MEMORY USAGE key
SCAN + MEMORY USAGE
What are Redis single-thread limitations? – Only one command processed at a time per instance.
How to horizontally scale beyond Redis Cluster? – Use proxies like Twemproxy or client-side sharding.
When is Redis not a good fit? – Large dataset requiring disk-based queries; complex joins.
What is an alternative to Redis for persistence? – RocksDB, PostgreSQL, or Cassandra.
How to migrate from Redis to another store? – Use DUMP
and restore logic or ETL tools.