Prev Next

Database / Redis real time troubleshooting and scenario based Interview questions

Last updated

1. How do you troubleshoot high latency in Redis? 2. Redis memory keeps growing. How do you investigate? 3. What happens when Redis reaches maxmemory? 4. How do you find big keys without blocking Redis? 5. Why is KEYS * dangerous in production? 6. How do you identify slow commands using SLOWLOG? 7. How do you troubleshoot Redis hitting 100% CPU? 8. Why does Redis latency spike during RDB snapshots? 9. How do you troubleshoot a replica that keeps resyncing? 10. What happens when a Redis master crashes without Sentinel? 11. How does Sentinel failover work step by step? 12. Why might a Sentinel failover not trigger? 13. How do you prevent split-brain in a Redis failover? 14. How do you handle a cache stampede? 15. How do you prevent cache penetration? 16. What is a cache avalanche and how do you prevent it? 17. How do you handle a hot key problem? 18. Why do clients get OOM command not allowed when used memory > maxmemory? 19. How do you fix MISCONF Redis is configured to save RDB snapshots? 20. Why does Redis fail with Can't save in background: fork? 21. How do you troubleshoot ERR max number of clients reached? 22. How do you debug a growing blocked_clients count? 23. How do you troubleshoot AOF rewrite taking too long? 24. What happens when a Redis AOF file is corrupted? 25. How do you recover Redis from a corrupted RDB file? 26. How do you troubleshoot high memory fragmentation in Redis? 27. How do you troubleshoot CLUSTERDOWN errors in Redis Cluster? 28. What happens when a Redis Cluster master node fails? 29. How do you fix MOVED and ASK redirection storms? 30. How do you handle CROSSSLOT errors in Redis Cluster? 31. How do you rebalance a Redis Cluster with uneven memory across nodes? 32. How do you troubleshoot Redis replication lag? 33. Why does the replication backlog size matter when troubleshooting resyncs? 34. How do you implement a safe distributed lock with Redis? 35. Why did my Redis lock expire before the work finished? 36. How do you troubleshoot keys expiring unexpectedly? 37. Why do expired keys still consume memory in Redis? 38. How do you troubleshoot eviction causing unexpected cache misses? 39. How do you choose an eviction policy for a given scenario? 40. How do you build a Redis rate limiter and fix incorrect counts? 41. Why are Redis Pub/Sub messages lost, and what is the alternative? 42. Why is a Redis Streams consumer group stuck with pending entries? 43. How do you troubleshoot a Lua script blocking Redis? 44. How do you troubleshoot MULTI/EXEC and WATCH transaction failures? 45. How do you troubleshoot NOAUTH, WRONGPASS and NOPERM errors? 46. How do you migrate Redis with zero downtime? 47. Why does Redis get OOMKilled in Kubernetes? 48. How do you troubleshoot Redis stuck in LOADING after a restart? 49. Which Redis metrics and alerts should you monitor in production? 50. What is your incident response when Redis is down in production?

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:

  1. SLOWLOG GET 20 to catch O(N) commands such as KEYS, SMEMBERS on a huge set or a large LRANGE.
  2. LATENCY DOCTOR and LATENCY LATEST for fork, AOF fsync and expire-cycle spikes.
  3. INFO commandstats and INFO clients for blocked clients and connection storms.
  4. INFO memory to 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
