# Redis for system design interviews

> Redis is an in-memory data structure server used for caches, counters, sessions, rankings, and short-lived coordination state. In a system design interview, explain which data Redis owns, which data can be rebuilt, and what happens when keys expire, memory fills, or a primary fails.

Source: https://sysround.com/tech/redis
Updated: 2026-11-05


## How it works

Clients send commands over persistent TCP connections using the Redis protocol. Most command execution on a node is serialized on a main thread, although networking and background work can use other threads depending on version and configuration. This makes individual commands atomic relative to other clients, but expensive commands and long scripts can delay unrelated requests.

Redis stores keys and values in memory, with types such as strings, hashes, lists, sets, sorted sets, and streams. Choose the type around the operation: strings for cached objects and counters, hashes for fields, and sorted sets for ranked access. Complexity matters: a large range query or collection scan can consume substantial CPU and network bandwidth even when the data is in memory.

Keys can have expiration times. Redis removes expired keys when accessed and through active expiration work, so expiration is not a precise task scheduler. Separately, maxmemory and an eviction policy control what happens under memory pressure. TTL answers how long data remains valid; eviction answers what to remove when memory is scarce.

Persistence is optional and configurable. RDB creates point-in-time snapshots; AOF records write operations and periodically rewrites the log into a compact representation. Snapshotting and AOF rewriting commonly involve a background child process, so fork overhead, copy-on-write memory, and disk capacity belong in the sizing discussion.

A primary can replicate to replicas, normally asynchronously. Sentinel monitors non-clustered Redis deployments and coordinates failover, while Redis Cluster combines sharding with replica promotion. Clients must support the chosen topology, including discovery, reconnects, and Cluster redirections.

## What it gives you in a design

- **Cache-aside storage.** Applications can read Redis first and populate it from a database on a miss. Define invalidation, TTLs, and miss behavior explicitly because Redis does not automatically keep cached values synchronized with the source database.
- **Atomic counters and conditional writes.** Commands such as INCR and SET with NX and an expiration support counters, admission checks, and temporary claims. A client timeout leaves the result uncertain, so blindly retrying a non-idempotent increment can apply it twice.
- **Server-side atomic logic.** Lua scripts and Redis Functions can combine checks and updates without interleaving from other clients. Keep execution bounded, and remember that atomic execution does not provide rollback after a runtime error.
- **Transactions and optimistic concurrency.** MULTI/EXEC executes queued commands without interleaving; WATCH allows an optimistic retry when watched keys change. Redis transactions do not provide SQL-style rollback, and Cluster multi-key operations generally require keys in the same hash slot.
- **Rankings and compact summaries.** Sorted sets support leaderboards and time-indexed collections, while HyperLogLog supports approximate distinct counts. State whether the design needs exact membership, exact counts, or only an estimate before choosing a structure.
- **Pub/Sub and Streams.** Pub/Sub broadcasts to connected subscribers without persistence or replay. Streams retain entries and support consumer groups with pending-entry tracking, but applications still need retention rules, recovery of abandoned work, and idempotent processing.
- **Pipelining.** Pipelining sends multiple commands without waiting for each response, reducing network round trips. It does not make the commands atomic, and large batches increase buffering and can worsen latency for other clients.

## Scaling, replication and failure

Redis Cluster maps keys to 16,384 hash slots distributed across primaries. Clients route requests using the slot map and follow MOVED or ASK redirections during topology changes. Hash tags, such as order:{123}:items and order:{123}:status, place related keys together for same-slot operations, but excessive co-location can create an overloaded shard.

Adding shards spreads keys and memory demand, but a single hot key still belongs to one primary. Address hot reads with application-local caching, request coalescing, or replica reads where stale results are acceptable. Splitting a hot counter across keys distributes writes but makes exact reads and global admission checks harder.

