cswork / libraryOpen practice workspace

Articles

Redis Interview Questions for Backend Engineers: Data Structures, Persistence, Replication, and Hot Keys

Prepare for Redis interview questions on data structures, RDB vs AOF, replication, Sentinel, Cluster, eviction, and hot-key diagnosis.

Redis interview questions for backend engineers test whether you can choose the right in-memory model, define durability, reason about asynchronous replication, and diagnose concentrated load. A strong answer does not stop at “Redis is fast.” It explains why a data type fits, what an acknowledged write survives, how failover can lose or expose data, and why one hot key can saturate one shard.

What Redis interviewers are actually testing

The interview signal is the quality of your boundaries: cache versus system of record, single command versus multi-step workflow, availability versus acknowledged durability, and distributed capacity versus per-key concentration.

AreaBaseline answerStrong backend signal
Data modelingUses strings for everythingMaps operations to a native type, names complexity, size, atomicity, and lifecycle
PersistenceSays AOF is safer than RDBDefines loss tolerance, write latency, recovery time, rewrite/snapshot cost, and backups
ReplicationAdds replicas for safetyExplains async propagation, PSYNC, failover gaps, read staleness, and WAIT limits
Hot keysAdds more shardsProves which key and shard are hot, then changes load concentration or access semantics

Which Redis data structure fits the workload?

Choose from the operations the application needs. Redis currently offers more than the classic structures, including JSON, probabilistic types, time series, and vector sets. In a general backend interview, however, strings, hashes, lists, sets, sorted sets, and streams are the most useful foundations.

NeedGood starting typeInterview caveat
Scalar, counter, token, serialized valueStringLarge serialized blobs make partial updates and memory ownership harder
Fields of one entityHashModel field-level access and expiry needs; key TTL applies to the hash as a key
Ordered queue with end operationsListArbitrary middle access and large blocking work need scrutiny
Unique membershipSetWhole-set operations can become expensive on high-cardinality values
Ranking by scoreSorted setUpdates are efficient, but memory and range size still matter
Append-only event log with consumer groupsStreamRetention, pending entries, acknowledgement, and replay must be designed

Are Redis commands automatically safe under concurrency?

An individual command is atomic from the perspective of other commands, but a client-side read-modify-write sequence is not. Prefer a single atomic command such as INCR, use conditional operations, or move a small rule into a script. MULTI/EXEC prevents interleaving among its queued commands; WATCH adds optimistic concurrency, not arbitrary rollback.

State the unit of correctness. A transfer across unrelated records may require a stronger source of truth and an idempotent workflow rather than clever Redis locking.

How should you reason about TTL and eviction?

Expiration is a per-key lifecycle rule. Eviction is a memory-pressure policy selected with maxmemory-policy. They solve different problems. A cache entry can expire on schedule even when memory is plentiful; a key can be evicted before its TTL when the configured policy needs space.

Redis offers policies such as allkeys-lru, allkeys-lfu, volatile variants that consider expiring keys, random policies, and noeviction. LRU and LFU are approximations designed for bounded overhead. Define whether every key is re-creatable before selecting an eviction policy; losing a coordination key is not equivalent to losing a cached product description.

For generic cache-aside consistency, invalidation races, TTL jitter, and stampede defenses, use the separate backend caching interview guide. This guide stays focused on Redis mechanisms.

RDB versus AOF persistence

Redis Open Source supports RDB snapshots, AOF logging, both together, or no persistence. The correct choice starts with a recovery objective: how much acknowledged data may be lost, how long restart may take, what steady-state write overhead is acceptable, and where independent backups live.

ModeWhat it recordsMain advantageMain risk or cost
RDBPoint-in-time dataset snapshotsCompact files and typically fast restartWrites after the latest completed snapshot can be lost
AOFAccepted write operations for replaySmaller loss window under suitable fsync policyMore write I/O, larger history, rewrite and replay cost
RDB + AOFBoth representationsCan combine backup convenience and a more complete restart logMore operational and resource complexity
NoneMemory onlyLowest persistence overheadRestart begins without the dataset

How does RDB snapshotting work?

During a background save, Redis forks a child process. The child writes a temporary RDB file and replaces the previous file after completion, while the parent continues serving commands. Copy-on-write means pages changed after the fork may require additional memory. A large dataset, high write rate, slow disk, or expensive fork can therefore create latency and memory pressure even though the save is “background.”

What does AOF durability depend on?

AOF appends write operations and replays them at startup. The appendfsync policy defines when buffered changes are synchronized to storage. Synchronizing every write favors durability and adds latency; every second is a common balance with a small loss window; letting the operating system decide weakens the bound.

AOF files need rewriting to remove superseded history. Capacity plans must cover copy-on-write growth, buffers, and rewrite files. If both AOF and RDB are enabled, Redis uses the more complete AOF during restart.

Persistence is not the same as backup. Replicating a deletion or corruption produces more copies of the bad state; an independent, tested restore path remains necessary.

How Redis replication works

Redis replication is asynchronous by default. A primary streams commands to replicas. After a disconnect, a replica sends its replication ID and offset through PSYNC; if the primary still has the needed backlog and history, it can perform a partial resynchronization. Otherwise, the replica needs a full synchronization.

This creates a clear failure boundary. A primary can acknowledge a write before a replica has processed it. If the primary fails and an older replica is promoted, recently acknowledged writes may be absent. Replica reads can also be stale, so route them only when the application tolerates that staleness or supplies a session-level safeguard.

Does WAIT make Redis strongly consistent?

No. WAIT asks for a number of replicas to acknowledge prior writes from the current client before a timeout. It can reduce the probability of losing a write, but the official replication documentation explicitly says it does not turn Redis into a strongly consistent CP system. Persistence configuration, failure timing, promotion, and network conditions still matter.