Which command reports fork and AOF fsync latency events recorded inside Redis?
CLIENT LIST
INFO keyspace
CONFIG GET timeout
LATENCY DOCTOR
A high result from redis-cli --intrinsic-latency on the Redis host most likely means:
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:

  1. Run redis-cli --bigkeys or --memkeys (both use SCAN, so they do not block).
  2. Check MEMORY USAGE <key> for suspects.
  3. Sample key prefixes with SCAN and count how many have no TTL (TTL key returns -1).
  4. Look at INFO clients for large client output buffers (omem in CLIENT 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
In CLIENT LIST, which field shows memory used by a client's pending replies?
flags
omem
idle
db
TTL mykey returns -1. What does it mean?
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
With noeviction at maxmemory, what happens to a GET on an existing key?
It returns OOM as well
The key is evicted first
The connection is closed
It still succeeds; only commands that add memory are rejected
Why can a volatile-lru setup still throw OOM errors?
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:

  1. Delete it with UNLINK, which frees memory in a background thread, instead of DEL.
  2. Split it, for example a huge hash into user:1:part:0..N buckets.
  3. Read it with HSCAN, SSCAN or ZRANGE with limits instead of fetching everything.
Take quiz
Which command removes a very large key without stalling the main thread?
FLUSHALL SYNC
UNLINK
KEYS
DEL with pipelining
--bigkeys avoids blocking Redis mainly because it:
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
What is the key behavioural difference between SCAN and KEYS?
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
Your code processes keys from SCAN. What must it tolerate?
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
The unit of slowlog-log-slower-than is:
Milliseconds
Microseconds
Seconds
Number of keys touched
Why might SLOWLOG look clean while clients still see delays?
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, big LRANGE, 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
Why does Redis show 100% on only one core under heavy load?
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
Which fix directly reduces a mass-expiry CPU spike?
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:

  1. The fork itself copies page tables. The bigger the dataset, the longer the main thread is paused. Check latest_fork_usec in INFO stats.
  2. 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
Which INFO stats field shows how long the last fork took?
rdb_last_save_time
latest_fork_usec
total_commands_processed
expired_keys
Why are Transparent Huge Pages harmful during a Redis snapshot?
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 replica kills the link while the RDB is being transferred under heavy writes. Raise it.
  • Timeouts: repl-timeout is 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
Which setting controls how much recent write history a master keeps for partial resync?
maxmemory-samples
slowlog-max-len
tcp-keepalive
repl-backlog-size
The master drops a replica during full sync under heavy writes. Which limit is the likely cause?
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:

  1. Check INFO replication on each replica and pick the one with the highest slave_repl_offset. That replica has the most data.
  2. Run REPLICAOF NO ONE on it to promote it.
  3. Run REPLICAOF new-master-ip port on the other replicas.
  4. 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
Which command promotes a replica to master manually?
SLAVEOF YES
REPLICAOF NO ONE
CLUSTER FAILOVER FORCE on the master
BGREWRITEAOF
Which replica should you promote after a master crash?
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.

  1. SDOWN: one Sentinel gets no valid reply from the master for down-after-milliseconds.
  2. ODOWN: at least quorum Sentinels agree the master is down.
  3. Leader election: Sentinels vote and one leader is chosen. It needs authorization from a majority of all Sentinels.
  4. Replica selection: by replica-priority, then highest replication offset, then lowest run ID.
  5. The leader sends REPLICAOF NO ONE to the chosen replica and reconfigures the other replicas.
  6. 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
What is the order of failure states in Sentinel?
ODOWN first, then SDOWN
Leader election first, then SDOWN
SDOWN and ODOWN are the same state
SDOWN first, then ODOWN once the quorum agrees
Who is selected first when Sentinel picks a replica to promote?
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-ip mistakes.
  • A recent failover: Sentinel waits failover-timeout before trying again.

Check SENTINEL master mymaster, SENTINEL replicas mymaster and the Sentinel logs for +sdown, +odown and -failover-abort-not-elected.

Take quiz
Why is a two-Sentinel deployment a poor choice?
Sentinel only supports odd quorums above 5
A majority needs both Sentinels, so losing one blocks failover
It disables replication
It doubles memory use
Which replica setting makes a replica ineligible for promotion?
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
What happens to writes made on an isolated old master after it rejoins as a replica?
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
Which settings let a master stop writes when it loses its replicas?
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:

  1. 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.
  2. TTL jitter: use ttl + random(0, 10%) so related keys do not expire together.
  3. Stale-while-revalidate: store a soft expiry inside the value, return the old value, and refresh in the background.
  4. Probabilistic early refresh: refresh slightly before expiry with rising probability.
  5. 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
Which Redis command pattern implements a single-flight rebuild lock?
FLUSHDB ASYNC
SET key token NX PX with a short TTL
KEYS lock:*
CONFIG SET maxmemory 0
Why add jitter to cache TTLs?
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:

  1. Cache the miss: store a null marker with a short TTL, such as 30-60 seconds.
  2. Bloom filter: keep all valid IDs in a RedisBloom filter and reject anything where BF.EXISTS returns 0.
  3. Validate input at the API layer (format, range) before touching Redis or the DB.
  4. 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
A Bloom filter says an item is NOT present. How reliable is that answer?
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
Why should cached null results use a short TTL?
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
Which action reduces avalanche risk from keys expiring together?
Using FLUSHALL nightly
Randomizing TTLs
Raising maxclients
Disabling persistence
How does a circuit breaker help during an avalanche?
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..N and 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
Why does adding more cluster nodes not fix a single hot key?
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
Which technique spreads reads for one hot key across multiple keys?
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:

  1. Check INFO memory for used_memory, maxmemory and the policy.
  2. Find big or TTL-less keys with --bigkeys and SCAN.
  3. Short term: CONFIG SET maxmemory higher (if the host has room) or UNLINK junk keys.
  4. Long term: switch to allkeys-lru for a pure cache, add TTLs, or scale out.
Take quiz
Which error text do clients receive when writes are rejected due to memory limits?
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
For a pure cache, which policy usually avoids OOM write errors?
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:

  1. Read the Redis log for the BGSAVE failure message.
  2. Check disk space (df -h) and inodes on the dir path.
  3. Check that the Redis user can write to dir and dbfilename.
  4. 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
Which INFO persistence field confirms the last snapshot succeeded?
aof_enabled
loading
rdb_changes_since_last_save only
rdb_last_bgsave_status
What does setting stop-writes-on-bgsave-error to no risk?
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:

  1. Set vm.overcommit_memory = 1 in /etc/sysctl.conf and apply with sysctl -p.
  2. Leave headroom for copy-on-write. Under heavy writes during a save, memory use can approach double the dataset.
  3. Keep maxmemory well below physical RAM, and avoid running other big processes on the same host.
  4. 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
Which sysctl setting is recommended so fork() does not fail on Redis hosts?
vm.swappiness = 100
vm.overcommit_memory = 1
net.core.somaxconn = 1
fs.file-max = 0
Why must you leave RAM headroom beyond the dataset size?
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:

  1. INFO clients to see connected_clients and INFO stats for rejected_connections.
  2. CLIENT LIST and group by addr or name to see which app host opens the most connections.
  3. Look at the idle field. 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
Which INFO stats field counts connections refused because of the client limit?
expired_keys
sync_full
keyspace_hits
rejected_connections
A CLIENT LIST shows thousands of connections with very high idle values. Most likely cause?
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 WAIT call 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
In CLIENT LIST, which flag marks a client blocked in a blocking operation?
r
b
M
x
Why avoid timeout 0 on BLPOP in long-lived workers?
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:

  1. INFO persistence: aof_rewrite_in_progress, aof_current_rewrite_time_sec, aof_last_bgrewrite_status.
  2. Disk I/O with iostat -x. A saturated disk slows both rewrite and normal fsync.
  3. The log warning Asynchronous AOF fsync is taking too long.
  4. 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
Which INFO persistence field tells you if an AOF rewrite is currently running?
rdb_bgsave_in_progress is the only one
loading_eta_seconds
aof_enabled
aof_rewrite_in_progress
What does no-appendfsync-on-rewrite yes trade off?
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:

  1. Stop Redis and back up the AOF files first.
  2. Run redis-check-aof on the file (on Redis 7+, point it at the manifest or the specific incr file in appendonlydir).
  3. Run redis-check-aof --fix to truncate at the first invalid entry.
  4. 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
Which tool repairs a corrupted AOF file?
redis-benchmark
redis-check-aof --fix
redis-sentinel --repair
redis-cli --bigkeys
What should you do before running --fix on an AOF?
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:

  1. Copy the damaged file somewhere safe.
  2. Run redis-check-rdb dump.rdb to see where it breaks.
  3. 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).
  4. Restore the best copy into dir and start Redis.
  5. 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