Replication is asynchronous by default, so a promoted replica can be missing acknowledged writes. WAIT can request replica acknowledgments and reduce the risk, but it does not turn Redis into a strongly consistent consensus-backed store. Replica reads can also lag behind the primary.

Cluster failover depends on failure detection, eligible replicas, and primary-majority authorization; network partitions can interrupt service and lose recent writes. Plan memory headroom for replication buffers, persistence, resharding, and copy-on-write overhead. At the application boundary, use timeouts, bounded retries, and a deliberate fallback so a Redis outage does not overwhelm the backing database.

## Limits and defaults worth knowing

- **Cluster partition count:** Redis Cluster uses exactly 16,384 hash slots. Slots are assigned to primaries; they are not equivalent to nodes.
- **String value size:** A Redis string value is limited to 512 MB. Practical cache values should usually be much smaller to limit transfer time, memory use, and command latency.
- **Memory limit and eviction defaults:** On 64-bit Redis, maxmemory defaults to 0, meaning no configured dataset memory limit. The default eviction policy is noeviction; managed services may supply different settings.
- **Expiration precision:** Expiration can be specified in milliseconds, but physical deletion is performed through access checks and active expiration. Expiration notifications are not guaranteed to occur exactly at the TTL deadline.
- **AOF fsync policy:** AOF supports always, everysec, and no fsync policies. With everysec, a crash can typically lose about one second of recent writes; this is not a strict upper bound under storage or operating-system problems.
- **Cluster multi-key operations:** Multi-key commands, transactions, and scripts generally require all involved keys to share one hash slot. Redis Cluster does not provide general cross-shard transactions.

## Use it when

- Repeated reads can be served from a bounded cache, and the design can tolerate or explicitly control stale data.
- A rate limiter or admission controller needs short, atomic operations on per-user or per-account state.
- Ranked sets, counters, temporary presence, or expiring sessions fit Redis data structures better than repeated database queries.
- The working set fits a realistic memory budget, including object overhead, replicas, and operational headroom.
- Transient live notifications or retained streams are useful, and their delivery and recovery requirements match the chosen Redis mechanism.

## Avoid it when

- Losing even an acknowledged write is unacceptable, such as for a financial ledger or the authoritative allocation of scarce inventory.
- The dataset is large, mostly cold, and more economical on disk than in replicated memory.
- The workload needs joins, arbitrary analytical queries, or general transactions across independently sharded records.
- A durable event backbone needs long retention, large replay workloads, and storage economics better served by a dedicated distributed log.

## What interviewers ask about it

### What happens when Redis is down?

For a cache, fall back only within the database's capacity, using request coalescing, concurrency limits, or load shedding to prevent a miss storm. For a rate limiter or session check, choose fail-open or fail-closed based on the security and availability requirements rather than treating Redis failure as an ordinary cache miss.

### How do you keep the cache consistent with the database?

Name the database as the source of truth and describe a concrete update path, such as committing the database write before invalidating the cache. Concurrent readers can still repopulate stale data, so use bounded TTLs, versions, or an ordered change stream when stronger freshness is required.

### How would you implement an atomic distributed rate limit?

Use a bounded script to read the bucket state, decide admission, update the state, and set expiration in one atomic operation. In Cluster, keep that bucket's keys in one slot, then explain clock handling, uncertain retries, failover write loss, and the chosen outage policy.

### Does SET NX with a TTL give you a safe distributed lock?

It gives a lease, not proof that an old holder has stopped working after a pause or partition. Release it only after atomically checking a unique ownership token, and use fencing enforced by the protected resource when stale holders could cause damage; asynchronous failover can also permit overlapping holders.

### How do you handle a hot key or cache stampede?

For hot reads, consider a short-lived local cache and request coalescing; for synchronized expiration, add TTL jitter and refresh popular values before they expire. Sharding alone does not split a single key's load, and stale-while-revalidate is appropriate only when serving stale data is acceptable.

### How do you size and observe Redis?

