Database / Redis real time troubleshooting and scenario based Interview questions
Last updated
1. How do you troubleshoot high latency in Redis?
First prove the problem is Redis and not the network or the client. Run redis-cli --intrinsic-latency 100 on the server host. If the baseline is already high, the VM or a noisy neighbour is the cause, not Redis.
Then look at what Redis itself is doing:
SLOWLOG GET 20to catch O(N) commands such asKEYS,SMEMBERSon a huge set or a largeLRANGE.LATENCY DOCTORandLATENCY LATESTfor fork, AOF fsync and expire-cycle spikes.INFO commandstatsandINFO clientsfor blocked clients and connection storms.INFO memoryto rule out swapping and eviction pressure.
The usual culprits are big keys, fork during RDB or AOF rewrite, transparent huge pages, swap, and clients sending huge pipelines. Fix the cause instead of just raising client timeouts.
Take quiz
CLIENT LIST
INFO keyspace
CONFIG GET timeout
LATENCY DOCTOR
The VM or host is adding delay before Redis does any work
Redis keys are too long
The replica has a stale offset
AOF is disabled
2. Redis memory keeps growing. How do you investigate?
Begin with INFO memory and compare used_memory, used_memory_rss and mem_fragmentation_ratio. This tells you whether the growth is real data or allocator overhead.
If it is real data, find out which keys own it:
- Run
redis-cli --bigkeysor--memkeys(both useSCAN, so they do not block). - Check
MEMORY USAGE <key>for suspects. - Sample key prefixes with
SCANand count how many have no TTL (TTL keyreturns -1). - Look at
INFO clientsfor large client output buffers (omeminCLIENT LIST).
Typical causes: keys written without TTL, a list or stream that is never trimmed, sets that only grow, or a slow consumer buffering replies. Fix the producer, add TTLs, and use XTRIM or LTRIM where appropriate.
Take quiz
flags
omem
idle
db
The key does not exist
The key expires in one second
The key exists but has no expiry
The key is stored on a replica only
3. What happens when Redis reaches maxmemory?
It depends on maxmemory-policy. Redis checks memory before running each command that can add data. If it is over the limit, it tries to evict keys according to the policy.
| Policy | Behaviour at the limit |
| noeviction | Writes fail with OOM command not allowed; reads still work. |
| allkeys-lru / allkeys-lfu | Evicts any key, least recently or least frequently used. |
| volatile-lru / volatile-ttl | Evicts only keys that have a TTL. |
| allkeys-random | Evicts random keys. |
A common surprise: with a volatile-* policy and no keys carrying a TTL, Redis behaves like noeviction and starts rejecting writes. Watch evicted_keys in INFO stats to see if eviction is active.
Take quiz
It returns OOM as well
The key is evicted first
The connection is closed
It still succeeds; only commands that add memory are rejected
No keys have a TTL, so nothing is eligible for eviction
LRU only works on strings
volatile policies disable writes
Replicas block eviction
4. How do you find big keys without blocking Redis?
Use redis-cli --bigkeys or redis-cli --memkeys. Both walk the keyspace with SCAN in small batches, so the server stays responsive. Add -i 0.1 to sleep between batches on a busy instance.
For a specific key, MEMORY USAGE key SAMPLES 0 gives the real byte size, including nested elements.
Never use KEYS * or DEBUG OBJECT loops for this. When you find a big key:
- Delete it with
UNLINK, which frees memory in a background thread, instead ofDEL. - Split it, for example a huge hash into
user:1:part:0..Nbuckets. - Read it with
HSCAN,SSCANorZRANGEwith limits instead of fetching everything.
Take quiz
FLUSHALL SYNC
UNLINK
KEYS
DEL with pipelining
Reads the RDB file instead
Locks the replica
Iterates the keyspace with SCAN in small batches
Uses MONITOR
5. Why is KEYS * dangerous in production?
Redis runs commands on a single main thread. KEYS is O(N) over the whole keyspace, so with millions of keys it can hold that thread for seconds. Every other client waits, timeouts pile up, and connection counts rise.
Use SCAN instead. It returns a cursor and a small batch each call, so other commands run between calls.
redis-cli --scan --pattern 'session:*' --count 500
Remember SCAN may return a key more than once, and keys added or removed during iteration may or may not appear. Make the processing idempotent. To stop teams from running it by accident, rename or disable it using ACL rules: ACL SETUSER app -keys style restrictions or -@dangerous.
Take quiz
SCAN sorts the keys, KEYS does not
KEYS only works on replicas
SCAN locks the database
SCAN iterates in small cursor-based batches, KEYS returns everything in one blocking call
The same key can be returned more than once
Keys always arrive sorted
Each key appears exactly once
Deleted keys are always skipped
6. How do you identify slow commands using SLOWLOG?
Redis records commands whose execution time exceeds slowlog-log-slower-than (microseconds, default 10000 = 10 ms). The log holds the last slowlog-max-len entries (default 128).
CONFIG SET slowlog-log-slower-than 5000 SLOWLOG GET 10 SLOWLOG LEN SLOWLOG RESET
Each entry has an ID, a timestamp, the duration in microseconds, the command with arguments and the client address. Note that only execution time is measured. Time spent waiting in the queue, network time and I/O are not included, so a clean SLOWLOG does not rule out latency caused by a long-running command ahead of yours.
Cross-check with INFO commandstats to see which commands have a high usec_per_call.
Take quiz
Milliseconds
Microseconds
Seconds
Number of keys touched
It only logs write commands
It resets on every GET
It measures only command execution, not queue wait or network time
It logs only replica traffic
7. How do you troubleshoot Redis hitting 100% CPU?
Redis executes commands on one main thread, so 100% on one core means that thread is saturated. Check INFO stats for instantaneous_ops_per_sec and INFO commandstats to see which command consumes the most total usec.
Common scenarios:
- Expensive commands:
SORT,ZUNIONSTORE, bigLRANGE, Lua loops. Fix with limits, pagination or precomputation. - Connection churn: apps opening a new connection per request (and TLS handshakes). Use pooling.
- Hot key receiving most traffic. Add local caching or key replication.
- Plain volume: add pipelining, enable
io-threads(Redis 6+) for network I/O, or shard with Redis Cluster. - Expiry storms: millions of keys expiring in the same second. Add TTL jitter.
Use redis-cli --hotkeys (needs an LFU policy) or a short MONITOR sample, remembering that MONITOR itself slows the server.
Take quiz
It limits itself to one core by licence
The replica uses the other cores
Persistence requires one core
Command execution runs on a single main thread
Adding random jitter to TTL values
Switching to KEYS cleanup
Disabling AUTH
Raising slowlog-max-len
8. Why does Redis latency spike during RDB snapshots?
To save an RDB file, Redis calls fork(). The child writes the snapshot while the parent keeps serving traffic using copy-on-write. Two things hurt latency:
- The fork itself copies page tables. The bigger the dataset, the longer the main thread is paused. Check
latest_fork_usecinINFO stats. - During the save, every write to a memory page forces the OS to copy that page, which raises memory use and CPU.
Transparent Huge Pages (THP) make this much worse because each write copies a 2 MB page instead of 4 KB. Redis logs a warning for it at startup. Disable it:
echo never > /sys/kernel/mm/transparent_hugepage/enabled
Other mitigations: fork on bare metal or Xen-free hosts where possible, schedule snapshots off-peak, and take snapshots from a replica instead of the master.
Take quiz
rdb_last_save_time
latest_fork_usec
total_commands_processed
expired_keys
They disable fork
They compress the RDB file
Each write copies a 2 MB page instead of a 4 KB page under copy-on-write
They block replicas from syncing
9. How do you troubleshoot a replica that keeps resyncing?
A resync loop usually means partial resync keeps failing and the master falls back to a full sync, which then fails or gets dropped again. Check the master log for Partial resynchronization not possible and compare sync_full and sync_partial_err in INFO stats.
Common causes:
- Replication backlog too small:
repl-backlog-size(default 1 MB) is exhausted during a short disconnect. - Replica output buffer limit hit:
client-output-buffer-limit replicakills the link while the RDB is being transferred under heavy writes. Raise it. - Timeouts:
repl-timeoutis too low for a big RDB over a slow link. - Replica too slow loading the RDB or hit by its own OOM.
The loop feeds itself: each full sync forks the master, which adds more latency and more disconnects. Raise the backlog and buffer limits first, then fix the network or sizing issue.
Take quiz
maxmemory-samples
slowlog-max-len
tcp-keepalive
repl-backlog-size
client-output-buffer-limit for replicas
maxclients
hash-max-ziplist-entries
appendfsync
10. What happens when a Redis master crashes without Sentinel?
Without Sentinel or Cluster there is no automatic failover. Writes fail immediately because clients cannot reach the master. Replicas stay up and keep serving reads, but they are read-only (replica-read-only yes) and keep trying to reconnect.
Manual recovery steps:
- Check
INFO replicationon each replica and pick the one with the highestslave_repl_offset. That replica has the most data. - Run
REPLICAOF NO ONEon it to promote it. - Run
REPLICAOF new-master-ip porton the other replicas. - Update the application endpoint, DNS or load balancer.
Because replication is asynchronous, any writes the master acknowledged but had not yet sent are lost. This gap is the main reason production setups use Sentinel or Cluster.
Take quiz
SLAVEOF YES
REPLICAOF NO ONE
CLUSTER FAILOVER FORCE on the master
BGREWRITEAOF
The one with the lowest memory use
The newest by hostname
The one with the highest replication offset
Any replica; offsets do not matter
11. How does Sentinel failover work step by step?
Sentinel watches the master and, when it fails, promotes a replica and tells clients.
- SDOWN: one Sentinel gets no valid reply from the master for
down-after-milliseconds. - ODOWN: at least
quorumSentinels agree the master is down. - Leader election: Sentinels vote and one leader is chosen. It needs authorization from a majority of all Sentinels.
- Replica selection: by
replica-priority, then highest replication offset, then lowest run ID. - The leader sends
REPLICAOF NO ONEto the chosen replica and reconfigures the other replicas. - The new configuration is published with a higher config epoch, and clients learn the new master through Sentinel.
flowchart LR A[SDOWN] --> B["ODOWN by quorum"] B --> C["Leader election"] C --> D["Pick best replica"] D --> E["Promote and reconfigure"] E --> F["Clients discover new master"]
Take quiz
ODOWN first, then SDOWN
Leader election first, then SDOWN
SDOWN and ODOWN are the same state
SDOWN first, then ODOWN once the quorum agrees
The replica with the best replica-priority, then highest offset
The replica with the smallest dataset
A random replica
The replica with the most clients
12. Why might a Sentinel failover not trigger?
Detecting the failure (quorum) and authorizing the failover (majority) are two different checks. Failover is silent when either one fails.
- Not enough Sentinels: with only 2 Sentinels, a majority needs both. Always run at least 3 on separate hosts or zones.
- Quorum too high for the Sentinels that are actually alive.
- down-after-milliseconds set too large, so the master is never marked down in time.
- No eligible replica: all replicas have
replica-priority 0, are disconnected, or were disconnected from the master too long. - Sentinels cannot reach each other because of firewall or
announce-ipmistakes. - A recent failover: Sentinel waits
failover-timeoutbefore trying again.
Check SENTINEL master mymaster, SENTINEL replicas mymaster and the Sentinel logs for +sdown, +odown and -failover-abort-not-elected.
Take quiz
Sentinel only supports odd quorums above 5
A majority needs both Sentinels, so losing one blocks failover
It disables replication
It doubles memory use
replica-read-only yes
repl-diskless-sync yes
replica-priority 0
replica-serve-stale-data no
13. How do you prevent split-brain in a Redis failover?
Split-brain happens when the old master is cut off from Sentinels but still reachable by some clients. Sentinel promotes a replica, yet the old master keeps accepting writes. When the network heals, the old master is demoted to a replica and its newer writes are discarded.
You cannot remove the window entirely, but you can shrink it. On the master set:
min-replicas-to-write 1 min-replicas-max-lag 10
With these settings, a master that cannot see at least one replica with lag under 10 seconds stops accepting writes. An isolated old master therefore rejects writes after about 10 seconds.
Also run 3 or more Sentinels across different failure domains, so a single partition cannot isolate the master with the majority. Accept that this trades some availability for less data loss.
Take quiz
They are merged automatically
They are copied to the new master
They are kept and replayed later
They are discarded when it resyncs from the new master
min-replicas-to-write and min-replicas-max-lag
maxclients and timeout
save and appendfsync
hz and dynamic-hz
14. How do you handle a cache stampede?
A stampede happens when a hot key expires and hundreds of requests all miss at once and hit the database together.
Practical defenses:
- Single-flight lock: the first miss takes a short lock with
SET lock:key token NX PX 5000, rebuilds the value, and the rest wait briefly or serve stale data. - TTL jitter: use
ttl + random(0, 10%)so related keys do not expire together. - Stale-while-revalidate: store a soft expiry inside the value, return the old value, and refresh in the background.
- Probabilistic early refresh: refresh slightly before expiry with rising probability.
- Pre-warm known hot keys after deploys or restarts.
Always give the lock a TTL, otherwise a crashed worker blocks the key forever.
Take quiz
FLUSHDB ASYNC
SET key token NX PX with a short TTL
KEYS lock:*
CONFIG SET maxmemory 0
To make keys immortal
To compress values
So many keys do not expire at the same moment
To bypass the replication backlog
15. How do you prevent cache penetration?
Cache penetration is when requests for keys that do not exist (bad IDs, bots, attacks) always miss the cache and hit the database. Caching a normal value does not help because there is no value to cache.
Ways to stop it:
- Cache the miss: store a null marker with a short TTL, such as 30-60 seconds.
- Bloom filter: keep all valid IDs in a RedisBloom filter and reject anything where
BF.EXISTSreturns 0. - Validate input at the API layer (format, range) before touching Redis or the DB.
- Rate-limit clients that keep requesting missing keys.
Keep null TTLs short, otherwise a record created a moment later stays invisible. Bloom filters can give false positives but never false negatives, so a few bad lookups still reach the database, which is acceptable.
Take quiz
It may be wrong half the time
It is only valid for one hour
It requires a database check
It is definite; Bloom filters have no false negatives
A record created later would otherwise stay invisible
Null values consume no memory
Redis rejects long TTLs on nulls
It speeds up replication
16. What is a cache avalanche and how do you prevent it?
A cache avalanche is a mass failure of the cache layer: many keys expire at the same moment, or the Redis instance goes down, and the database suddenly takes the full read load.
| Cause | Prevention |
| Keys loaded in one batch with the same TTL | Add TTL jitter and stagger warm-up jobs. |
| Redis node down or restarting | Use Sentinel or Cluster with replicas. |
| DB overwhelmed after cache loss | Circuit breaker, request limiting, and a small in-process cache as a second level. |
Also load-test the "cold cache" scenario. If your database cannot survive that, you need load shedding or a gradual warm-up before sending real traffic.
Take quiz
Using FLUSHALL nightly
Randomizing TTLs
Raising maxclients
Disabling persistence
It re-creates expired keys
It promotes a replica
It stops traffic to an overloaded database so it can recover
It compresses cached values
17. How do you handle a hot key problem?
A hot key is a single key getting a disproportionate share of traffic, for example a flash-sale product. In a cluster, one shard saturates while the others sit idle, and adding nodes does not help because the key lives in one slot.
Detect it with redis-cli --hotkeys (requires an LFU policy), a brief MONITOR sample, or application metrics.
Fixes:
- Local cache inside the app with a 1-5 second TTL.
- Key replication: store copies as
product:42:0..Nand read a random suffix. - Read from replicas for read-heavy keys.
- Client-side caching with
CLIENT TRACKING(Redis 6+), so Redis invalidates local copies.
The trade-off is staleness, so choose a TTL that the business can accept.
Take quiz
Cluster does not support strings
New nodes cannot hold data
Hot keys are replicated automatically
The key stays in one hash slot on one node
Key replication with random suffixes
Using KEYS on each read
Lowering the TTL to 0
Switching to MONITOR
18. Why do clients get OOM command not allowed when used memory > maxmemory?
The error means Redis is over maxmemory and cannot free enough memory to run a write command. Reads still work.
It happens when:
- The policy is
noeviction(the default in many setups). - The policy is
volatile-*but there are no keys with a TTL to evict. - Eviction cannot keep up with the write rate, for example when huge values are written.
Triage:
- Check
INFO memoryforused_memory,maxmemoryand the policy. - Find big or TTL-less keys with
--bigkeysandSCAN. - Short term:
CONFIG SET maxmemoryhigher (if the host has room) orUNLINKjunk keys. - Long term: switch to
allkeys-lrufor a pure cache, add TTLs, or scale out.
Take quiz
READONLY You can't write against a read only replica
OOM command not allowed when used memory > 'maxmemory'
MOVED 3999 127.0.0.1:6381
LOADING Redis is loading the dataset
noeviction
volatile-ttl on keys without TTL
allkeys-lru
no policy; set maxmemory 0 on a small VM
19. How do you fix MISCONF Redis is configured to save RDB snapshots?
This error means the last background save failed and stop-writes-on-bgsave-error yes (the default) makes Redis reject writes to protect you from silent data loss.
Find out why the save failed:
- Read the Redis log for the
BGSAVEfailure message. - Check disk space (
df -h) and inodes on thedirpath. - Check that the Redis user can write to
diranddbfilename. - Check for fork failures (low memory,
vm.overcommit_memory).
After fixing the cause, run BGSAVE. Once rdb_last_bgsave_status in INFO persistence is ok, writes resume.
Setting stop-writes-on-bgsave-error no removes the error but also removes the safety net, so use it only as a short emergency measure.
Take quiz
aof_enabled
loading
rdb_changes_since_last_save only
rdb_last_bgsave_status
Accepting writes without a successful snapshot, so data may be lost
Disabling AUTH
Stopping replication
Deleting the RDB file
20. Why does Redis fail with Can't save in background: fork?
The full message is usually Can't save in background: fork: Cannot allocate memory. fork() needs the kernel to promise enough memory for a copy of the process. With the default overcommit mode, Linux may refuse that promise on a host where Redis uses a large part of RAM, even though copy-on-write means most pages will be shared.
Fix:
- Set
vm.overcommit_memory = 1in/etc/sysctl.confand apply withsysctl -p. - Leave headroom for copy-on-write. Under heavy writes during a save, memory use can approach double the dataset.
- Keep
maxmemorywell below physical RAM, and avoid running other big processes on the same host. - Disable THP to reduce copy-on-write overhead.
In containers, also check the cgroup memory limit, because the limit applies to parent plus child.
Take quiz
vm.swappiness = 100
vm.overcommit_memory = 1
net.core.somaxconn = 1
fs.file-max = 0
Redis stores each key twice
AOF always doubles RAM
Copy-on-write during a save can grow memory use toward double
Replicas share the primary's memory
21. How do you troubleshoot ERR max number of clients reached?
Redis refuses new connections when connected_clients reaches maxclients (default 10000, but capped by the OS file descriptor limit, ulimit -n).
Steps:
INFO clientsto seeconnected_clientsandINFO statsforrejected_connections.CLIENT LISTand group byaddrornameto see which app host opens the most connections.- Look at the
idlefield. Many connections with a huge idle time point to a leak.
Usual causes are apps creating a new connection per request, pools sized too large across many pods, and missing close calls. Fix with connection pooling, sensible pool sizes, timeout 300 to close idle clients, and tcp-keepalive.
As a stopgap, use CLIENT KILL on leaked connections or raise maxclients after raising the file limit.
Take quiz
expired_keys
sync_full
keyspace_hits
rejected_connections
A connection leak in the application
A corrupted AOF
Replica lag
Slow disk
22. How do you debug a growing blocked_clients count?
blocked_clients in INFO clients counts connections waiting on blocking operations: BLPOP, BRPOP, BLMOVE, XREAD BLOCK, XREADGROUP BLOCK and WAIT.
A few blocked clients are normal for workers waiting on a queue. A count that keeps rising is not. Typical reasons:
- The producer stopped, so consumers wait forever on an empty list or stream.
- Workers restart in a loop and each new instance leaves a stale connection behind.
- A
WAITcall blocks because replicas are lagging or down.
Use CLIENT LIST and look at cmd= and flags=b to see who is blocked on what. Then check the producer side, give blocking calls a finite timeout instead of 0, and use CLIENT KILL for dead workers.
Take quiz
r
b
M
x
BLPOP disallows zero
It disables persistence
A dead producer or lost connection can leave workers blocked forever
It doubles memory use
23. How do you troubleshoot AOF rewrite taking too long?
An AOF rewrite forks a child that writes a compact copy of the dataset. Slow rewrites usually come from disk or memory pressure, not from Redis logic.
Checks:
INFO persistence:aof_rewrite_in_progress,aof_current_rewrite_time_sec,aof_last_bgrewrite_status.- Disk I/O with
iostat -x. A saturated disk slows both rewrite and normal fsync. - The log warning
Asynchronous AOF fsync is taking too long. - Dataset size and fork time (
latest_fork_usec).
Tuning options: use faster storage, keep appendfsync everysec, review no-appendfsync-on-rewrite (it trades durability during rewrite for lower latency), and adjust auto-aof-rewrite-percentage and auto-aof-rewrite-min-size so rewrites run less often. Do not run rewrites at the same time as RDB saves or backups.
Take quiz
rdb_bgsave_in_progress is the only one
loading_eta_seconds
aof_enabled
aof_rewrite_in_progress
Lower latency during rewrite for weaker durability in that window
Smaller RDB files for faster loading
Faster replica sync for lost keys
Cluster slot safety for speed
24. What happens when a Redis AOF file is corrupted?
On startup Redis replays the AOF. If it hits a bad command in the middle it refuses to start and logs the offset. If only the tail is cut off, which is common after a crash or full disk, Redis can load the file anyway when aof-load-truncated yes (the default) and logs a warning.
Recovery:
- Stop Redis and back up the AOF files first.
- Run
redis-check-aofon the file (on Redis 7+, point it at the manifest or the specific incr file inappendonlydir). - Run
redis-check-aof --fixto truncate at the first invalid entry. - Start Redis and compare key counts with what you expect.
Fixing discards everything after the bad point, so also compare with the latest RDB or a replica and use whichever has more complete data.
Take quiz
redis-benchmark
redis-check-aof --fix
redis-sentinel --repair
redis-cli --bigkeys
Flush all replicas
Delete the RDB file
Back up the existing AOF files
Restart Sentinel
25. How do you recover Redis from a corrupted RDB file?
If Redis exits on startup with an error like Bad data format or a checksum failure, the RDB file is damaged. Do not delete it yet.
Recovery order:
- Copy the damaged file somewhere safe.
- Run
redis-check-rdb dump.rdbto see where it breaks. - Check for a healthy source: a replica, an older snapshot or backup, or an AOF if enabled (Redis prefers AOF over RDB on startup when AOF is on).
- Restore the best copy into
dirand start Redis. - If it was a primary, re-attach replicas and let them resync.
RDB files are not repairable in the same way as AOF, because they are binary snapshots, so prevention matters: enable rdbchecksum yes, keep several timestamped backups off the host, and test restores regularly.
Take quiz
redis-check-aof only
redis-cli --latency
redis-cluster-fix
redis-check-rdb
The AOF
The RDB
Whichever is smaller
Both merged
26. How do you troubleshoot high memory fragmentation in Redis?
Look at mem_fragmentation_ratio in INFO memory, which is RSS divided by used_memory. About 1.0 to 1.5 is healthy. Above 1.5 means a lot of memory is held but not used. Below 1.0 is worse, because it usually means the OS is swapping Redis pages out.
Fragmentation often follows heavy delete or update churn, with values of varying size.
- Check
allocator_frag_ratioto separate allocator fragmentation from other overhead. - Enable online defragmentation:
CONFIG SET activedefrag yes(needs the bundled jemalloc). - Try
MEMORY PURGEto ask jemalloc to release dirty pages. - If it stays high, fail over to a freshly restarted replica, which loads the data compactly.
A ratio below 1 needs immediate action: fix swap or reduce memory use.
Take quiz
Perfect memory use
Redis memory is being swapped out by the OS
AOF is disabled
Replicas are ahead of the master
defrag-now 1
hz 100
activedefrag yes
lazyfree-lazy-user-del yes
27. How do you troubleshoot CLUSTERDOWN errors in Redis Cluster?
A CLUSTERDOWN reply means the cluster considers itself unable to serve some or all hash slots. The two common forms are The cluster is down and Hash slot not served.
Start with:
redis-cli -c -p 7000 CLUSTER INFO redis-cli --cluster check 10.0.0.1:7000
Look at cluster_state, cluster_slots_assigned and cluster_slots_fail. Typical causes:
- A master and all its replicas are down, so some of the 16384 slots have no owner.
- A majority of masters cannot reach each other (network partition).
- An interrupted resharding left slots in
migratingorimportingstate.
With cluster-require-full-coverage yes (default) a single uncovered slot stops the whole cluster. Bring the failed node back first. For stuck slots use redis-cli --cluster fix. Setting coverage to no keeps healthy slots available but returns errors only for the missing ones.
Take quiz
cluster-enabled no
cluster-announce-ip
cluster-replica-no-failover yes
cluster-require-full-coverage yes
redis-cli --cluster check
redis-cli --bigkeys
redis-benchmark -c
SLOWLOG GET
28. What happens when a Redis Cluster master node fails?
Cluster nodes gossip with each other. When a node does not answer pings within cluster-node-timeout, others mark it PFAIL (possible failure). When a majority of masters agree, the state becomes FAIL.
- The failed master's replicas start an election and ask the other masters for votes.
- The replica with the best offset usually wins, promotes itself and takes over the slots.
- The new master announces the change with a higher config epoch, and clients get
MOVEDredirects to learn the new owner.
If the failed master has no replica, its slots are uncovered and the cluster can go into a fail state. Also, if a majority of masters are unreachable, no failover can happen at all.
When the old master returns, it rejoins as a replica of the new one and its unreplicated writes are lost.
Take quiz
A client reports an error
A majority of masters agree it is unreachable
The replica deletes its RDB
The node reaches maxclients
A random master
The client that detected failure
The replica with the best replication offset
The node with the lowest IP
29. How do you fix MOVED and ASK redirection storms?
Both are normal cluster replies, but a flood of them means clients are routing badly.
| MOVED | ASK |
| Permanent: the slot now belongs to another node. Update the slot map. | Temporary: the slot is mid-migration. Send ASKING then retry on the target, without updating the map. |
Causes of storms:
- A client that is not cluster-aware, or one that does not cache the slot map and retries blindly.
- Resharding or rebalancing during peak traffic, producing constant ASK replies.
- A failover just happened and clients still hold the old topology.
Use a cluster-aware client with slot-map caching and refresh on MOVED. Schedule resharding off-peak and migrate in smaller batches. Check CLUSTER SLOTS or CLUSTER SHARDS against the client's view if the storm continues.
Take quiz
ASK
LOADING
BUSY
MOVED
ASKING before retrying the command
CLUSTER RESET
FLUSHSLOTS
READONLY on the source
30. How do you handle CROSSSLOT errors in Redis Cluster?
CROSSSLOT Keys in request don't hash to the same slot appears when a multi-key command (MGET, SUNION, MULTI with several keys, a Lua script) touches keys that live in different slots. Each slot belongs to one node, so the cluster cannot run it atomically across nodes.
Fix it with hash tags. Redis hashes only the text inside the first {...} of the key name:
cart:{user42}:items cart:{user42}:total MGET cart:{user42}:items cart:{user42}:total
Both keys map to the same slot. Be careful with the trade-off: if one tag, such as a huge tenant, holds too much data or traffic, that node becomes a hot spot. Choose a tag with enough cardinality, or split the work into several single-key calls with pipelining when atomicity is not needed.
Take quiz
The last 8 characters
The text inside the first curly braces
The entire key name
Only the prefix before the first colon
Keys stop expiring
Replicas lose data
One node can become a hot spot
Slots are reduced to 1024
31. How do you rebalance a Redis Cluster with uneven memory across nodes?
Start by confirming the imbalance is real. Run redis-cli --cluster info for key counts per node and INFO memory on each master. Slots may be evenly spread while memory is not, usually because of big keys or heavy hash-tag usage.
- If slot counts are uneven (for example after adding a node):
redis-cli --cluster rebalance 10.0.0.1:7000 --cluster-use-empty-masters. - To move specific slots:
redis-cli --cluster reshard, choosing source, target and slot count. - If a few slots hold giant keys, find them with
--bigkeysand split those keys. Moving slots alone will not fix it. - Run migration off-peak, since each key move is a blocking
MIGRATE, and large keys cause latency spikes.
After the move, verify with --cluster check that all 16384 slots are covered.
Take quiz
--cluster-yes-all
--bigkeys
--cluster-replicas 0
--cluster-use-empty-masters
A few slots may hold very large keys
Slots store no data
Replicas hold all the memory
Cluster rebalances memory automatically after every write
32. How do you troubleshoot Redis replication lag?
Compare offsets. On the master, INFO replication shows master_repl_offset and a line per replica with its offset and lag in seconds. The difference between offsets, in bytes, is your backlog of unapplied writes.
Causes to check:
- Slow replica: CPU saturated by heavy read queries or a slow disk when AOF is on.
- Network: limited bandwidth or packet loss between master and replica.
- Write bursts: huge values or large
MSETor Lua scripts that take time to replay. - Full sync in progress, which temporarily freezes the replica's view.
Fixes: move heavy reads away from the replica, upgrade the network or the instance, break huge writes into chunks, and size the backlog so brief lag does not turn into a full resync. If you need guarantees for a critical write, call WAIT numreplicas timeout afterwards.
Take quiz
PSYNC
WAIT
SCAN
DEBUG RELOAD
INFO keyspace on the replica only
SLOWLOG on the sentinel
INFO replication on the master
CONFIG GET save
33. Why does the replication backlog size matter when troubleshooting resyncs?
The backlog is a circular in-memory buffer on the master that stores the most recent write stream. When a replica reconnects, it sends its last replication ID and offset (PSYNC). If that offset is still inside the backlog, the master sends only the missing part: a partial resync. If not, a full resync is needed, which forks the master and transfers the whole dataset.
The default repl-backlog-size is 1 MB, which is tiny for a busy system.
A simple sizing rule:
backlog >= write_bytes_per_second x longest_disconnect_seconds
For example, 5 MB/s of writes and a 60 second tolerated outage needs about 300 MB. Also remember that repl-backlog-ttl controls how long the master keeps the backlog after the last replica leaves. Watch sync_partial_ok against sync_full in INFO stats to confirm the setting works.
Take quiz
Its entire dataset
A KEYS listing
Its AOF file
Its replication ID and offset via PSYNC
About 300 MB
About 1 MB
About 5 MB
About 60 MB
34. How do you implement a safe distributed lock with Redis?
The basic building block is a single atomic command that sets the lock only if it does not exist, with an expiry and a unique owner token:
SET lock:order:42 7f3a9c NX PX 30000
Release must be safe too. Never plain DEL, because your lock may have expired and been taken by someone else. Compare the token and delete in one Lua script:
if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end
Key points:
- Always set a TTL so a crashed owner cannot block forever.
- Use a random token per attempt.
- For correctness-critical work, add a fencing token checked by the resource being protected, because a lock with a TTL cannot fully prevent two owners.
- For multiple independent Redis nodes, Redlock is an option, though its safety is debated.
Take quiz
Because DEL is not atomic
To avoid deleting a lock that now belongs to another client
Because Lua is faster than DEL
Because DEL needs a replica
XX and KEEPTTL
GET and EXAT
NX and PX
NX and KEEPTTL only
35. Why did my Redis lock expire before the work finished?
The TTL on the lock is a guess about how long the work takes. When the job runs longer, from a slow query, a long GC pause or a stalled network call, the lock expires and a second worker acquires it. Now two workers believe they are the owner.
Ways to handle it:
- Lock renewal (watchdog): a background thread extends the TTL with a token-checked
PEXPIREwhile the work continues. Libraries such as Redisson do this automatically. - Right-size the TTL using real p99 durations plus headroom.
- Fencing tokens: each lock grant returns an increasing number, and the database or service rejects writes with an older number.
- Idempotent work, so a duplicate run does no harm.
Renewal alone does not protect against a paused process that wakes up after expiry, so fencing and idempotency matter for critical jobs.
Take quiz
A longer key name
Disabling expiry
Running KEYS before work
A fencing token that increases with each lock grant
Extends the lock TTL while the owner is still working
Deletes expired locks from replicas
Compresses the lock value
Moves the lock to another slot
36. How do you troubleshoot keys expiring unexpectedly?
First separate expiry from eviction. Check INFO stats: a rising expired_keys means TTL expiry, a rising evicted_keys means memory pressure.
If it is expiry, common causes:
- A plain
SETon an existing key removes its TTL (useKEEPTTLto preserve it), and the reverse, a code path that always sets a short TTL. - A shared constant such as
EXPIRE key 60in the wrong module. - Wrong time unit: seconds with
EXversus milliseconds withPX. - Another service sharing the same Redis and key prefix.
Debug with TTL or PTTL right after writing. Enable keyspace notifications with CONFIG SET notify-keyspace-events Ex and subscribe to __keyevent@0__:expired to see which keys expire and when.
Take quiz
The TTL doubles
The TTL is removed unless KEEPTTL is used
The TTL is unchanged
The key is deleted
total_connections_received
sync_full
evicted_keys versus expired_keys
rejected_connections
37. Why do expired keys still consume memory in Redis?
Redis does not remove every key at the exact second it expires. It uses two mechanisms:
- Lazy expiration: when a key is accessed and found expired, it is deleted then.
- Active expiration: about 10 times per second Redis samples keys that have TTLs, deletes the expired ones, and repeats if more than about 25% of the sample was expired. This is capped to limit CPU time.
A key that is expired but never read, in a large keyspace, can sit in memory until the sampler happens to pick it. After a big batch of identical TTLs, memory may stay high for a while.
What to do:
- Spread TTLs with jitter so cleanup is gradual.
- Raise
active-expire-effort(Redis 6+) if memory is tight and CPU is available. - Enable
lazyfree-lazy-expire yesso freeing large expired values does not block. - Watch
expired_keysandexpired_stale_percinINFO stats.
Take quiz
Deleting all keys at midnight
Moving keys to disk
Expiring only on replicas
Deleting an expired key only when it is accessed
lazyfree-lazy-expire yes
appendonly yes
tcp-backlog 511
stop-writes-on-bgsave-error no
38. How do you troubleshoot eviction causing unexpected cache misses?
If your hit ratio drops while traffic is steady, memory pressure may be evicting hot keys. Verify it with numbers:
redis-cli INFO stats | grep -E "evicted_keys|keyspace_hits|keyspace_misses"
Hit ratio is hits / (hits + misses). If evicted_keys is climbing in step with misses, eviction is the cause.
Next steps:
- Check
used_memoryagainstmaxmemoryand look for new big keys or a feature that started caching larger values. - Check the policy.
allkeys-randomor a poorly chosenvolatile-ttlmay discard hot data.allkeys-lfuoften protects frequently read keys better. - Raise
maxmemory, compress values, shorten TTLs for low-value data, or shard across more nodes.
Do not just increase TTLs, because a longer TTL keeps more data and makes eviction worse.
Take quiz
evicted_keys divided by expired_keys
keyspace_hits divided by (hits + misses)
used_memory divided by maxmemory
connected_clients divided by maxclients
AOF is corrupted
Sentinel quorum is wrong
Memory pressure is evicting keys that are still needed
The replica is read-only
39. How do you choose an eviction policy for a given scenario?
Base the choice on what the data is and what the application can lose.
| Scenario | Policy |
| Pure cache, any key can be rebuilt | allkeys-lru or allkeys-lfu |
| Skewed traffic with a few very hot keys | allkeys-lfu |
| Redis holds cache and persistent data (queues, counters) together | volatile-lru, with TTLs only on cache keys |
| Session store where the soonest-to-expire sessions can go first | volatile-ttl |
| Primary data store, queues, locks | noeviction plus memory alerts and capacity planning |
The best practice is to avoid mixing cache and critical data on one instance. If you do, volatile-* policies only work if every cache key has a TTL, otherwise Redis falls back to rejecting writes.
Take quiz
noeviction
volatile-ttl
allkeys-random on a store that holds critical data
allkeys-lfu
noeviction, with alerts on memory
allkeys-lru
allkeys-random
volatile-lfu
40. How do you build a Redis rate limiter and fix incorrect counts?
The simplest design is a fixed window counter: INCR rate:user42:minute, then EXPIRE on the first hit. The classic bug is doing INCR and EXPIRE as two separate calls. If the app crashes between them, the key never expires and the user is blocked forever. Make them atomic:
local c = redis.call("INCR", KEYS[1]) if c == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end return c
Other incorrect-count causes:
- Boundary bursts: a fixed window allows 2x the limit around the window edge. Use a sliding window with a sorted set (
ZADD,ZREMRANGEBYSCORE,ZCARD) or a token bucket in Lua. - Clock skew between app servers. Use
redis.call("TIME")inside the script. - Cluster key spread, when a limit spans several keys. Use hash tags.
Take quiz
INCR does not work on strings
A crash between them leaves a counter with no expiry
EXPIRE removes the counter
It doubles the count
A single string counter
A HyperLogLog
A sorted set of request timestamps
A Bloom filter
41. Why are Redis Pub/Sub messages lost, and what is the alternative?
Pub/Sub is fire-and-forget. Redis does not store messages. It pushes each message to subscribers connected at that instant and then forgets it.
Messages are lost when:
- A subscriber is disconnected or restarting during the publish.
- A subscriber is too slow and exceeds
client-output-buffer-limit pubsub(default 32 MB hard, or 8 MB for 60 seconds). Redis then closes its connection. - A failover or reconnect happens. Nothing is replayed to a client that resubscribes.
| Pub/Sub | Streams |
| No persistence, no history | Persisted log with IDs |
| No acknowledgements | Consumer groups with XACK |
| Good for live notifications | Good for reliable work queues and event processing |
If you cannot afford to lose a message, use Streams.
Take quiz
Pub/Sub has a 10 subscriber maximum
AOF rewrites close subscribers
Keys expire on subscribe
Its output buffer exceeds the pubsub client-output-buffer-limit
Streams with consumer groups
KEYS patterns
Pub/Sub with PSUBSCRIBE
OBJECT FREQ
42. Why is a Redis Streams consumer group stuck with pending entries?
When a consumer reads a message with XREADGROUP, the entry moves into the group's Pending Entries List (PEL) and stays there until the consumer calls XACK. A growing PEL means messages are delivered but never acknowledged.
Investigate:
XINFO GROUPS orders XPENDING orders workers - + 10 XINFO CONSUMERS orders workers
Common causes:
- A consumer crashed after reading, so its entries are orphaned.
- The code forgot
XACK, or acknowledges only on success and throws on a bad message. - A poison message that fails every time and keeps being retried.
Recover with XAUTOCLAIM (Redis 6.2+) or XCLAIM to hand idle entries to a healthy consumer. Check the delivery count from XPENDING, and after a few attempts move the message to a dead-letter stream and acknowledge it.
Take quiz
XDEL on the consumer
XACK
XTRIM
XGROUP DESTROY
XREAD BLOCK
XADD NOMKSTREAM
XAUTOCLAIM
XLEN
43. How do you troubleshoot a Lua script blocking Redis?
Redis runs a Lua script atomically on the main thread. A long loop or a script that touches a lot of keys blocks every other client. After busy-reply-threshold (formerly lua-time-limit, default 5000 ms), Redis starts replying to other clients with BUSY Redis is busy running a script but does not interrupt the script.
Your options:
SCRIPT KILLstops it, but only if the script has not yet performed a write.- If it has already written,
SCRIPT KILLis refused, and the only way out isSHUTDOWN NOSAVE, which loses unsaved data.
Prevention: keep scripts short and bounded, never loop over unbounded data, declare all keys in KEYS (needed for Cluster), test with production-sized data, and watch INFO commandstats for eval and evalsha durations. If a script needs heavy work, move that work to the application and keep only the atomic part in Lua.
Take quiz
Always
Only on replicas
Only with AOF enabled
Only if the script has not performed any write yet
BUSY Redis is busy running a script
MOVED slot
NOAUTH
READONLY
44. How do you troubleshoot MULTI/EXEC and WATCH transaction failures?
Redis transactions queue commands with MULTI and run them together on EXEC. They are isolated, but they are not rolled back on a runtime error. If one command fails (for example INCR on a non-numeric string), the others still run.
Failure types:
- EXEC returns nil: a key under
WATCHchanged beforeEXEC, so the whole transaction was aborted. That is optimistic locking working as designed. Retry the read-modify-write loop with a small backoff. - EXECABORT: a command had a syntax error at queue time, so nothing executed.
- CROSSSLOT in Cluster: all keys must share a slot.
WATCH balance:42 GET balance:42 MULTI DECRBY balance:42 100 EXEC
If high contention causes constant retries, replace the pattern with a Lua script, which is atomic and needs no retry loop.
Take quiz
The server ran out of memory
A watched key was modified, so the transaction was aborted
The transaction succeeded
The client lost AUTH
All are rolled back
The server restarts
They still execute; there is no rollback
The queue is retried
45. How do you troubleshoot NOAUTH, WRONGPASS and NOPERM errors?
Each error points to a different layer:
| Error | Meaning |
| NOAUTH Authentication required | The client sent a command without authenticating. |
| WRONGPASS invalid username-password pair | Credentials are wrong, or the user is disabled. |
| NOPERM | The user authenticated but the ACL does not allow that command, key or channel. |
Debug with ACL WHOAMI to see the current user, ACL LIST for rules and ACL LOG for recent denials with the command and reason.
In HA setups, remember that passwords must line up: replicas need masterauth (and masteruser) to authenticate to the master, and Sentinel needs sentinel auth-pass for the monitored master. After a failover, a replica with a different password makes the new topology fail even though the old master worked. Also check that TLS and the client's username setting match.
Take quiz
CLIENT KILL
ACL GENPASS only
DEBUG SEGFAULT
ACL LOG
masterauth
maxmemory-policy
appendfsync
hz
46. How do you migrate Redis with zero downtime?
The safest pattern is to build the new instance as a replica of the old one, let it catch up, then switch.
- Start the new Redis (new version, new host or new size) and run
REPLICAOF old-host 6379. - Wait for the initial sync and watch
master_link_status:upand matching offsets inINFO replication. - Optionally pause writes briefly with
CLIENT PAUSE 5000 WRITEso the offsets converge. - Run
REPLICAOF NO ONEon the new node. - Switch the application endpoint, DNS entry or Sentinel configuration.
- Keep the old node as a fallback for a while, then decommission it.
For a version upgrade with Sentinel, upgrade replicas first, then trigger a controlled SENTINEL FAILOVER and upgrade the former master. For cross-version or cross-provider moves where replication is not possible, use tools such as redis-cli --rdb with a restore, or a live-migration tool, and expect a short write freeze.
Take quiz
FLUSHALL
CLIENT PAUSE with WRITE
DEBUG SLEEP 0
CONFIG SET save ''
The master
All nodes simultaneously
The replicas
Only the Sentinels
47. Why does Redis get OOMKilled in Kubernetes?
The container memory limit applies to the whole container, not to Redis's own accounting. Redis can use more memory than maxmemory because of client buffers, replication backlog, the fork child during RDB or AOF rewrite, fragmentation and Lua. When total RSS crosses the limit, the kernel kills the process and kubectl describe pod shows Reason: OOMKilled.
Fixes:
- Set
maxmemoryto roughly 60-70% of the container limit, leaving room for copy-on-write and buffers. Less if persistence is on and writes are heavy. - Set requests equal to limits for predictable scheduling.
- Use a persistent volume if the data must survive a restart.
- Use a
startupProbeor generous probe delays. A large dataset takes time to load, and an aggressive liveness probe creates a restart loop, which looks like repeated crashes. - Watch
mem_fragmentation_ratioand client output buffers.
Take quiz
Reason: Completed
Reason: ImagePullBackOff
Reason: Evicted by Redis
Reason: OOMKilled
Buffers, backlog and fork copy-on-write add memory beyond maxmemory
Redis refuses to start otherwise
The kernel doubles the limit
Probes require it
48. How do you troubleshoot Redis stuck in LOADING after a restart?
While Redis loads an RDB or replays an AOF, it answers commands with LOADING Redis is loading the dataset in memory. It is normal for a short time, but large datasets can take minutes.
Check progress with INFO persistence: loading:1, loading_loaded_perc and loading_eta_seconds.
If it is slow or never finishes:
- Large AOF: a long, un-rewritten AOF takes much longer than an RDB. Use RDB-preamble AOF (
aof-use-rdb-preamble yes) and rewrite regularly. - Slow disk or network storage.
- Swap or a memory limit causing load to thrash or fail.
- Orchestrator probes killing the process mid-load. Extend probe timeouts.
To reduce impact, keep replicas ready and fail over instead of waiting, and make sure applications retry on LOADING instead of failing hard.
Take quiz
rdb_last_save_time
loading_loaded_perc
aof_rewrite_scheduled
latest_fork_usec
appendfsync always
rdbcompression no
aof-use-rdb-preamble yes
maxclients 1
49. Which Redis metrics and alerts should you monitor in production?
Export INFO data with redis_exporter to Prometheus and graph it in Grafana. Group the alerts by failure type.
| Area | Metric | Alert on |
| Memory | used_memory, mem_fragmentation_ratio |
Above 80-85% of maxmemory; ratio under 1 or over 1.5 |
| Cache quality | evicted_keys, hit ratio |
Sustained eviction; sudden hit-ratio drop |
| Clients | connected_clients, blocked_clients, rejected_connections |
Near maxclients; any rejections |
| Replication | master_link_status, offset lag |
Link down; lag growing |
| Persistence | rdb_last_bgsave_status, latest_fork_usec |
Status not ok; fork time rising |
| Performance | ops/sec, slowlog length, CPU | New slow commands; sustained high CPU |
Also alert when role changes unexpectedly, which indicates a failover.
Take quiz
redis-benchmark
redis-check-aof
redis-sentinel
redis_exporter
The client connection limit being reached
A full disk
AOF corruption
Slow replication
50. What is your incident response when Redis is down in production?
Work from fast checks to deeper ones, and protect the database while you do it.
- Confirm scope: is it the process, the host, the network or the client? Try
redis-cli -h host pingfrom another machine. - Check the process:
systemctl status redis, then the log.dmesg | grep -i oomreveals an OOM kill. - Check resources: disk full, memory, file descriptors.
- Decide: if replicas exist, fail over (Sentinel, Cluster or manual
REPLICAOF NO ONE) rather than wait for a long reload. - Protect the backend: enable rate limiting or a circuit breaker so the database is not crushed by a cache miss flood.
- Restore from RDB or AOF if no replica is available, and watch the
LOADINGstate. - Warm up hot keys gradually before sending full traffic.
- Post-mortem: identify the root cause, add the missing alert and test the failover.
flowchart TD
A["Alert: Redis down"] --> B{Replica available?}
B -->|Yes| C["Fail over"]
B -->|No| D["Restore from RDB or AOF"]
C --> E["Protect database"]
D --> E
E --> F["Warm cache and post-mortem"]