How it works
Clients send commands through persistent TCP connections with the Redis protocol. A main thread executes most commands on a node in sequence. Other threads can handle network tasks and background work, depending on the version and configuration. Thus, individual commands are atomic relative to other clients. But expensive commands and long scripts can delay unrelated requests.
Redis stores keys and values in memory as strings, hashes, lists, sets, sorted sets, and streams. Choose strings for cached objects and counters, hashes for fields, and sorted sets for ranked access. Consider operation complexity. A large range query or collection scan can use substantial CPU and network bandwidth, even with data in memory.
Keys can have expiration times. Redis removes expired keys during access checks and active expiration, so expiration does not provide a precise task scheduler. Separately, maxmemory and an eviction policy control what Redis does when memory is scarce. TTL defines how long data stays valid. Eviction defines what Redis removes 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 form. Snapshots and AOF rewrites commonly use a background child process. Include fork overhead, copy-on-write memory, and disk capacity in capacity plans.
A primary can replicate data to replicas, normally asynchronously. Sentinel monitors non-clustered Redis deployments and coordinates failover. Redis Cluster combines sharding with replica promotion. Clients must support the chosen topology, including discovery, new connections after failures, and Cluster redirections.
What it gives you in a design
- Cache-aside storage
- Applications can read Redis first and copy data from a database into Redis after a cache miss. Define invalidation, TTLs, and behavior after a cache miss explicitly. Redis does not automatically keep cached values consistent 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. A retry of a non-idempotent increment without a result check can apply it twice.
- Server-side atomic logic
- Lua scripts and Redis Functions can combine checks and updates without commands from other clients between them. Limit execution time. Atomic execution does not roll back changes after a runtime error.
- Transactions and optimistic concurrency
- MULTI/EXEC executes queued commands without commands from other clients between them. WATCH permits an optimistic retry when watched keys change. Redis transactions do not provide SQL-style rollback. Cluster multi-key operations generally require keys in the same hash slot.
- Rankings and compact summaries
- Sorted sets support leaderboards and collections indexed by time. HyperLogLog supports approximate distinct counts. Before you choose a structure, state whether the design needs exact membership, exact counts, or only an estimate.
- Pub/Sub and Streams
- Pub/Sub broadcasts to connected subscribers without persistence or replay. Streams retain entries and support consumer groups that track pending entries. Applications still need retention rules, recovery of abandoned work, and idempotent execution.
- Pipelining
- Pipelining sends multiple commands without a wait for each response, which reduces network round trips. It does not make the commands atomic. Large batches increase buffer use and can increase latency for other clients.
Scaling, replication and failure
Redis Cluster maps keys to 16,384 hash slots across primaries. Clients use the slot map to route requests 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 too many keys together can overload a shard.
More shards distribute keys and memory demand, but one primary still owns each hot key. For hot reads, use application-local caches, request coalescing, or replica reads where stale results are acceptable. A hot counter split across keys distributes writes but makes exact reads and global admission checks harder.
Replication is asynchronous by default, so a promoted replica can lack acknowledged writes. WAIT can request replica acknowledgments and reduce this risk. But WAIT does not make Redis a strongly consistent store that uses consensus. Replica reads can also lag behind the primary.
Cluster failover depends on failure detection, eligible replicas, and authorization from a majority of primaries. Network partitions can interrupt service and cause loss of recent writes. Plan spare memory for replication buffers, persistence, resharding, and copy-on-write overhead. At the application boundary, use timeouts, limited retries, and a planned fallback. These measures prevent a Redis outage from overwhelming the source database.
Limits and defaults to know
Many of these values are configurable. Check the current documentation before you use an exact value.
| Cluster partition count | Redis Cluster uses exactly 16,384 hash slots. Redis assigns slots to primaries. Slots are not equivalent to nodes. |
|---|---|
| String value size | Redis limits a string value 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, which means no configured dataset memory limit. The default eviction policy is noeviction. Managed services may supply different settings. |
| Expiration precision | You can specify expiration in milliseconds, but Redis physically deletes keys through access checks and active expiration. Redis does not guarantee expiration notifications 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. Storage or operating system problems can cause greater loss. |
| 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
- A cache with size limits can serve repeated reads. The design can tolerate stale data or explicitly control it.
- A rate limiter or admission controller needs short, atomic operations on state for each user or account.
- Ranked sets, counters, temporary presence, or sessions that expire fit Redis data structures better than repeated database queries.
- The active dataset fits a realistic memory budget that includes object overhead, replicas, and spare capacity for operations.
- Temporary live notifications or retained streams are useful. Their delivery and recovery requirements match the chosen Redis mechanism.
Avoid it when
- The design cannot accept loss of even an acknowledged write, as with a financial ledger or authoritative allocation of scarce inventory.
- The dataset is large and rarely accessed. Disk storage costs less than replicated memory.
- The workload needs joins, arbitrary analytical queries, or general transactions across records with independent sharding.
- A durable event backbone needs long retention and large replay workloads. A dedicated distributed log provides more economical storage.
What interviewers ask about it
When Redis is on your whiteboard, expect these follow-up questions. Each answer gives the core of a strong answer.
- What happens when Redis is unavailable?
- For a cache, use the database only within its capacity. Use 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 security and availability requirements. Do not treat 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. Describe a specific update path, such as committing the database write before you invalidate the cache. Concurrent readers can still fill the cache with stale data. Use bounded TTLs, versions, or an ordered change stream when you need stronger freshness.
- How would you implement an atomic distributed rate limit?
- Use a bounded script for one atomic operation: read bucket state, decide admission, update state, and set expiration. In Cluster, keep that bucket's keys in one slot. Explain how you handle clocks, 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 stopped work after a pause or partition. Release it only after an atomic check of a unique ownership token. Use fencing that the protected resource enforces when stale holders could cause damage. Asynchronous failover can also permit holders with overlapping leases.
- How do you handle a hot key or cache stampede?
- For hot reads, consider a local cache with a short lifetime and request coalescing. For synchronized expiration, add TTL jitter and refresh popular values before they expire. Sharding alone does not split the load for a single key. Use stale-while-revalidate only when you can accept stale data.
- How do you size and monitor Redis?
- Estimate key count, serialized value size, per-key overhead, data-structure overhead, replication, and extra capacity for persistence, not just payload bytes. Track command latency, memory, fragmentation, evictions, hit rate, replication lag, client buffers, and slow commands. Use these measures to distinguish capacity problems from hot keys or expensive operations.
Common mistakes
- You call Redis single-threaded and conclude that every command is cheap. You ignore command complexity, large replies, scripts, and background work.
- You equate atomic execution with durable, exactly-once effects. Or you assume a successful primary response guarantees that writes survive failover.
- You mix disposable cache entries with coordination state critical to correctness. The eviction policy can remove either.
- You use KEYS or collection reads without limits in request paths. Or you assume SCAN provides a consistent snapshot without duplicates during changes.
Alternatives
- Memcached
- Choose it for a simple disposable object cache without Redis data structures, persistence, or server-side atomic logic.
- PostgreSQL
- Choose it when constraints, durable transactions, and authoritative state matter more than direct memory access to the active dataset.
- etcd
- Choose it for small coordination metadata that needs consistency through consensus, 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. Redis Pub/Sub does not provide durable messages.
Where it is used
Redis is a good fit for these interview questions. Each line tells you why.
- Design a distributed cacheRedis provides a concrete basis to discuss partition ownership, eviction, expiration, hot keys, and replica failover.
- Design a distributed rate limiterAtomic scripts and state that expires support distributed rate-limit algorithms, with explicit trade-offs for outages and failover.
- Design a URL shortener like BitlyRedis can cache popular short-code mappings while the durable database stays authoritative.
- Design a news feed like FacebookRedis can hold feed ID lists with size limits and cached post data. Durable storage supports reconstruction after eviction or failure.
- Design a top K trending systemSorted sets support ranked access. But window expiration, duplicate events, and cross-shard aggregation still need explicit designs.
- Design Netflix's concurrent screen limitAtomic lease admission and expiration fit Redis operations. But strict account-wide limits require solutions for stale holders and write loss during failover.
Common questions
Is Redis a cache or a database?
Redis can serve either role because it stores structured data and offers persistence. You can usually rebuild a cache from another source. A database owns authoritative state. If Redis owns the data, explicitly evaluate persistence settings, eviction, backups, and loss of acknowledged writes during failover.
What is the difference between Redis Cluster and Sentinel?
Sentinel monitors primary-replica deployments, detects 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 limits 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. It executes commands in sequence to avoid much synchronization overhead. Performance still depends on command complexity, network round trips, payload sizes, and resource contention. Large collections, long scripts, swapping, and persistence overhead can cause latency spikes.