Which tool inspects an RDB file for corruption?
redis-check-aof only
redis-cli --latency
redis-cluster-fix
redis-check-rdb
When both AOF and RDB exist and appendonly is yes, which does Redis load at startup?
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.

  1. Check allocator_frag_ratio to separate allocator fragmentation from other overhead.
  2. Enable online defragmentation: CONFIG SET activedefrag yes (needs the bundled jemalloc).
  3. Try MEMORY PURGE to ask jemalloc to release dirty pages.
  4. 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
What does a mem_fragmentation_ratio below 1.0 usually indicate?
Perfect memory use
Redis memory is being swapped out by the OS
AOF is disabled
Replicas are ahead of the master
Which setting enables online defragmentation in Redis?
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 migrating or importing state.

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
Which setting makes the entire cluster stop when any slot is uncovered?
cluster-enabled no
cluster-announce-ip
cluster-replica-no-failover yes
cluster-require-full-coverage yes
Which command checks for open or uncovered slots and inconsistent state?
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.

  1. The failed master's replicas start an election and ask the other masters for votes.
  2. The replica with the best offset usually wins, promotes itself and takes over the slots.
  3. The new master announces the change with a higher config epoch, and clients get MOVED redirects 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
What must happen before a cluster node is marked FAIL?
A client reports an error
A majority of masters agree it is unreachable
The replica deletes its RDB
The node reaches maxclients
Which node typically takes over the failed master's slots?
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
Which reply tells a client that a slot has moved permanently?
ASK
LOADING
BUSY
MOVED
What must a client send to the target node after receiving ASK?
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
What part of a key name does Redis Cluster hash when a hash tag is present?
The last 8 characters
The text inside the first curly braces
The entire key name
Only the prefix before the first colon
What risk comes from putting all of a large tenant's keys under one hash tag?
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.

  1. If slot counts are uneven (for example after adding a node): redis-cli --cluster rebalance 10.0.0.1:7000 --cluster-use-empty-masters.
  2. To move specific slots: redis-cli --cluster reshard, choosing source, target and slot count.
  3. If a few slots hold giant keys, find them with --bigkeys and split those keys. Moving slots alone will not fix it.
  4. 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
