Skip to content

Redis in Practice

Intermediate 53 min read Part 15 of 18

Redis in practice: the single-threaded event loop, data structures, cache, locks, rate limits, queues, persistence, Sentinel, Cluster, big and hot keys.

Summary#

Redis is an in-memory data structure server. Keys are strings. Values are strings, hashes, lists, sets, sorted sets, streams, geospatial indexes, HyperLogLogs, bitmaps and more. Commands run one at a time on a single thread, so each one is atomic, and needs no locks. With everything in RAM, a single node serves on the order of 100,000 operations per second at sub-millisecond latency, and far more with pipelining. That speed and those structures make Redis the Swiss Army knife of system design: caches, sessions, rate limiters, leaderboards, distributed locks, queues, pub/sub and proximity search. The catch: it's memory-bound, replication is asynchronous, and persistence has loss windows. So Redis is rarely the system of record, and key design (big keys, hot keys, hash slots) determines whether it scales.

Why It Exists#

Salvatore Sanfilippo ("antirez") wrote Redis in 2009 to make a real-time web analytics product fast. A relational database couldn't keep up with the write rate of page-view events, and he needed lists and counters updated thousands of times per second. Instead of a cache of opaque blobs, like Memcached, he built a server whose values are data structures with server-side operations:

  • push onto a list;
  • increment a counter;
  • add a member to a sorted set with a score;
  • intersect two sets.

Moving the operation to the data, in memory, removed round trips and race conditions at the same time.

That design answers a recurring problem in system design. Many features need tiny, extremely frequent, simple operations on shared state: "increment this user's request count", "who are the top 10 players?", "is this seat held?", "give me the session for this token", "which drivers are within 3 km?". Doing these against a disk-based database works at small scale, but they become the bottleneck at thousands of operations per second per key. Redis gives microsecond execution, atomic commands, and structures that match these jobs directly.

Redis is also simple to reason about. There's no query planner and no optimiser. Each command has a documented time complexity (O(1) for GET, O(log N) for ZADD, O(N) for SMEMBERS), so you can predict its cost. That simplicity is why it's so useful in interviews: once you know a few structures and the scaling rules, you can go deep without obscure internals.

The project's governance has changed over the years. Redis Ltd. (formerly Redis Labs) moved new releases from the BSD licence to source-available licences in March 2024. In response, the Linux Foundation launched Valkey, a fork of Redis 7.2.4, backed by several cloud providers. Redis 8 (2025) added the open-source AGPLv3 as a licensing option. For design purposes, Redis, Valkey and managed services such as Amazon ElastiCache and MemoryDB, Google Memorystore and Azure's Redis offerings share the same core model and commands.

How It Works#

The single-threaded event loop, and why Redis is fast#

Redis runs an event loop, built on the operating system's I/O multiplexing (epoll on Linux, kqueue on BSD and macOS):

  1. The loop asks the kernel which of thousands of client sockets have data ready.
  2. It reads the bytes, and parses commands in RESP (the Redis Serialisation Protocol), a simple text-like format. You can type SET foo 1 by hand, and that's essentially what travels on the wire.
  3. It executes each command against in-memory structures, one command at a time.
  4. It writes replies into output buffers, which are flushed to sockets when writable.
  5. Between iterations, it runs timers: active key expiry, replication housekeeping, and stats.

Why does a single thread go so fast?

  • Memory, not disk. A hash lookup in RAM takes tens to hundreds of nanoseconds. Even with protocol parsing and syscalls, a simple command costs about a microsecond of CPU. The network round trip, about 100–500 µs in the same data centre, dominates what the client sees.
  • No locks, no contention, no context switches between worker threads. Each command runs to completion, so it's atomic by construction. INCR can't interleave with another INCR.
  • Non-blocking I/O multiplexing lets one thread serve tens of thousands of connections.
  • Compact, purpose-built encodings (listpacks, intsets, skiplists) keep data cache-friendly (more below).
  • Pipelining and batching. A client can send 100 commands without waiting for replies, and pay one round trip. MGET and MSET fetch or write many keys at once. With pipelining, one node can exceed 1 million simple operations per second.

The canonical planning number is about 100,000 operations per second per node, for typical commands without heavy pipelining (Numbers to Know). With that, even the N+1 query pattern, which ruins a SQL database, is merely wasteful against Redis, and pipelining or MGET mostly fixes it.

"Single-threaded" needs nuance:

  • Background threads do slow housekeeping: closing files, AOF fsync, and lazy freeing of big values (UNLINK, FLUSHALL ASYNC).
  • I/O threads (since Redis 6) can parallelise socket reads, writes and protocol parsing, while command execution stays on the main thread. That raises throughput on many-core machines with many connections.
  • Forked child processes write RDB snapshots and rewrite the AOF, using copy-on-write memory, so the main thread keeps serving.

The mental model remains: one command at a time, in order. Which means a single slow command, such as KEYS *, HGETALL on a 2-million-field hash, a long Lua script, or DEL on a huge set, blocks every other client until it finishes.

Data structures: the core of Redis#

Every key maps to one value of one type. Choose the type by the operations you need:

TypeWhat it isKey commands (complexity)Typical uses
StringBinary-safe bytes up to 512 MB; also integers and floatsGET, SET with NX, EX or PX, INCR, INCRBY, APPEND, GETRANGE — O(1) mostlyCache entries, counters, locks, serialised JSON, flags
HashField-to-value map under one keyHSET, HGET, HINCRBY, HMGET O(1) per field; HGETALL O(N)Objects (user profile, session), small maps, per-field counters
ListOrdered sequence (quicklist of listpacks)LPUSH, RPUSH, LPOP, RPOP O(1); BLPOP, BLMOVE blocking; LRANGE O(S+N)Queues, recent-items lists, activity timelines
SetUnordered unique membersSADD, SREM, SISMEMBER O(1); SCARD; SINTER and SUNION O(N)Tags, unique visitors (small), friends, online users
Sorted set (ZSET)Unique members, each with a float score, kept orderedZADD, ZINCRBY, ZRANK O(log N); ZRANGE O(log N + M); ZRANGEBYSCORE, ZREMRANGEBYRANKLeaderboards, priority queues, sliding-window rate limits, time-indexed sets, top-k
StreamAppend-only log of entries with IDs (ms-seq), consumer groupsXADD, XRANGE, XREADGROUP, XACK, XAUTOCLAIM, XTRIMEvent logs, durable-ish work queues, activity feeds
GeospatialSorted set whose scores are 52-bit geohashesGEOADD, GEOSEARCH, GEODISTNearby drivers, stores, friends
HyperLogLogProbabilistic distinct counter, at most 12 KB, about 0.81% standard errorPFADD, PFCOUNT, PFMERGEUnique visitors, unique searches at huge scale
Bitmap and bitfieldBit operations on stringsSETBIT, GETBIT, BITCOUNT, BITOP, BITFIELDDaily active flags per user ID, feature bitsets, compact counters
Pub/Sub channelsFire-and-forget messaging (not a stored type)PUBLISH, SUBSCRIBE, SPUBLISH, SSUBSCRIBEReal-time fan-out to connected servers

Redis 8 also bundles, in its core distribution, what used to be separate Redis Stack modules: JSON documents with path updates, time series, probabilistic structures (Bloom and cuckoo filters, count-min sketch, top-k, t-digest), and a query engine for secondary indexing and vector search. Redis 7.4 added per-field expiry on hashes (HEXPIRE), long requested for sessions and caches stored as hashes. See Probabilistic Data Structures for the maths behind HyperLogLog, Bloom filters and count-min sketch.

Key naming is data modelling. Keys are usually namespaced with colons: user:123, session:abc, leaderboard:game:42, rate:user:123:202612021530. In a cluster, the key determines which node stores the value, so the way you name keys is the way you shard your data. That's covered in the Cluster section below.

Data structures, in depth: encodings, memory and complexity traps#

Dual encodings. Redis stores small collections in compact, contiguous encodings, and converts them to pointer-based structures past configurable thresholds:

  • Hashes and sorted sets stay as a listpack (a single contiguous byte array) up to 128 entries, with values up to 64 bytes by default (hash-max-listpack-entries and -value, zset-max-listpack-entries and -value). Beyond that, a hash becomes a real hash table, and a sorted set becomes a skiplist plus a hash table. The hash table gives O(1) score lookup by member. The skiplist gives O(log N) rank and range operations.
  • Sets of small integers use an intset, a sorted integer array. Small sets of strings use a listpack (since 7.2). Larger sets use a hash table.
  • Lists are a quicklist: a doubly linked list of listpack nodes. That balances memory with O(1) pushes and pops at both ends.
  • Strings: integers are stored as integers. Short strings (up to 44 bytes) are embedded in the object header in one allocation ("embstr"). Longer ones use SDS (simple dynamic strings) buffers.