Estimate key count, serialized value size, per-key and data-structure overhead, replication, and persistence headroom rather than counting payload bytes alone. Track command latency, memory and fragmentation, evictions, hit rate, replication lag, client buffers, and slow commands to distinguish capacity problems from hot keys or expensive operations.

## Common mistakes

- Calling Redis single-threaded and concluding that every command is cheap, while ignoring command complexity, large replies, scripts, and background work.
- Equating atomic execution with durable, exactly-once effects, or assuming a successful primary response guarantees survival through failover.
- Mixing disposable cache entries with correctness-critical coordination state under an eviction policy that can remove either.
- Using KEYS or unbounded collection reads in request paths, or assuming SCAN is a consistent snapshot without duplicates during changes.

## Alternatives

- **Memcached:** Choose it for a straightforward disposable object cache when Redis data structures, persistence, and server-side atomic logic are unnecessary.
- **PostgreSQL:** Choose it when constraints, durable transactions, and authoritative state matter more than serving the working set directly from memory.
- **etcd:** Choose it for small coordination metadata that requires consensus-backed consistency, such as configuration, leader election, and fenced ownership.
- **Apache Kafka:** Choose it for a durable partitioned event log with long retention, replay, and multiple independent consumers rather than treating Redis Pub/Sub as durable messaging.

## Interview questions where it comes up

- [Design a distributed cache](https://sysround.com/questions/design-distributed-cache): Redis provides a concrete basis for discussing partition ownership, eviction, expiration, hot keys, and replica failover.
- [Design a distributed rate limiter](https://sysround.com/questions/design-rate-limiter): Atomic scripts and expiring state support distributed rate-limit algorithms, with explicit trade-offs around outages and failover.
- [Design a URL shortener like Bitly](https://sysround.com/questions/design-url-shortener): Redis can cache popular short-code mappings while the durable database remains authoritative.
- [Design a news feed like Facebook](https://sysround.com/questions/design-news-feed): Redis can hold bounded feed ID lists and cached post data, while durable storage supports reconstruction after eviction or failure.
- [Design a top K trending system](https://sysround.com/questions/design-top-k): Sorted sets support ranked access, but window expiration, duplicate events, and cross-shard aggregation still need explicit designs.
- [Design Netflix's concurrent screen limit](https://sysround.com/questions/design-netflix-screen-limit): Atomic lease admission and expiration fit Redis operations, but strict account-wide limits require addressing stale holders and failover write loss.

## FAQ

### Is Redis a cache or a database?

Redis can serve either role because it stores structured data and offers persistence. A cache can usually be rebuilt from another source, while a database owns authoritative state. If Redis owns the data, explicitly evaluate persistence settings, eviction, backups, and acknowledged-write loss during failover.

### What is the difference between Redis Cluster and Sentinel?

Sentinel monitors primary-replica deployments, discovers failures, and coordinates promotion, but it does not shard the dataset. Redis Cluster partitions keys across hash slots and includes failover for replicated shards. Cluster requires compatible clients and constrains multi-key operations to a single slot.

### Why is Redis fast, and what makes it slow?

Redis usually serves data from memory with efficient data structures and serialized command execution that avoids much synchronization overhead. Performance still depends on command complexity, network round trips, payload sizes, and resource contention. Large collections, long scripts, swapping, and persistence-related overhead can cause latency spikes.

## Related concepts

- [Caching strategies](https://sysround.com/concepts/caching-strategies)
- [Database sharding](https://sysround.com/concepts/database-sharding)
- [Database replication](https://sysround.com/concepts/replication)
- [Hot keys and hot partitions](https://sysround.com/concepts/hot-keys)
- [Distributed locks and fencing tokens](https://sysround.com/concepts/distributed-locks)


---
SysRound (https://sysround.com) is an AI practice tool for system design interviews: a voice or typed AI interviewer, a shared whiteboard, then feedback on every skill and a model answer. Its feedback is AI-generated and can be wrong.