Which flag lets cluster rebalance place slots on newly added empty masters?
--cluster-yes-all
--bigkeys
--cluster-replicas 0
--cluster-use-empty-masters
Why can slot counts be even while memory is uneven?
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 MSET or 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
Which command makes a client wait until N replicas acknowledge earlier writes?
PSYNC
WAIT
SCAN
DEBUG RELOAD
Where do you see per-replica offset and lag?
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
What does a replica send to try a partial resync?
Its entire dataset
A KEYS listing
Its AOF file
Its replication ID and offset via PSYNC
Writes are 5 MB/s and you want to survive a 60 s outage. Roughly what backlog is needed?
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
Why release a lock with a compare-and-delete Lua script instead of DEL?
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
Which SET options create a lock only if absent, with an expiry?
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:

  1. Lock renewal (watchdog): a background thread extends the TTL with a token-checked PEXPIRE while the work continues. Libraries such as Redisson do this automatically.
  2. Right-size the TTL using real p99 durations plus headroom.
  3. Fencing tokens: each lock grant returns an increasing number, and the database or service rejects writes with an older number.
  4. 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
Which mechanism lets the resource reject a stale lock holder?
A longer key name
Disabling expiry
Running KEYS before work
A fencing token that increases with each lock grant
What does a lock watchdog do?
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 SET on an existing key removes its TTL (use KEEPTTL to preserve it), and the reverse, a code path that always sets a short TTL.
  • A shared constant such as EXPIRE key 60 in the wrong module.
  • Wrong time unit: seconds with EX versus milliseconds with PX.
  • 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
What happens to a key's TTL when you run a plain SET on it?
The TTL doubles
The TTL is removed unless KEEPTTL is used
The TTL is unchanged
The key is deleted
Which INFO stats counter distinguishes memory eviction from TTL expiry?
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:

  1. Lazy expiration: when a key is accessed and found expired, it is deleted then.
  2. 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 yes so freeing large expired values does not block.
  • Watch expired_keys and expired_stale_perc in INFO stats.
Take quiz
What is lazy expiration in Redis?
Deleting all keys at midnight
Moving keys to disk
Expiring only on replicas
Deleting an expired key only when it is accessed
Which setting makes freeing large expired values non-blocking?
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:

  1. Check used_memory against maxmemory and look for new big keys or a feature that started caching larger values.
  2. Check the policy. allkeys-random or a poorly chosen volatile-ttl may discard hot data. allkeys-lfu often protects frequently read keys better.
  3. 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