Compact encodings use several times less memory, at the cost of O(N) scans within the small object, which is trivial for N up to 128. Instagram described in 2011 how bucketing about 300 million photo-to-user mappings into hashes of about 1,000 fields each (so they stayed in the compact encoding) cut memory from roughly 21 GB to about 5 GB. That's a classic Redis memory optimisation.

Per-key overhead. Each top-level key costs a dictionary entry, an object header, the key string and allocator overhead: typically tens of bytes, plus the payload. With 100 million tiny keys, overhead alone can be 5–10 GB. Grouping small values into hashes, using shorter key names, and avoiding a separate key per tiny fact all reduce it. Measure with MEMORY USAGE key and INFO memory (watch used_memory, used_memory_rss and mem_fragmentation_ratio).

Skiplists, briefly. A skiplist is a linked list with probabilistic "express lanes". Each node is promoted to the next level with probability 1/4 in Redis, giving expected O(log N) search, insert and delete, plus easy range traversal. William Pugh introduced skiplists in "Skip Lists: A Probabilistic Alternative to Balanced Trees" (CACM 1990). Redis's variant stores a span per forward pointer, so it can compute a member's rank in O(log N): exactly what ZRANK and leaderboards need.

Complexity traps. Commands whose cost grows with collection size block the single thread:

  • KEYS pattern scans the whole keyspace. Never use it in production. Use SCAN cursors, which iterate incrementally.
  • HGETALL, SMEMBERS, LRANGE 0 -1 and ZRANGE 0 -1 on large collections. Use HSCAN, SSCAN, ZSCAN, or paginated ranges.
  • SINTER, SUNION and SDIFF across large sets, and SORT.
  • DEL of a large collection frees memory synchronously. Use UNLINK, which frees in a background thread, or enable lazyfree-lazy-user-del.
  • Long Lua scripts or functions. The whole script is one atomic command, and nothing else runs meanwhile.

Find offenders with SLOWLOG GET (commands slower than a threshold, 10 ms by default) and LATENCY DOCTOR.

Expiry mechanics. A key with a TTL (EXPIRE, SET ... EX) is removed in two ways:

  • lazily, when accessed after expiry. A client never sees an expired value;
  • actively, by a periodic job that samples keys with TTLs and deletes expired ones, repeating while a large fraction of the sample has expired.

So expired-but-untouched keys may hold memory briefly, but never return data. On replicas, expiry is driven by the primary, which sends explicit deletions, so the dataset stays consistent.

The data model: designing a keyspace#

Redis has no schema. The "data model" is your key naming scheme plus the type behind each key. Here's a realistic keyspace for a ticketing and social app, showing each entity's key pattern, type and expiry:

EntityKey patternTypeExpiry and boundsAccess
User sessionsession:{token}Hash (user_id, csrf, created_at)Sliding TTL 30 minHGETALL per request, EXPIRE refresh
Rate windowrate:{user}:{minute}String counterTTL 60 sINCR in Lua
Profile cachecache:v3:user:{id}String (JSON)TTL 10 min with jitterGET, SET EX, DEL on write
Seat holdhold:{event}:{seat}String (holder token)NX EX 600SET NX, Lua compare-and-delete
Leaderboardlb:{event}Sorted set (member to points)Trimmed or TTL per periodZINCRBY, ZREVRANGE, ZREVRANK
Presenceonline:{event}Set of user IDs, or sorted set by last-seenPrune members older than 60 sSADD, SREM, SCARD
Driver positionsdrivers:geo:{city}Geo (sorted set of geohashes)Pruned by last-seen sorted setGEOADD, GEOSEARCH
Job queuejobs:{queue}Stream with consumer groupXTRIM MAXLEN ~ 1000000XADD, XREADGROUP, XACK

Design rules that follow:

  1. One key per access unit. Store what you fetch together under one key: a hash for an object, a sorted set for a ranking. Fetching 50 tiny keys for one page view is 50 lookups. Pipelining helps, but one HGETALL of a small hash is simpler.
  2. Embed the shard decision in the key. In a cluster, {event:42} in braces forces related keys onto the same node (see hash tags).
  3. Give everything an expiry plan. Caches, sessions, holds and windows all carry TTLs. Anything without a TTL needs an explicit deletion path, or memory grows forever.
  4. Bound collections. Cap lists with LTRIM, streams with XTRIM MAXLEN ~ 1000000, and sorted sets with ZREMRANGEBYRANK. An unbounded collection eventually becomes a big key.
  5. Version cached formats. For example cache:v3:user:123, so a deploy that changes serialisation doesn't read stale shapes.

Use case 1: cache#

The most common job is a cache-aside layer in front of a database or a slow service (Caching Strategies). The app checks Redis. On a miss, it reads the database, then writes the value back with a TTL:

GET cache:user:123            -> nil (miss)
... query Postgres ...
SET cache:user:123 "<json>" EX 600

The numbers explain why. RAM is roughly 100 ns per access, an SSD read about 100 µs, and a spinning-disk seek about 10 ms. A database query that touches disk, plans and locks costs about 1–10 ms or more, while a Redis GET across the network costs about 0.5–1 ms end to end. Redis serves on the order of 100k reads per second per node, more with replicas. A URL shortener's redirect path is the textbook case: hot short codes stay in memory, so a cache hit rate of 90–99% keeps the database out of the read path.

Practical rules:

  • Key construction. Build the key from all the inputs that change the result. Caching a ticketing search means a key like search:v1:{hash(query, city, date, page, sort)}. Forget the page number and every page returns page 1.
  • TTL as a staleness bound. A 60-second TTL on search results means at most 60 seconds of staleness. Pair it with explicit deletion on writes when freshness matters (delete cache:user:123 after updating the user row). Add jitter to TTLs, for example 600 ± 60 s, so keys written together don't expire together.
  • Eviction policy. When maxmemory is reached, Redis applies maxmemory-policy. The default noeviction rejects writes with an error (OOM). For a pure cache, set allkeys-lru or allkeys-lfu. For a mixed workload where only keys with TTLs are disposable, use volatile-lru or volatile-ttl. Redis approximates LRU by sampling (maxmemory-samples, 5 by default) and evicting the best candidate from a small pool. That's far cheaper than a true LRU list and close enough in practice. LFU uses a logarithmic 8-bit access counter that decays over time. See Cache Eviction and Invalidation.
  • Stampede protection. When a hot key expires, thousands of requests may miss at once and hammer the database. Mitigate with a short lock (SET rebuild:key token NX EX 5) so one caller rebuilds, serve stale data while refreshing, or refresh early with probability (XFetch). See Cache Failure Modes.

Client-side caching (Redis 6+ "tracking") lets the client keep a local copy of hot keys in process memory. The server remembers what each client has read and sends invalidation messages when those keys change. That turns a 0.5 ms network read into a roughly 100 ns local read, and absorbs hot keys. It's covered in more detail under hot keys.

Use case 2: sessions and ephemeral state#

Store web sessions as session:{token} hashes with a sliding TTL: refresh EXPIRE on each request, so idle sessions vanish after 30 minutes. Any app server can serve any user (stateless servers), and logout is just DEL. Shopping carts, OTP codes (otp:{phone} with EX 300 and an attempts counter), "user is typing" flags and short-lived feature data fit the same pattern.

The durability question decides the setup. Losing sessions on a crash logs users out. That's annoying but recoverable, so AOF with everysec plus a replica is usually enough. Losing a cart may lose revenue, so some teams keep carts in a database and cache them in Redis.

Use case 3: rate limiting#

A rate limiter needs a shared, atomic counter per client per window, which Redis does in a single command. A fixed window limiter:

  1. Builds a key such as rate:{user}:{epochMinute}.
  2. Runs INCR.
  3. If the result is 1 (the first request in this window), sets EXPIRE to the window length.
  4. If the count exceeds the limit, returns HTTP 429 Too Many Requests with a Retry-After header.

The INCR and EXPIRE pair must be atomic. If the process crashes between them, a key without a TTL lives forever and blocks that user permanently. So wrap them in a Lua script, which Redis runs atomically as one command:

-- KEYS[1] = rate key (e.g. rate:{user:42}:202612021530)
-- ARGV[1] = limit, ARGV[2] = window seconds
local count = redis.call('INCR', KEYS[1])
if count == 1 then
  redis.call('EXPIRE', KEYS[1], tonumber(ARGV[2]))
end
if count > tonumber(ARGV[1]) then
  return {0, redis.call('TTL', KEYS[1])}  -- denied, retry-after seconds
end
return {1, tonumber(ARGV[1]) - count}     -- allowed, remaining

Fixed windows allow bursts of up to twice the limit at window boundaries: 100 requests at 12:00:59 and 100 more at 12:01:00. A sliding log fixes that with a sorted set per client, where each member is a request ID scored by its timestamp:

  1. ZREMRANGEBYSCORE key 0 (now - window) drops old entries.
  2. ZCARD key counts the rest.
  3. If under the limit, ZADD key now reqId and PEXPIRE key window.

All of this runs inside one Lua script. The sliding log is exact, but costs memory per request. A sliding window counter (two fixed-window counters, weighted by overlap) or a token bucket (a hash holding tokens and last_refill, updated in Lua) gives smooth limits with O(1) memory. The algorithms are compared in Rate Limiting, and a full design is in Design a Rate Limiter.

At scale, one Redis node handles about 100k checks per second. Cluster the limiter by client key, so each client's counters live on one shard. The limiter adds about 0.5–1 ms to each request. Decide whether to fail open (allow traffic if Redis is down) or fail closed. Most public APIs fail open, protecting availability over strictness.

Use case 4: leaderboards and rankings#

A sorted set is a ready-made leaderboard:

  • ZADD lb:game:42 1500 player:7 sets a score. ZINCRBY lb:game:42 25 player:7 adds points.
  • ZREVRANGE lb:game:42 0 9 WITHSCORES returns the top 10 in O(log N + 10).
  • ZREVRANK lb:game:42 player:7 returns a player's rank in O(log N), even with 50 million members.
  • ZREVRANGE around that rank gives "players near me".

With 10 million players, each sorted-set entry costs roughly 60–100 bytes (skiplist node, hash entry, member string), so about 1 GB of RAM. Comfortable on one node.

Bounded top-k. When you only need the top few, trim after each insert. For "top 5 posts by likes for this keyword", run ZADD top:keyword:redis 812 post:99 and then ZREMRANGEBYRANK top:keyword:redis 0 -6. That removes everything except the five highest scores (ranks are ascending, so 0 to -6 means "all but the last five"), and memory stays constant per keyword. A post-search design can use this so that "most-liked results for a keyword" is a single read. Time-windowed leaderboards (daily or weekly) use one key per period, such as lb:2026-12-02, with a TTL, and ZUNIONSTORE to combine periods. See Top-K for heavy-hitter variants at internet scale.

Ties sort lexicographically by member. To break ties by "who got there first", encode the time in the score, for example score = points * 1e10 + (MAX_TS - ts), staying within the 53-bit integer precision of a double.

Use case 5: distributed locks#

The simplest lock is a key that only one client can create:

SET lock:concert:343:seat:A12 <random-token> NX EX 30
  • NX means "only if the key doesn't exist", so exactly one caller succeeds.
  • EX 30 is a lease, so a crashed holder can't block forever.
  • The random token identifies the owner. Releasing must check that you still own the lock, because after 30 seconds it may have expired and been taken by someone else. That check-and-delete must be atomic, so it's a Lua script:
if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("DEL", KEYS[1])
else
  return 0
end

This is the pessimistic approach: grab the lock before touching the resource. Redis also supports optimistic concurrency with WATCH key, then MULTI ... EXEC. If the watched key changes before EXEC, the transaction aborts and you retry. That suits low-contention updates where you don't want to hold a lock.

Two hard truths about Redis locks:

  1. Failover can grant the lock twice. Replication is asynchronous. Client A acquires the lock on the primary, the primary crashes before replicating it, and a replica is promoted without the key. Client B acquires the "same" lock. Now both believe they hold it.
  2. Leases can't protect against pauses. If client A stalls for 40 seconds (a GC pause, a VM freeze, network delay) after acquiring a 30-second lock, the lock expires and B takes it. Then A wakes up and writes, with no idea anything happened.