Name what an acknowledgement means in your design: applied in primary memory, received by replicas, synchronized to AOF, or preserved in an external source of truth. “Replicated” without that definition is ambiguous.

For vendor-neutral leaders, quorums, lag, and repair, use the database replication interview guide.

Sentinel versus Redis Cluster

Sentinel and Cluster solve different first-order problems. Sentinel monitors non-clustered Redis deployments, discovers the current primary, notifies operators or clients, and coordinates automatic failover. Redis Cluster partitions the key space and adds a primary-replica availability model for each partition.

DecisionSentinel deploymentRedis Cluster
Primary goalHigh availability for one logical, unsharded datasetHorizontal partitioning plus per-slot failover
Key distributionEvery node in the replication group represents the datasetKeys map into 16,384 hash slots owned by different primaries
Multi-key operationsSame-node constraints are simplerKeys generally must share a slot; hash tags can co-locate them
Scaling write capacityDoes not shard writesAdds primaries and moves slots

In Sentinel, failure-detection quorum is not the same as failover authorization; a majority of Sentinel processes must still authorize it. In Cluster, an overused hash tag can concentrate traffic on one slot.

Neither product choice removes application-level requirements. Clients need topology refresh, retry bounds, idempotency, timeouts, and behavior for failover or slot migration.

Hot key, big key, and cache stampede

These symptoms are related but not interchangeable:

  • A hot key receives a disproportionate share of operations, CPU time, or network bytes.
  • A big key has a large value or high element count, making memory, transfer, deletion, or complex commands expensive.
  • A cache stampede occurs when many requesters simultaneously rebuild missing or expired data.

In Redis Cluster, one key belongs to one hash slot and one primary. Adding shards does not split that key automatically. First verify per-shard CPU, command latency, network, key size, and access concentration. Also inspect SLOWLOG and command complexity; an O(1) command at extreme frequency and an O(N) command over a huge collection require different fixes.

Redis Open Source 8.6 adds HOTKEYS tracking based on CPU time and network bytes during a tracking window. The older redis-cli --hotkeys samples LFU counters and requires an LFU policy. State the version before recommending either method.

Mitigations change semantics and therefore need trade-offs:

  1. Use a bounded application-local cache for read-only data.
  2. Split aggregatable values into subkeys when one-key atomicity is unnecessary.
  3. Replicate immutable values behind derived keys and randomize reads.
  4. Coalesce refreshes and serve bounded stale data when policy permits it.
  5. Rate-limit expensive work while protecting the source of truth.

Do not solve every hotspot with a lock. A lock can serialize the same overload, fail during owner loss, or create a new availability dependency.

Three failure scenarios to rehearse

A primary restarts with persistence disabled

If it restarts empty and replicas synchronize from it, valid replica data can be replaced by the empty dataset. Redis warns against automatic restart in this configuration. Use persistence where data safety matters or repair the topology deliberately.

A replica is promoted while behind

Quantify the lost-write window, make side effects idempotent, and reconcile against an authoritative log or database. A replica does not make failover lossless.

One slot saturates while the cluster is mostly idle

Find the high-traffic keys and commands on that slot, distinguish a single hot key from a poor key-tagging pattern, and change the data or access model. Moving the entire slot to another node relocates the bottleneck; it does not divide a single key's demand.

A seven-day Redis interview plan

  • Day 1: Map six workloads to Redis data types and state operation complexity.
  • Day 2: Explain TTL, eviction, memory limits, and atomic update boundaries.
  • Day 3: Compare RDB, AOF policies, rewrite, restart, and independent backups.
  • Day 4: Draw full and partial replication sync plus a failover loss window.
  • Day 5: Explain Sentinel, Cluster slots, hash tags, and client topology changes.
  • Day 6: Diagnose hot key, big key, stampede, slow command, and memory pressure separately.
  • Day 7: Run a mock where every recommendation includes evidence, failure mode, and verification.

Frequently asked questions

What is the difference between RDB and AOF?

RDB captures point-in-time dataset snapshots; AOF records accepted write operations for replay. RDB is compact and often fast to load but can lose changes after the last snapshot. AOF can provide a smaller loss window under an appropriate fsync policy, with more write, storage, rewrite, and replay cost.

Is Redis replication synchronous?

Redis replication is asynchronous by default. The primary can acknowledge a write before replicas process it. WAIT can wait for replica acknowledgements and reduce loss probability, but it does not provide a universal strong-consistency guarantee. Define persistence, failover, and client retry behavior separately.

When should you use Sentinel instead of Cluster?

Use Sentinel when the primary need is failover for one unsharded logical dataset and its capacity fits that model. Use Cluster when you need to partition keys and write load across primaries. Both require replicas, failure planning, topology-aware clients, and explicit application guarantees.

How do you detect a Redis hot key?

Start with uneven shard CPU, latency, and network evidence, then identify concentrated key access using a version-appropriate method. Redis 8.6 provides HOTKEYS; redis-cli --hotkeys uses LFU counters and requires an LFU policy. Confirm key size and command complexity so a big key is not mislabeled.

How should you mitigate a Redis hot key?

Choose from application-local caching, safe value replication, subkey partitioning, request coalescing, bounded stale serving, or rate limits according to correctness. Adding shards or moving one slot only relocates a single-key bottleneck. Verify reduced per-shard CPU, tail latency, and source load without violating freshness.

Final takeaway

Strong Redis interview answers make guarantees explicit. Model the workload with native operations, set persistence from recovery objectives, treat replication as asynchronous unless a stronger boundary is proven, distinguish Sentinel failover from Cluster sharding, and diagnose hot keys with measurements before changing the data model.

Sources and Further Reading