How is the cache hit ratio calculated from INFO stats?
evicted_keys divided by expired_keys
keyspace_hits divided by (hits + misses)
used_memory divided by maxmemory
connected_clients divided by maxclients
Misses and evicted_keys both climb together. What does that suggest?
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
Which policy fits a pure cache with highly skewed access to a few hot keys?
noeviction
volatile-ttl
allkeys-random on a store that holds critical data
allkeys-lfu
Redis is the primary store for job queues. Which policy is safest?
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
Why is separate INCR then EXPIRE risky in a rate limiter?
INCR does not work on strings
A crash between them leaves a counter with no expiry
EXPIRE removes the counter
It doubles the count
Which structure suits a precise sliding window limiter?
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
Why can a subscriber disconnect under heavy Pub/Sub traffic?
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
Which Redis feature adds acknowledgements and replay for messages?
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
Which command acknowledges a processed stream message?
XDEL on the consumer
XACK
XTRIM
XGROUP DESTROY
Which command transfers idle pending entries from a dead consumer to another one?
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:

  1. SCRIPT KILL stops it, but only if the script has not yet performed a write.
  2. If it has already written, SCRIPT KILL is refused, and the only way out is SHUTDOWN 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
When does SCRIPT KILL succeed?
Always
Only on replicas
Only with AOF enabled
Only if the script has not performed any write yet
What reply do other clients receive while a script exceeds the busy threshold?
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 WATCH changed before EXEC, 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
EXEC returns nil after a WATCH. What does it mean?
The server ran out of memory
A watched key was modified, so the transaction was aborted
The transaction succeeded
The client lost AUTH
What happens to other queued commands if one command fails at runtime inside EXEC?
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
Which command lists recent ACL denials with reasons?
CLIENT KILL
ACL GENPASS only
DEBUG SEGFAULT
ACL LOG
Replicas fail to sync after a password change. Which setting must match the master's password?
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.

  1. Start the new Redis (new version, new host or new size) and run REPLICAOF old-host 6379.
  2. Wait for the initial sync and watch master_link_status:up and matching offsets in INFO replication.
  3. Optionally pause writes briefly with CLIENT PAUSE 5000 WRITE so the offsets converge.
  4. Run REPLICAOF NO ONE on the new node.
  5. Switch the application endpoint, DNS entry or Sentinel configuration.
  6. 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
Which command briefly stops writes to let replica offsets converge?
FLUSHALL
CLIENT PAUSE with WRITE
DEBUG SLEEP 0
CONFIG SET save ''
When upgrading a Sentinel-managed setup, which node do you upgrade first?
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:

  1. Set maxmemory to roughly 60-70% of the container limit, leaving room for copy-on-write and buffers. Less if persistence is on and writes are heavy.
  2. Set requests equal to limits for predictable scheduling.
  3. Use a persistent volume if the data must survive a restart.
  4. Use a startupProbe or generous probe delays. A large dataset takes time to load, and an aggressive liveness probe creates a restart loop, which looks like repeated crashes.
  5. Watch mem_fragmentation_ratio and client output buffers.
Take quiz
What does kubectl describe pod show for a container killed for exceeding its memory limit?
Reason: Completed
Reason: ImagePullBackOff
Reason: Evicted by Redis
Reason: OOMKilled
Why set maxmemory well below the container limit?
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
Which INFO persistence field shows how far the dataset load has progressed?
rdb_last_save_time
loading_loaded_perc
aof_rewrite_scheduled
latest_fork_usec
Which setting makes AOF files load faster by embedding a snapshot?
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
Which tool commonly exposes Redis INFO data to Prometheus?
redis-benchmark
redis-check-aof
redis-sentinel
redis_exporter
A rising rejected_connections value most directly points to:
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.

  1. Confirm scope: is it the process, the host, the network or the client? Try redis-cli -h host ping from another machine.
  2. Check the process: systemctl status redis, then the log. dmesg | grep -i oom reveals an OOM kill.
  3. Check resources: disk full, memory, file descriptors.
  4. Decide: if replicas exist, fail over (Sentinel, Cluster or manual REPLICAOF NO ONE) rather than wait for a long reload.
  5. Protect the backend: enable rate limiting or a circuit breaker so the database is not crushed by a cache miss flood.
  6. Restore from RDB or AOF if no replica is available, and watch the LOADING state.
  7. Warm up hot keys gradually before sending full traffic.
  8. 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"]
Take quiz
Which command can reveal that the Linux OOM killer stopped Redis?
redis-cli --bigkeys
dmesg | grep -i oom
SLOWLOG GET
CONFIG REWRITE
Why enable rate limiting or a circuit breaker during a Redis outage?
To speed up AOF loading
To rename the master
To stop the database from being overwhelmed by cache-miss traffic
To raise maxclients
«
»

Comments & Discussions