Redlock (antirez's algorithm) acquires the lock on a majority of N independent primaries (for example 3 of 5) within a time bound, to survive the failover problem. Martin Kleppmann's 2016 essay "How to do distributed locking" argued that Redlock still depends on timing assumptions (bounded clock drift, pauses and network delay), so it's unsafe for correctness. The fix for both problems is a fencing token: a monotonically increasing number issued with each lock grant, which the storage system checks, rejecting writes with an older token. Redis alone doesn't give you fencing at the storage layer.

The practical guidance:

  • Use Redis locks for efficiency, such as preventing duplicate expensive work, or stampede control. An occasional double execution is tolerable there.
  • For correctness, such as "never double-sell a seat", enforce the invariant in the database of record: SELECT ... FOR UPDATE, a conditional UPDATE seats SET status='held' WHERE id=? AND status='free', a unique constraint, or a consensus-based lock service (ZooKeeper or etcd) whose fencing tokens the storage system checks.
  • A Redis hold with a TTL is still a great user-facing reservation (the ten-minute seat hold in a ticketing flow), as long as the final purchase is checked transactionally.

The deep dive below goes through Redlock's steps and the critique in detail. See also Distributed Locking.

Use case 6: queues and streams#

Lists as simple queues. Producers LPUSH jobs. Workers BRPOP jobs 5 (block up to 5 seconds). That's O(1) and very fast, but a job popped by a worker that then crashes is lost. The reliable-queue pattern uses BLMOVE jobs processing:{worker} RIGHT LEFT, so the job atomically moves to a per-worker in-flight list, is removed after success, and is recovered by a reaper if the worker dies. Libraries such as Sidekiq (Ruby), BullMQ (Node) and Celery (Python, with a Redis broker) build retries, delays (sorted sets scored by run-at time) and priorities on these primitives.

Streams (Redis 5+) are an append-only log with consumer groups, closer to a mini Kafka:

  • XADD jobs * type email to 42 appends an entry, with an auto ID such as 1733130000000-0 (milliseconds and a sequence).
  • XREADGROUP GROUP workers w1 COUNT 10 BLOCK 5000 STREAMS jobs > delivers new entries to consumer w1. Each entry goes to one consumer in the group, and is recorded in the group's Pending Entries List (PEL) until acknowledged.
  • XACK jobs workers <id> marks it done.
  • If a worker dies, its entries stay pending. XPENDING shows them with idle time. Another worker takes over entries idle beyond a threshold with XCLAIM, or XAUTOCLAIM jobs workers w2 60000 0, which claims entries idle for over 60 seconds.
  • XTRIM jobs MAXLEN ~ 1000000 caps the length. The ~ allows efficient approximate trimming.

That gives at-least-once delivery. A message can be processed twice (worker finishes, crashes before XACK, and the entry is reclaimed), so handlers must be idempotent (Idempotency). Streams also inherit Redis durability: with AOF everysec and async replication, a crash or failover can lose recent entries.

Redis Streams vs Kafka. Use Streams when you already run Redis, the volume fits in memory (for example a few GB of backlog), retention is short, and you want simple work distribution. Pick Kafka when you need disk-based retention for days or weeks, replay by many independent consumers, throughput of hundreds of MB/s per broker, and stronger durability (replicated, acks=all). For workflow-style jobs with retries and timers, see Long-Running Tasks.

Use case 7: pub/sub for real-time fan-out#

SUBSCRIBE chat:room:9 on one connection, PUBLISH chat:room:9 "hello" from anywhere, and every currently connected subscriber gets the message. Channels exist implicitly. There's nothing to create, and a channel with no subscribers costs nothing. Pub/Sub is at-most-once: messages aren't stored. A subscriber that's disconnected, slow or not yet subscribed simply misses them. A slow subscriber whose output buffer grows past client-output-buffer-limit pubsub is disconnected.

A typical use is routing between WebSocket servers. User A is connected to gateway 3 and user B to gateway 7. Each gateway subscribes to channels for its connected users or rooms. When A sends a message, the service publishes to user:B, and gateway 7, which subscribed when B connected, pushes it down B's socket. One Redis connection per gateway carries all its subscriptions. You don't need one connection per channel.

Sharded pub/sub (Redis 7+). In classic cluster pub/sub, every PUBLISH is broadcast to every node in the cluster, so throughput doesn't scale with node count. SPUBLISH and SSUBSCRIBE route a channel to the shard that owns its hash slot, like a key, so capacity grows with the cluster. A gateway then keeps one connection per Redis node (not per channel), and subscribes to each channel on the node that owns it.

Why not let services connect to each other directly ("roll your own pub/sub")? Direct delivery is one network hop fewer: A's server sends straight to B's server, instead of going through Redis (two hops instead of three). But you then need:

  • a registry of which server holds which user, kept consistent as connections move;
  • a connection mesh between all servers, which is N² connections;
  • heartbeats and reconnection logic;
  • per-server buffering.

Redis concentrates all that complexity in one well-understood component. It's usually the right trade until the scale is very large.

Durability pairing. Because pub/sub drops messages for offline users, real systems pair it with something durable:

  • write the chat message to a database (or Kafka, or a stream) first, for history and offline delivery;
  • then publish to Redis for low-latency delivery to whoever is online.

Clients that reconnect fetch what they missed from the durable store. This is the core of Real-time Updates, Design a Chat System and Live Comments. The transactional outbox (Change Data Capture) helps keep "store" and "notify" in step.

Use case 8: geospatial proximity#

GEOADD drivers:geo:sf -122.4194 37.7749 driver:42 stores a member with a longitude and latitude. Internally, the coordinates become a 52-bit interleaved geohash used as the score in a sorted set. GEOSEARCH drivers:geo:sf FROMLONLAT -122.41 37.77 BYRADIUS 3 km ASC COUNT 20 WITHDIST finds the nearest 20 drivers.

The algorithm:

  1. Picks a geohash precision whose cell size covers the radius.
  2. Computes the centre cell and its 8 neighbours.
  3. Runs a sorted-set range scan for each cell, since geohash prefixes are contiguous score ranges.
  4. Filters candidates by exact distance (a second pass), because cells are squares and the query is a circle.

The cost is about O(N + log M), where N is the number of elements in the scanned cells and M the set size.

A ride-hailing system updating driver locations every 4 seconds with 500,000 active drivers generates about 125k GEOADDs per second. Spread that across a cluster by city or region key (drivers:geo:{city}). Expire stale drivers with a parallel sorted set of last-seen times, because members of a geo set can't carry a TTL. See Geospatial Indexing, Design a Proximity Service and Design a Ride-Hailing Service.

Use case 9: counting, presence and analytics#

  • Counters: INCR for likes or views, HINCRBY post:99 likes 1 for per-field counters. Flush to the database periodically (write-behind) so the database sees one write per batch instead of one per like (Scaling Writes).
  • Unique counts: PFADD uv:2026-12-02 user:42, then PFCOUNT uv:2026-12-02. That's a HyperLogLog, costing 12 KB regardless of cardinality, with about 0.81% standard error. PFMERGE combines days into weeks.
  • Daily active bitmaps: SETBIT dau:2026-12-02 <userId> 1 uses 1 bit per user ID, so 100 million users take 12.5 MB per day. BITCOUNT gives DAU, and BITOP AND across days gives retention cohorts.
  • Presence: a key per user online:{user} with EX 60, refreshed by heartbeats. Or a sorted set scored by last-seen time, cleared with ZREMRANGEBYSCORE for anyone older than 60 seconds.

Persistence: RDB snapshots and the AOF#

Redis keeps the dataset in memory, but it can persist to disk in two ways (or both):

RDB snapshots. BGSAVE, or a save 3600 1 300 100 60 10000 schedule, forks the process. The child walks the dataset and writes a compact binary dump.rdb, while the parent keeps serving. Snapshots are small, quick to load on restart, and ideal for backups (copy the file to object storage hourly). But anything written after the last snapshot is lost on a crash. With hourly snapshots, that's up to an hour of data.

AOF (append-only file). Every write command is appended to a log, and on restart Redis replays it. The appendfsync setting decides how often the log is forced to disk:

appendfsyncBehaviourData at risk on crashCost
alwaysfsync after every write batchAlmost none (the last batch)Throughput limited by disk sync latency; rarely used
everysec (default)Background fsync once per secondAbout 1 s of writes (up to about 2 s if the disk stalls)Small; the usual choice
noLet the OS flush (typically every 30 s on Linux)Up to about 30 sLowest

The AOF grows forever, so Redis periodically rewrites it. A forked child writes the minimal command set that recreates the current dataset (one SET per key, instead of a thousand INCRs). Since Redis 7, the AOF is multi-part: a base file (RDB or AOF format), plus incremental files, tracked by a manifest. That made rewrites cheaper and safer than the old single-file approach, which buffered new writes in memory during the rewrite. With aof-use-rdb-preamble yes (the default), the base is in RDB format, so restarts load quickly and then replay only the recent tail.

What to choose:

  • Pure cache: often no persistence at all, or just RDB for faster warm restarts. Losing the cache costs a cold start, not data.
  • Sessions, rate-limit state, leaderboards that can be rebuilt: AOF everysec plus RDB backups, plus a replica.
  • Data that must not be lost: don't trust a single Redis. Use a database as the source of truth. Or use a Redis-compatible service with a durable design, such as Amazon MemoryDB, which commits writes to a multi-AZ transaction log before acknowledging them. The cost is single-digit-millisecond write latency instead of sub-millisecond.

Persistence, in depth: fork, copy-on-write and big-key pain#

fork() doesn't copy memory up front. Parent and child share physical pages, marked copy-on-write (COW). When the parent modifies a page during the snapshot, the kernel copies that 4 KB page first. That has three consequences:

  1. The fork itself costs time proportional to the page tables. For a 25 GB dataset with 4 KB pages, the page tables are about 50 MB, so the fork can block the main thread for tens of milliseconds. On some virtualised hosts with slow forks, it has historically been worse. Watch latest_fork_usec in INFO stats. This is one reason teams prefer more, smaller instances (for example 10–25 GB each) to one 200 GB instance.
  2. Memory can approach double during a snapshot under heavy writes. If the write workload touches most pages during the snapshot, almost every page gets copied. So budget headroom: never set maxmemory near physical RAM on a persisting instance. Typical guidance leaves 25–50% free for COW, replication buffers and fragmentation.
  3. Transparent Huge Pages (THP) amplify COW. One small write copies 2 MB instead of 4 KB. Redis logs a warning at startup if THP is enabled, and the standard advice is echo never > /sys/kernel/mm/transparent_hugepage/enabled.

Big keys hurt persistence and replication too. A single 1 GB hash:

  • makes DEL block the thread for a long time while it frees millions of allocations. UNLINK or lazyfree-lazy-* settings move that to a background thread;
  • causes a large burst of COW copying if it's modified during a snapshot, because its pages are scattered across memory;
  • slows AOF rewrites and full syncs;
  • in a cluster, can't be split across nodes, so it pins memory and load to one shard, and makes migrating its slot slow and blocking (MIGRATE of a big key holds the thread on both ends).

Durability and replication interplay. If persistence is off on the primary and it restarts automatically, it comes back empty, and replicas then sync from it and wipe their own data. Either enable persistence on the primary, or disable auto-restart, so Sentinel can promote a replica first. The Redis replication docs specifically warn about this.

Replication, Sentinel and failover#

Replication is primary-replica and asynchronous:

  • A replica connects and sends PSYNC <replid> <offset>.
  • If the primary still has the missing range in its replication backlog (a circular buffer, repl-backlog-size, 1 MB by default; production setups often raise this to hundreds of MB), it sends just the missing commands (partial resync).
  • Otherwise it does a full sync: it forks and creates an RDB, streams it to the replica (or sends it diskless, straight over the socket), and then streams new writes.
  • Replicas acknowledge offsets roughly once a second.

The primary acknowledges the client before replicas have the write. So on failover, writes acknowledged in the last few milliseconds can be lost. WAIT numreplicas timeout blocks until N replicas have acknowledged the write. That reduces the window, but it isn't a true synchronous commit: a failover can still promote a replica that didn't receive it. min-replicas-to-write 1 and min-replicas-max-lag 10 make a primary refuse writes when it's isolated from its replicas, which bounds the loss during a network partition.

Replica reads. Replicas can serve reads (in a cluster, the client must send READONLY on the replica connection), adding read capacity with eventual consistency: a read may miss a write made milliseconds ago. Use them for read-heavy, staleness-tolerant data such as caches, catalogues and leaderboards.

Sentinel provides high availability for a non-cluster deployment (one primary with replicas):

  • A group of Sentinel processes (at least 3, on separate failure domains) monitor the primary.
  • When one Sentinel can't reach it for down-after-milliseconds, it marks it subjectively down.
  • When a quorum of Sentinels agree, the primary is objectively down.
  • The Sentinels then elect a leader among themselves (Raft-like voting with epochs), which picks the best replica (priority, then replication offset, then run ID), promotes it with REPLICAOF NO ONE, and repoints the other replicas.
  • Clients ask Sentinel for the current primary address, so they follow failovers automatically.

Typical failover time is a few seconds to tens of seconds, depending on down-after-milliseconds.

Redis Cluster: hash slots and sharding#

When one node's memory or throughput isn't enough, Redis Cluster shards the keyspace:

  • There are exactly 16,384 hash slots. A key's slot is CRC16(key) mod 16384.
  • Each primary owns a subset of slots (for example, 3 primaries own about 5,461 each). Each primary has one or more replicas for failover.
  • Nodes talk over a cluster bus (port + 10000) using a gossip protocol (ping and pong messages carrying the slot map and node health; see Failure Detection and Gossip).
  • If a majority of primaries flag a node as failing, a replica of the failed primary wins an election among the primaries and takes over its slots. No external Sentinel is needed.

Clients do the routing. Smart clients (Lettuce, Jedis, redis-py cluster, go-redis, ioredis) fetch the slot map with CLUSTER SHARDS (or the older CLUSTER SLOTS), cache it, and send each command straight to the owning node: one hop, no proxy. If the map is stale:

  • MOVED 3999 10.0.0.5:6379 says that slot 3999 now lives elsewhere permanently, so the client updates its map and retries.
  • ASK 3999 10.0.0.5:6379 happens during a slot migration: this one key has already moved, so the client sends ASKING and then the command to the target node, but doesn't update its map yet.

Servers don't proxy for clients and don't fan out queries across nodes.

Multi-key commands must stay in one slot. MGET, SUNIONSTORE, Lua scripts touching several keys, and MULTI/EXEC transactions all fail with CROSSSLOT if their keys hash to different slots. Hash tags fix that: only the substring inside the first {...} is hashed. {user:123}:profile, {user:123}:cart and {user:123}:sessions all land in one slot, so you can update them atomically. The cost: everything sharing a tag is pinned to one node, so tag at the granularity of a user or an entity, never something global like {all}.

Why 16,384 slots? antirez explained it on GitHub. The heartbeat messages carry the slot ownership bitmap, and 16,384 bits is 2 KB, small enough to gossip frequently. Clusters were expected to stay below about 1,000 primaries, so that's still plenty of slots per node for balanced resharding.

Resharding moves slots between nodes. You mark the slot MIGRATING on the source and IMPORTING on the target, then MIGRATE keys in batches. During that time the slot is split, and ASK redirects let clients find moved keys. Adding a node means moving about 1/N of the slots to it. Only the keys in those slots move, and the rest of the keyspace is untouched, much like Consistent Hashing. Because data moves only on planned membership changes, not on failures (replicas take over in place), clusters stay stable. Replicas exist precisely so that a failure means promotion, not data shuffling.

Proxies. Some deployments put a proxy (Envoy's Redis filter, twemproxy, or a cloud provider's endpoint) in front, so that simple clients see one address. That's convenient, at the cost of an extra hop of about 0.1–0.3 ms.

Big keys and hot keys#

Big keys are single keys with huge values: a 50 MB string, a hash with 5 million fields, a list of 10 million items. They:

  • block the thread on DEL, HGETALL and SMEMBERS, or on expiry;
  • saturate network bandwidth on reads (a 10 MB value fetched 1,000 times per second is 10 GB/s);
  • unbalance cluster memory, and make migrations slow and blocking;
  • amplify COW during persistence.

Detect them with redis-cli --bigkeys and --memkeys (sampling scans), MEMORY USAGE key, or offline RDB analysis tools. Fix them by:

  • splitting: followers:{user}:{bucket} with bucket = hash(follower) % 64;
  • paginating reads with HSCAN, SSCAN and ZSCAN;
  • compressing values;
  • trimming collections;
  • UNLINK for deletion.

As a rule of thumb, keep string values in the tens of KB, and collections in the thousands to low millions of elements, sized so a full read stays well under a millisecond.

Hot keys are single keys receiving a disproportionate share of traffic: a celebrity's profile, a flash-sale product, a viral post's counter. One key lives on one node. That node is one main thread at about 100k ops/s, so a key requested 500k times per second will melt its shard regardless of cluster size. Detect hot keys with redis-cli --hotkeys (needs an LFU policy), or with client-side sampling and metrics. Mitigations, depending on whether the heat is reads or writes:

MitigationHowHelps readsHelps writesCost
Client-side (near) cacheApp process caches the value for 1–5 s, or uses Redis client-side tracking with invalidationYes, massivelyNoStaleness, memory per app server
Key replicationStore copies product:123:1 .. product:123:10, read a random copyYes, spreads across slots and nodesNo (writes go to all copies)Write amplification, consistency between copies
Read replicasRoute reads for the hot key to replicas (READONLY)Yes, up to replica countNoEventual consistency; clients must be configured for replica reads
Counter shardinglikes:post:9:{0..15}, INCR a random shard, sum on read (or periodically)Read needs aggregationYesMore complex reads
Local aggregationBatch increments in the app (sum for 1 s, then one INCRBY)—YesDelay, loss on crash

The pattern questions this answers are covered in Scaling Reads. "Millions of concurrent reads for the same cached data" is solved by near caches plus key copies, or by a CDN for public data. "Cache invalidation that's immediately visible" is solved by deleting on write plus client-side tracking invalidations, or by versioned keys that make the new value a new key, accepting a bounded staleness window when replicas or near caches are involved.

Limits of Redis#

  • Memory is the dataset limit, and it's expensive. RAM costs roughly 10–30 times more than SSD per GB in the cloud. A 1 TB working set across a cluster is feasible but costly. Beyond the working set, a database with its own cache is cheaper. (Redis Enterprise's "Redis on Flash", or Dragonfly's tiering, push this boundary at some complexity.)
  • One main thread per node caps CPU-bound throughput per shard at about 100k–200k ops/s without pipelining. Scale by sharding, not bigger machines. Many-core boxes are often run with several Redis processes.
  • Asynchronous replication means acknowledged writes can be lost on failover. It isn't a CP system.
  • No query language. There are no joins, no ad-hoc filters, and no secondary indexes unless you maintain them by hand (or use Redis 8's query engine). You must know your access patterns up front.
  • Value size: strings up to 512 MB, but anything over about 1 MB is a design smell.
  • Transactions are weak. MULTI/EXEC queues commands and runs them atomically, but there's no rollback: if one command fails at runtime, the others still apply. Atomic conditional logic belongs in Lua or Functions.
  • Cluster restrictions: multi-key operations only within one slot, a single logical database (no SELECT 1), and cross-slot transactions are impossible.

Redis vs Memcached and the Redis-compatible family#

SystemModelThreadsPersistence and replicationFits when
Redis (OSS, and Redis 8 with bundled modules)Data structures, Lua and Functions, streams, pub/sub, clusterSingle execution thread plus I/O threadsRDB and AOF, async replicas, Sentinel and ClusterDefault choice when you need more than a blob cache
Valkey (Linux Foundation fork, 2024)Same as Redis 7.2 at the fork, evolving independentlyLike Redis, with added multithreaded I/O workSameYou want a BSD-licensed, community-governed Redis; offered by several clouds
MemcachedPlain key to blob cache, LRU, no typesMultithreadedNone, and no replication (the client shards)Simple, huge, pure caches where multithreaded vertical scaling and simplicity matter; Facebook's "Scaling Memcache at Facebook" (Nishtala et al., NSDI 2013) describes it at trillions of requests per day
Dragonfly, KeyDBRedis-protocol compatible, multithreaded enginesMany threads per processSnapshotting and replicationYou want one big multi-core node instead of a cluster; verify command compatibility
Amazon MemoryDBRedis or Valkey compatible, durable multi-AZ logManagedWrites durable before ack; ms-level writesRedis API as a primary database with durability
ElastiCache, Memorystore, Azure Cache or Managed RedisManaged Redis or ValkeyManagedManaged replicas, failover, backupsYou don't want to run Sentinel or Cluster yourself

Memcached's case is simplicity: multithreaded, slab-allocated, no persistence, consistent hashing in the client. If every value is an opaque cached blob, and you want one big multithreaded box per shard, it's excellent. Redis wins whenever the data structures, TTL per key, replication, persistence or pub/sub matter. In interviews, that's almost always.

When to Use It#

Reach for Redis when the feature needs fast, simple, atomic operations on shared state, and the data is either rebuildable or tolerant of a small loss window. Concrete signals:

  • Read-heavy hot data where a database would see more than about 5k–10k reads per second for the same items. A Redis cache serves about 100k per second per node at about 0.5–1 ms.
  • Counters and limits updated thousands of times per second (likes, views, quotas, rate limits) where an UPDATE ... SET n=n+1 on one row would serialise on a row lock.
  • Rankings and time-ordered sets: leaderboards, top-k, "most recent N", priority queues by deadline.
  • Ephemeral state with expiry: sessions, OTPs, seat holds, presence, idempotency keys with a 24-hour TTL.
  • Real-time fan-out between stateless servers (pub/sub to WebSocket gateways).
  • Lightweight queues and background jobs, where the backlog fits in memory and at-least-once delivery with idempotent handlers is fine.
  • Proximity queries on frequently updated positions (drivers, couriers), where a database geo index would churn.

Pick something else instead when:

  • The data is the system of record and must not lose acknowledged writes: pick PostgreSQL (or another ACID database), or MemoryDB if you need the Redis API.
  • The working set is far larger than affordable RAM (terabytes of mostly cold data): pick Cassandra, DynamoDB, or a database with a cache in front.
  • You need durable, replayable event streams retained for days, with many consumer groups: pick Kafka.
  • You need ad-hoc queries, joins, full-text relevance: pick SQL or Elasticsearch.
  • You need correctness-grade coordination (leader election, locks with fencing): pick ZooKeeper or etcd.
  • You need long-running workflows with timers and retries across days: pick Temporal.

When NOT to Use It#

  • As the only copy of important data. A crash with AOF everysec can lose about a second of writes, and a failover can lose more. If losing an order, payment or message is unacceptable, write to a durable store first.
  • For large, cold datasets. Paying for RAM to hold data read once a month is a cost mistake. Measure the working set and cache only that.
  • When you'll need flexible queries later. If product teams will want "filter by any field", Redis forces you to maintain every index by hand.
  • For big values or unbounded collections (multi-MB blobs, ever-growing lists). Store blobs in object storage and keep a pointer.
  • For strong distributed locks guarding correctness. Use Redis locks only for efficiency, or add database-enforced fencing.
  • When a local in-process cache suffices. For a single service with a small, rarely changing dataset (configuration, feature flags), an in-memory map with a TTL avoids a network hop and a dependency entirely.

How to Implement It#

  1. Decide the role. Cache, ephemeral state, coordination or queue? The role determines eviction, persistence and replication settings.
  2. Design keys and types. Pick namespaced keys, the type for each access pattern, TTLs, size bounds, and hash tags for keys that must stay together.
  3. Size memory. Data plus about 50–100 bytes of overhead per key, multiplied by replicas. Leave 25–50% headroom for fork COW, buffers and fragmentation. Prefer shards of about 10–25 GB.
  4. Choose the topology.
    • A single primary with replicas plus Sentinel, for up to about 100k ops/s and a few tens of GB.
    • Redis Cluster for more, sized by peak ops/s ÷ about 80k per shard and dataset ÷ shard size.
    • A managed service unless you have Redis operators.
  5. Set eviction and persistence: allkeys-lru or allkeys-lfu for caches, noeviction plus alerts for state you mustn't lose, AOF everysec for state, RDB for backups.
  6. Configure clients. Pool connections, set timeouts (for example a 50–100 ms command timeout for cache reads, then fall back to the database), and use cluster-aware clients, pipelining and MGET.
  7. Write atomic logic in Lua or Functions, keeping each script short (milliseconds at most), with all touched keys declared and same-slot.
  8. Handle failure explicitly. Cache reads should degrade to the database (with a circuit breaker, so a Redis outage doesn't become a database stampede). Rate limiters should fail open or closed by policy. Queues need consumers that are idempotent.
  9. Observe: track hit ratio, used_memory versus maxmemory, evicted keys, instantaneous_ops_per_sec, latency percentiles, SLOWLOG, replication lag (offset difference), latest_fork_usec, connected clients and keyspace size per shard.
  10. Operate safely. Disable or rename dangerous commands (KEYS, FLUSHALL, CONFIG) with ACLs. Enable TLS and ACL users. Run game days that kill the primary.

A production-leaning redis.conf for a cache-plus-state node:

# memory
maxmemory 24gb                    # on a 32 GB host: headroom for COW and buffers
maxmemory-policy allkeys-lfu      # cache semantics; use noeviction for must-keep state
maxmemory-samples 10              # better LRU/LFU approximation for slightly more CPU
lazyfree-lazy-eviction yes        # free evicted big values in background
lazyfree-lazy-expire yes
lazyfree-lazy-user-del yes        # DEL behaves like UNLINK
 
# persistence
appendonly yes
appendfsync everysec              # ~1 s loss window
aof-use-rdb-preamble yes          # fast restart: RDB base + AOF tail
save 3600 1                       # hourly RDB for backups
 
# replication safety
repl-backlog-size 512mb           # survive longer replica disconnects with partial resync
min-replicas-to-write 1
min-replicas-max-lag 10           # isolated primary stops accepting writes
 
# performance and safety
io-threads 4                      # parallel socket I/O on multi-core hosts
slowlog-log-slower-than 10000     # microseconds (10 ms)
timeout 300                       # close idle clients
rename-command KEYS ""            # or use ACLs to forbid it
TechnologyFits when
Redis OSS or Valkey self-hostedYou have operators, want full control, and run on VMs or Kubernetes with operators
Amazon ElastiCache, Google Memorystore, Azure Cache or Managed RedisManaged cache and state with automated failover, patching and backups
Amazon MemoryDBYou want the Redis API with durable, multi-AZ-committed writes as a primary store
Redis Enterprise or Redis CloudActive-active geo-replication (CRDT-based), flash tiering, vendor support
MemcachedPure blob caching with multithreaded nodes and no persistence needs
Dragonfly or KeyDBA single large multi-core node speaking the Redis protocol
Sidekiq, BullMQ, Celery (with Redis)Background job queues built on Redis lists, sorted sets or streams

Trade-offs#

OptionProsConsPick when
Single primary + replicas + SentinelSimple; multi-key ops work everywhere; automatic failoverOne node's memory and write throughput is the ceilingUnder about 100k ops/s, under about 25 GB
Redis ClusterScales memory and throughput horizontally; built-in failoverCROSSSLOT limits; hash-tag design; client support neededLarger datasets or throughput; key-partitionable workloads
Cache-only (eviction on, little or no persistence)Cheapest; simplest operationsCold restarts; stampedes after lossData fully rebuildable from a database
State store (AOF everysec + replicas)Survives restarts with about 1 s lossAsync failover loss; memory costSessions, limits, holds, leaderboards
Durable Redis-compatible (MemoryDB)No acknowledged-write loss across AZ failuresMillisecond writes; higher cost; vendor lock-inRedis API as a primary database
Redis Streams vs KafkaStreams: tiny operational cost, low latencyMemory-bound retention; weaker durabilityShort-lived work queues on existing Redis
Redis lock vs ZooKeeper or etcd lockRedis: fast, simple, already deployedNo fencing or consensus; failover double-grantEfficiency locks only; use ZooKeeper or etcd or the database for correctness

Common Pitfalls#

  • No TTL and no bound. Keys without expiry plus noeviction means OOM errors on writes when memory fills. Every cache key gets a TTL, and every collection gets a trim.
  • Running KEYS * in production (or FLUSHALL by accident). It blocks the thread for seconds on millions of keys. Use SCAN, and lock down dangerous commands with ACLs.
  • Big keys. A single 2 GB hash makes DEL, migration, failover sync and persistence painful. Split by bucket.
  • Hot keys on one shard no matter how many shards you add. Use near caches, key copies or counter sharding.
  • Treating SET NX EX locks as correct under failover. Async replication can double-grant. Add fencing at the storage layer, or use the database.
  • Expecting MULTI/EXEC to roll back. Redis has no rollback. Use Lua for conditional atomic logic.
  • Cache stampede on expiry of a hot key or a mass expiry. Use jittered TTLs, a single-flight rebuild lock, and stale-while-revalidate.
  • Cache and database inconsistency. The safer default is "update the database, then delete the cache key" (not "set the cache"), with a short TTL as a backstop. Racing writers can still briefly cache an old value, so consider versioned values or delayed double-delete for hot keys.
  • Memory headroom ignored. Setting maxmemory to 95% of RAM means a BGSAVE under write load triggers the OOM killer, so the whole node dies.
  • Primary with persistence off and auto-restart: it comes back empty and replicas sync the empty dataset.
  • Pub/sub used as a durable queue: subscribers that disconnect lose messages. Use streams, Kafka, or store first and then notify.
  • One connection per request. Connection setup plus TLS dominates latency. Pool connections, and use pipelines.
  • Cross-slot surprises after moving to Cluster: MGET across users fails. Design hash tags before migration.

Real-World Examples#

  • Twitter described in talks (for example Raffi Krikorian's "Timelines at Scale", QCon 2012) keeping users' home timelines as Redis lists of tweet IDs in a large Redis cluster, fanning out on write to followers' lists. It's the archetype of fan-out-on-write (News Feed).
  • GitHub created Resque (2009), a Redis-backed background job library, and Sidekiq later popularised the same model in the Ruby world. Redis lists and sorted sets as job queues became standard practice from these projects.
  • Instagram explained (2011) how it stored about 300 million photo-to-user mappings in Redis, and how bucketing them into hashes, to use the compact encoding, reduced memory roughly fourfold.
  • Stack Overflow has written publicly about using Redis as a shared cache tier in front of SQL Server, alongside in-process caches (a two-level near-cache plus Redis design).
  • Ticketing systems commonly use Redis for short seat holds with TTLs and for caching search results keyed by all search parameters, while the database enforces final booking correctness.
  • Ride-hailing and delivery systems keep the latest driver or courier positions in a geo index or in-memory store, and query nearby candidates in milliseconds (Ride-Hailing, Food Delivery).

Case studies that use this pattern#

In the Interview#

Deep Dive: Redlock, the fencing debate, and safe locking with RedisShow

Why one Redis node isn't enough. The single-node SET NX EX lock is correct while that node is alive and doesn't lose data. Add a replica for availability and you reopen the hole: the primary acknowledges the lock, crashes before the replication stream carries it, and the promoted replica grants it again. Turn persistence off and restart the node, and the same thing happens. The lock key is simply gone.

The Redlock algorithm (proposed by antirez in the Redis documentation) uses N independent Redis primaries, typically 5, with no replication between them, on separate machines:

  1. Record the start time t0.
  2. Try SET resource token NX PX ttl on each of the N nodes in turn, with a short per-node timeout (a few to tens of milliseconds), so a dead node doesn't stall the attempt.
  3. Compute elapsed = now - t0. The lock is held if it was acquired on a majority (at least N/2 + 1 nodes) and elapsed < ttl.
  4. The usable validity time is ttl - elapsed - drift, where drift is a small allowance for clock rate differences.
  5. If acquisition failed, release on all nodes (the Lua compare-and-delete), and retry after a random delay, to avoid synchronised retries.

To survive crashes, antirez recommends either appendfsync always or delayed restarts: a crashed node stays offline for longer than the maximum TTL, so it can't come back empty and grant a lock that another client still holds elsewhere.

Kleppmann's critique (Martin Kleppmann, "How to do distributed locking", 2016) makes two arguments:

  1. Process pauses defeat any lease. A client acquires the lock and then hits a 60-second garbage-collection pause, or its VM is suspended, or a packet is delayed. The lease expires, a second client acquires the lock and writes, and then the first client resumes and writes too, believing it still holds the lock. Checking "do I still hold it?" just before writing doesn't help, because the pause can happen between the check and the write. Every lease-based lock has this problem, Redlock or not.
  2. Redlock depends on timing assumptions. If a node's clock jumps forward (an NTP step, a manual change), its key expires early, and a majority can be formed for a second client while the first still believes it's safe. Algorithms whose safety depends on bounded network delay, pauses and clock error are not safe in an asynchronous system model, where those bounds can be violated.

His fix is fencing tokens. The lock service returns a number that increases with every grant (33, then 34). The storage service remembers the highest token it has seen, and rejects writes carrying a lower one. Client 1 wakes up with token 33, but storage has already accepted token 34, so the stale write is refused. That moves safety out of the lock and into the resource. It requires a lock service that can produce monotonic tokens safely: ZooKeeper's zxid or znode version, etcd's revision, or a database sequence. Redlock has no such counter across nodes.

antirez replied in "Is Redlock safe?" (2016). He argued that the system model is reasonable when clocks are monotonic and the max drift is bounded, that the random token can act as a check if the resource supports compare-and-set, and that pauses hurt every lease-based system. The broad engineering consensus since then:

  • If the lock only prevents duplicate work (efficiency), a single Redis node with SET NX PX and a random token is fine. Redlock adds cost without changing the guarantee you actually need.
  • If the lock protects correctness, don't rely on any lease alone. Put a check in the resource itself: a fencing token, a conditional write (UPDATE ... WHERE version = ?), a unique constraint, or a transaction. Or use a consensus system designed for coordination (Leader Election and Coordination).

A worked ticketing example. 50,000 users try to buy 500 seats for one event.

  1. Hold: SET hold:evt:7:seat:A12 user:991 NX EX 600. It's instant, and gives a fair first-come user experience.
  2. Payment: happens with the hold in place. Usually under 10 minutes.
  3. Commit: UPDATE seats SET status='sold', buyer=991 WHERE event=7 AND seat='A12' AND status IN ('free','held'), and if one row was affected, the sale stands. Even if a Redis failover lost the hold and someone else grabbed it, the database row lets exactly one commit through. The other buyer gets a clean "seat no longer available" and an automatic refund.

Redis carries the contention for the user experience; the database carries correctness. This split is the heart of Dealing with Contention.

Lock hygiene checklist:

  • random token per acquisition;
  • TTL longer than the p99 critical section;
  • Lua compare-and-delete on release;
  • lease renewal (a "watchdog" extending the TTL while work is alive, as Redisson does in Java), with an absolute cap;
  • jittered retries;
  • metrics for acquisition failures and lock-held durations;
  • hash tags if several lock keys must be operated on atomically in a cluster.
Deep Dive: Cluster failover, resharding and client-side caching internalsShow

Failure detection. Each node pings a few random peers every second (and any peer it hasn't heard from in more than cluster-node-timeout / 2), carrying a gossip section about other nodes.

  1. If a node doesn't answer within cluster-node-timeout (15 s by default; often tuned to 5 s), the observer marks it PFAIL (possible failure).
  2. These flags spread through gossip. When a primary collects PFAIL reports from a majority of primaries within a window, it marks the node FAIL and broadcasts that.

That's a quorum-based detector in the spirit of Failure Detection and Gossip.

Replica election.

  1. The failed primary's replicas wait a delay: about 500 ms, plus a random 0–500 ms, plus about 1 s × their rank. Rank 0 is the replica with the most replicated data (highest offset), so it usually wins, minimising lost writes.
  2. The replica increments the cluster's currentEpoch and asks all primaries for votes.
  3. Each primary votes at most once per epoch (and not again for the same failed primary within twice the node timeout).
  4. With a majority of votes, the replica promotes itself, takes the slots under the new configEpoch, and gossips the change. Higher configEpochs win conflicting claims, a monotonic versioning scheme reminiscent of Raft terms (Consensus).

End-to-end failover is roughly node-timeout plus a second or two.

Availability rules worth knowing.

  • With cluster-require-full-coverage yes (the default), if any slot has no live owner (a primary and all its replicas down), the whole cluster stops accepting queries. Set it to no to keep serving the slots that are alive, at the cost of partial availability.
  • Replica migration (cluster-migration-barrier) lets a spare replica move to a primary that has lost its replicas.
  • During a partition, a primary on the minority side stops accepting writes after node-timeout, but writes accepted in that window are lost when the majority side promotes a replica. It's the same asynchronous-replication trade as Sentinel, bounded by the node timeout.

Resharding step by step, moving slot 3999 from A to D:

  1. CLUSTER SETSLOT 3999 IMPORTING A on D, and CLUSTER SETSLOT 3999 MIGRATING D on A.
  2. Loop: CLUSTER GETKEYSINSLOT 3999 100 on A, then MIGRATE D-host D-port "" 0 5000 KEYS k1 ... k100. Each MIGRATE atomically serialises the keys, restores them on D and deletes them from A. It blocks both nodes for the duration, which is why big keys make resharding painful.
  3. While migrating, a request for a key in slot 3999 at A is served normally if the key still exists there. Otherwise A replies ASK D. The client sends ASKING and then the command to D. D accepts the command for an importing slot only after ASKING.
  4. When the slot is empty on A, run CLUSTER SETSLOT 3999 NODE D on both, and the new ownership spreads (bumping the epoch). Clients that still go to A get MOVED and update their maps.

Tools (redis-cli --cluster reshard and rebalance, or managed-service online scaling) automate this. Rebalancing 1/N of the data from N to N+1 nodes moves only the slots reassigned to the new node.

Atomic slot migration was a long-standing pain point: key-by-key MIGRATE was slow for big keys. Newer Redis and Valkey releases have been working on faster, replication-based slot migration, so check your version's documentation before quoting specifics.

Client-side caching (tracking). Redis 6 added server-assisted invalidation. In default tracking mode:

  • a client sends CLIENT TRACKING ON;
  • the server records, in an invalidation table, which keys each client has read;
  • when any of those keys changes or expires, the server sends an invalidation push message to that client (over RESP3, or redirected to the __redis__:invalidate channel for RESP2 clients).

The table is bounded by tracking-table-max-keys, and when full, Redis evicts entries by sending invalidations early. Broadcasting mode (BCAST PREFIX user:) skips per-key bookkeeping: clients get invalidations for every key matching the prefixes they registered. That costs more messages but no server memory per read.

The result is a near cache with bounded staleness: roughly the time for an invalidation message to arrive (sub-millisecond to a few milliseconds), plus any gap if the connection drops. Clients must therefore flush their local cache on reconnect. That's how you serve "millions of concurrent reads of the same key" without melting the shard, while keeping invalidation nearly immediate.

Hot key worked example. A celebrity post receives 1.2 million reads per second at peak. One shard serves about 100k ops/s, so the single key needs at least 12 times that capacity.

  • Option A: 10 copies (post:9:c0..c9) on different slots. Each copy sees about 120k reads per second, still too hot.
  • Option B: near cache on 400 application servers, with a 2-second TTL or tracking invalidation. With 2-second TTLs, Redis sees about 400 / 2 = 200 reads per second for the key, a 6,000-fold reduction.
  • Combination: near cache plus 4 copies, for resilience when near caches are cold after a deploy.

Writes to the post (like counts) go to a sharded counter, likes:post:9:{0..31}, with the app summing every second, keeping the hottest write key under about 40k ops/s.

Deep Dive: Latency engineering and capacity planning for RedisShow

Where Redis latency comes from. A healthy GET costs about 1–2 µs of server CPU. Client-observed latency is mostly network: about 0.1–0.5 ms in the same availability zone, and about 0.5–1.5 ms across zones. When the p99 climbs to tens or hundreds of milliseconds, look at these, roughly in order of frequency:

  1. Slow commands. O(N) commands on big keys, KEYS, large SORT, heavy Lua. Everything queues behind them. Find them in SLOWLOG and LATENCY HISTORY command.
  2. Fork stalls. BGSAVE or AOF rewrite on a large instance. Check latest_fork_usec. Fixes: smaller shards, snapshots on replicas only, disabling THP.
  3. Swapping. If the OS pages Redis memory out, a lookup becomes a disk read of about 10 ms. Check /proc/<pid>/smaps swap totals. Keep maxmemory well below RAM, and consider vm.overcommit_memory=1 so fork doesn't fail.
  4. AOF fsync stalls. With everysec, if a background fsync is still running after 2 seconds (a busy or slow disk), the main thread blocks writes until it finishes, to cap the loss window. Use fast local SSDs, avoid sharing disks with other I/O-heavy processes, or set no-appendfsync-on-rewrite yes, accepting a larger loss window during rewrites.
  5. Mass expiry. Millions of keys with the same expiry second. The active-expire cycle works harder (it can consume a significant fraction of a CPU while more than about 10% of sampled keys are expired). Jitter the TTLs.
  6. Eviction storms. Writing quickly at maxmemory makes each write evict first. Big-value eviction is costly unless lazy freeing is on.
  7. Network and clients. Connection storms after a deploy (TLS handshakes), too many idle connections (each costs memory and file descriptors), and client-output-buffer-limit disconnecting slow pub/sub or replica clients.
  8. Noisy neighbours and CPU steal on shared VMs. Pin Redis to dedicated instance types for latency-critical work.

Pipelining maths. If an RTT is 0.3 ms and the server work 2 µs, a client doing one request at a time manages about 3,300 requests per second per connection. Pipelining 100 commands pays one RTT for 100 commands, so about 300k commands per second from one connection. The server becomes the limit at roughly 1 million per second for simple commands. That's why batch loaders and fan-out readers should pipeline or use MGET. With 1 KB values, also check the network: 1 Gbps is about 125 MB/s, or roughly 120k 1-KB values per second. A large share of "Redis is slow" reports are actually saturated NICs.

Capacity planning, worked example. A social app caches user profiles and post metadata for 20 million DAU:

  • Working set: 50 million objects × about 1 KB serialised = 50 GB. Key and object overhead, at about 80 bytes × 50 million, is about 4 GB. Total about 54 GB.
  • Traffic: peak 200k reads per second plus 10k writes per second (invalidations and sets) = 210k ops/s.
  • Throughput sizing: at a planning figure of about 80k ops/s per shard (leaving headroom below the 100k mark), 210k ÷ 80k means at least 3 shards.
  • Memory sizing: with 12 GB usable per shard on 16 GB hosts (25% headroom), 54 GB ÷ 12 GB means at least 5 shards.
  • Choose 6 primaries for growth: about 9 GB and 35k ops/s each, with 1 replica each in another availability zone. That's 12 nodes, or 192 GB of RAM.
  • Network per shard: 35k × 1 KB is about 35 MB/s, well under a 10 Gbps NIC. Cross-zone replication traffic is about 10k writes × 1 KB = 10 MB/s in total. Cheap, but it shows on the bill.
  • Failure budget: losing one shard's primary causes a failover of a few seconds. Cache reads for about 1/6 of keys fall back to the database, about 33k reads per second. If the database can't absorb that, add a circuit breaker and serve stale data from near caches. Better, keep a near cache with a TTL of a few seconds in each app process, to soak up most of the burst.

Memory estimation tips.

  • Benchmark with production-like values (redis-benchmark, or load a sample and read INFO memory).
  • The fragmentation ratio (used_memory_rss / used_memory) of about 1.0–1.5 is normal. Above 1.5 suggests fragmentation, so enable activedefrag yes (jemalloc-based active defragmentation). Below 1.0 means swapping. Investigate immediately.
  • Replication buffers, client output buffers and the AOF rewrite buffer all sit outside maxmemory accounting in some cases, another reason for headroom.

Multi-region. Native Redis replication is single-primary, so a cross-region replica is read-only, and failover across regions is a manual or orchestrated event. Active-active writes across regions need CRDT-based offerings (Redis Enterprise's Active-Active, which uses conflict-free replicated data types for counters, sets and strings). Otherwise you design per-region Redis with a database-level replication strategy (Multi-Region Data). Most teams keep caches regional, rebuilt from regional database replicas, rather than replicating the cache itself.

Key Takeaways#

  • Redis is an in-memory data structure server. One main thread executes commands atomically, one at a time, giving about 100k ops/s per node at sub-millisecond latency, and far more with pipelining.
  • Pick the structure for the access pattern: strings and counters, hashes for objects, lists and streams for queues, sets for membership, sorted sets for rankings and sliding windows, GEO for proximity, HyperLogLog and bitmaps for approximate and compact analytics.
  • The flagship uses are cache-aside caching, sessions, rate limiting (Lua), leaderboards, locks for efficiency, queues and streams, pub/sub fan-out and geo search.
  • Persistence has loss windows. RDB loses everything since the last snapshot. AOF everysec loses about 1 s. Async replication can lose acknowledged writes on failover. Use a database or MemoryDB for data you can't lose.
  • Sentinel gives failover for one primary. Cluster shards over 16,384 hash slots with client-side routing (MOVED and ASK). Use hash tags to keep multi-key operations in one slot.
  • Big keys and hot keys are the main scaling failures. Bound and split collections. Absorb hot reads with near caches, key copies and replicas, and hot writes with sharded counters.
  • Redis locks are for efficiency. For correctness, add fencing tokens or database-enforced conditions (Kleppmann vs Redlock).
  • Size for memory with 25–50% headroom, small shards (about 10–25 GB), TTLs on everything, jittered expiry, and dangerous commands disabled.