Skip to main content

Chapter 21 — Redis Beyond Caching: Data Structures, Caching Patterns & Coordination

Part IV · Data & Storage | Prerequisites: Ch 17 | Builds: Pulsely clinician sessions, an RCM ops leaderboard, rate limiting, and a cache on Redis

Most teams meet Redis as a GET/SET box bolted onto the side of their app: "we put the slow query result in Redis with a five-minute TTL, and now it's fast." That works, and then it betrays them — usually at 3 a.m., usually because a single key expired at the wrong moment. The trouble is that "string cache" is maybe a tenth of what the thing in front of you actually is. Redis is a single-threaded, in-memory data-structure server: a process that holds typed structures — sorted sets, hashes, streams — in RAM and runs operations on them atomically, where the data lives, at sub-millisecond speed. Once you see it that way, four problems that used to need their own infrastructure collapse into one tool: shared sessions, leaderboards, distributed rate limiting, and coordination between processes that can't otherwise see each other.

This chapter is the caching-theory chapter the rest of the book points at. When earlier chapters waved at "the CDN caches it" and promised "we'll do the real rate limiter in the Redis chapter," they were deferring to here. We'll derive caching patterns and their failure modes (stampede, dogpile, incoherence) from first principles, then derive each Redis use case from the engine's one defining property — it runs one command at a time — and we'll wire all four into Pulsely. Two ADRs close it out: how we cache and invalidate, and why we reject Redlock.


1. The problem: a cache is a bet, and the bet has a payout schedule you didn't read​

Let me put you in the incident.

It's a Tuesday night. A Pulsely provider profile — a well-known specialist whose clinic just opened a batch of appointment slots, the kind of thing a local news story or an open-enrollment guide links to — gets shared widely. Traffic on GET /providers/:id for that one provider goes from a trickle to four thousand requests a second. You're fine, because you cached it: provider:8842 lives in Redis with a 60-second TTL, and 99.9% of those requests are served from memory in under a millisecond. The database barely notices.

Then the TTL expires.

At second 60, the key is gone. The next request misses, so it does the obvious thing — queries Postgres, rebuilds the value, writes it back. But it isn't the next request; it's four thousand requests that all miss in the same handful of milliseconds, because they all arrived after the key vanished and before any one of them finished repopulating it. All four thousand stampede straight past the cache into Postgres. The connection pool (a fixed, shared set of reusable database connections the whole server borrows from) — sized for normal load, say 40 connections — saturates instantly. Requests queue for a connection. The query that took 8 ms when the database was calm now takes 900 ms because the database is fighting four thousand copies of itself. p99 on that endpoint goes from 40 ms to 9 seconds. And because your scheduling service calls the provider-directory service, and the patient portal calls the scheduling service, the timeout cascades outward — one expired key, and three services are now red on the dashboard.

Nothing was wrong. The query was correct. The cache was correct. The TTL was a reasonable number. The failure lives between correct components, in the same way the double-booked-slot race you saw earlier lived between two correct transactions. This one has a name — thundering herd, or cache stampede — and it is the single most common way a cache turns from a shield into a trigger.

Now stack two more pains on top, because they're the other reasons this chapter exists.

Sessions in process memory are a scaling dead end. Pulsely stores logged-in clinician sessions in a plain JavaScript Map inside each app process. It demos beautifully on one box. Then you scale to five pods behind a load balancer, and three things break at once: a clinician logs in on pod 2, their next request lands on pod 4, which has never heard of them, so they get a spurious 401; a routine deploy rolls the pods, and every session map is wiped, logging everyone out mid-charting; and you reach for "sticky sessions" on the load balancer to paper over it, which works until a pod dies and takes a third of your logged-in clinicians with it. State that lives in a process is state that dies with the process and is invisible to its siblings — the same lesson from the statelessness preview earlier, now biting.

Rate limiting in process memory is worse than useless — it's a false sense of safety. Pulsely limits login attempts to five per minute per account, implemented as a counter in each pod's memory. With five pods and a load balancer spreading traffic round-robin, the effective limit is twenty-five per minute, because each pod counts only what it personally saw. An attacker running credential stuffing doesn't even need to be clever; the load balancer spreads their attempts across pods for free, and the gate that was supposed to stop brute force never trips. A per-instance limiter on a multi-instance service is not a weaker control — it's the absence of a control, dressed up as one. On a system holding PHI, a login gate that silently doesn't work is exactly the failure you don't want to first learn about from a breach report.

What do these three have in common? Each needs shared state that lives outside any single process, that supports atomic compound operations (decrement-and-check, count-in-a-window, test-and-set), with first-class expiry. You could try to bolt all of that onto Postgres — and people do, with SELECT FOR UPDATE and a expires_at column — but you'd be paying a disk-backed, MVCC-versioned, transactional database to do work that is fundamentally "a number in RAM that several processes share." Redis exists for exactly that gap: a place to put shared, fast, atomic, expiring state that a relational database serves only clumsily and slowly.

🧭 A useful distinction. A cache is not "a faster copy of the truth." A cache is a bet that recomputation is more expensive than staleness. Every caching decision — what to cache, how long, who refreshes it, what happens on a miss — is a different answer to two questions: how wrong are we willing to be, and who pays when we're wrong? The stampede above is what happens when you answer "how wrong" but never answer "who pays on a miss." Hold this framing; the entire caching half of the chapter is just answering those two questions carefully for different kinds of data.


2. The mental model: a data-structure server that runs one command at a time​

Hold three pictures.

First: Redis stores structures, not bytes. With Memcached or a naïve cache, you store an opaque blob and parse it client-side. With Redis you store a typed structure — a hash, a sorted set, a stream — and you run operations on the server, where the data is. You don't fetch a leaderboard's rows and sort them in Node; you tell Redis ZREVRANGE and it returns the top ten already ranked, because the sorted set kept them ranked the whole time. This is the inverse of the stateless-app instinct you've already met, where we worked hard to keep logic out of any single process. Here we deliberately move the computation to the data for a narrow set of operations that are far cheaper executed in-place than fetched-and-recomputed.

Second: Redis runs exactly one command at a time, to completion, with no interleaving. This is the load-bearing fact of the whole chapter. There is one command-execution thread. Commands queue up and run serially, each one finishing entirely before the next begins. That single property explains almost everything else:

client A ──┐
client B ──┤ ┌──────────────────────────────┐
client C ──┼──────▶ │ ONE execution thread: │
client D ──┤ │ cmd → run to completion → cmd │ ──▶ replies
client E ──┘ └──────────────────────────────┘
(a serial queue; no two commands interleave)

Because nothing interleaves, atomicity is free: an INCR can't half-happen, and no other client can observe the keyspace mid-command. That's why coordination primitives — counters, locks, rate limiters — are so natural here; the hard part of concurrency control (serialization) is the engine's default, not something you bolt on. But the same property is also the sharpest blade pointed at your foot: because everything is serial, one slow command stalls every other client. Run KEYS * against a million-key keyspace, or a ZRANGE that returns half a million members, and for the duration of that one command nobody else's commands run at all. The single-threaded model gives you free atomicity and charges you for it in tail latency whenever you let one command run long.

Third: Redis plays three roles, and you must keep them separate in your head, because they have completely different correctness and durability expectations:

  • Cache — lossy, reconstructable, TTL'd. If you lose it, you recompute from the source of truth. Wrong-but-bounded-stale is acceptable here by design.
  • Authoritative ephemeral state — sessions, rate-limit counters. Losing these has real consequences (everyone logged out; the rate gate resets), even though the data isn't "permanent" in the way a signed encounter or a posted claim is. This is the role people underestimate.
  • Coordination bus — locks, pub/sub, streams. Here Redis isn't storing your data so much as arbitrating between your processes.

Mixing these roles in one keyspace is how you get the subtle bugs later in this chapter — a maxmemory eviction policy that's right for the cache silently deleting sessions, for instance. Same engine, three jobs, three different contracts.

🧭 Mental model. Redis is a serial executor of operations over shared, in-memory, typed structures. Picture a single very fast clerk at a counter: customers (clients) line up, the clerk serves exactly one at a time, completes their whole transaction before calling the next, and never gets confused about who's mid-transaction because there's only ever one. That image gives you atomicity (the clerk can't be interrupted), speed (no coordinating with other clerks, no walking to a filing cabinet — everything's on the desk), and the failure mode (one customer with a huge order makes everyone behind them wait). Every pattern in this chapter is a different errand for that clerk.


3. Theory & invariants​

A mental model tells you how to picture Redis. Invariants tell you what stays true so you can build correctness on top. These are the load-bearing rules.

🔑 The atomicity invariant. Every single command — and every Lua script or MULTI/EXEC block — executes atomically with respect to all other clients: it runs to completion with no other command interleaved. This is the guarantee every coordination pattern in this chapter leans on. A rate limiter that reads a count, decides, and writes back is only correct if those three steps can't be split by another client's commands. In a multi-step pattern, the unit of atomicity is the script, not the individual command — which is exactly why the sliding-window limiter is one Lua block and not three round trips.

The atomicity invariant is what lets you reason about concurrency at all. But notice the boundary: it's atomicity within a single Redis instance. It says nothing about what happens across a replication failover, and that crack is where distributed locks get dangerous (§7).

TTL and expiry are lazy plus active. A key can carry an expiry. When that time passes, the key is logically gone — but it isn't necessarily physically gone the instant the clock crosses it. Redis removes expired keys two ways: lazily, when something tries to access the key (it's checked, found expired, deleted, and treated as absent), and actively, via a background job that samples a handful of keys-with-TTL many times a second and evicts the expired ones it finds. The practical consequence: an "expired" key can briefly linger in memory before the active sweep reaches it, which matters for memory accounting (your memory usage lags your logical key count) and means you should never reason about expiry as a precise hardware clock — it's "gone at or shortly after the TTL, and definitely gone the next time anyone looks."

Eviction and expiry are different mechanisms, and conflating them loses data. Expiry is "this key had a TTL and its time came." Eviction is "Redis hit its maxmemory ceiling and had to free space now to accept a write." The eviction policy decides what gets sacrificed:

  • noeviction — refuse new writes with an error when full (the safe default for authoritative state).
  • allkeys-lru / allkeys-lfu — evict the least-recently / least-frequently used key, TTL or not.
  • volatile-lru / volatile-lfu / volatile-ttl — evict only among keys that have a TTL, leaving TTL-less keys alone.

The trap hides in allkeys-*: a key with no TTL can still be evicted. So if you keep sessions (which you want to keep until they expire or the user logs out) in the same instance as cache entries, under allkeys-lru, Redis will happily evict a logged-in clinician's session to make room for one more cached provider profile. The cache's eviction policy silently became your session store's data-loss policy. We'll fix this by separating the roles onto different keyspaces or instances in §5.

The data-structure vocabulary, and the invariant each one buys you. You don't memorize these; you reach for the one whose guarantee matches your problem:

StructureWhat it guaranteesCanonical use
Stringatomic INCR/DECR, SET ... NX, TTL on the keycounters, flags, single cached blob, the lock primitive
Hashfield-level reads/writes within one keya session object (HSET session HGET field) — update one field without rewriting the whole thing
ListO(1) push/pop at both endsa simple queue or stack (LPUSH/RPOP)
Setmembership, union/intersection/difference"have we seen this id," tag intersections, unique visitors (small)
Sorted set (ZSET)members kept ordered by a numeric score; O(log n) rank and rangeleaderboards, sliding-window timestamps, priority queues
Bitmapone bit per offset, packeddaily active flags (SETBIT user:42), 1 bit per user
HyperLogLogprobabilistic cardinality, ~0.81% error, fixed ~12 KB regardless of count"how many unique visitors today" when exact is overkill
Streamappend-only log with consumer groups and per-consumer offsetsdurable-ish event log, at-least-once fan-out to workers

The sorted set is the star of this chapter — it's both the leaderboard primitive and the sliding-window rate-limiter primitive — so internalize its shape: a set of members, each with a score, kept sorted by score, queryable by rank or score range in O(log n). HyperLogLog deserves a second look too: trading 0.81% error for a constant 12 KB to count billions of distinct things is a genuinely magical space tradeoff, and it's the right tool the moment "unique count" appears next to "and we don't need it exact."

🔑 Redis can forget a write you thought was saved. (The formal name for the guarantee it lacks is linearizability.) Replication from primary to replica is asynchronous: the primary acknowledges your write to you before the replica has it. If the primary crashes after acking but before replicating, and a replica is promoted, your acknowledged write is gone — it was never on the new primary. If you've done optimistic UI updates in React, it's the same shape: the client paints the change as "saved" the instant it applies locally, but if the network request behind it never actually lands, that state quietly vanishes. This is not a bug; it's the durability-vs-latency tradeoff Redis chose. It's also the theoretical crack under every "is my Redis lock safe?" question (§7) and the reason sessions and counters in Redis are ephemeral authoritative state, not durable truth: design so a lost session or a reset counter is survivable, because failover can and will eat one occasionally.

🔑 A lock does not enforce mutual exclusion — the resource does. This is the subtlest invariant in the chapter, so plant it now. A distributed lock is a hint that "I, holder of token X, believe I'm the only one acting." But locks have timeouts (they must, or a crashed holder freezes the resource forever), and a slow-but-alive holder can run past its timeout while still believing it holds the lock. Now two processes think they hold it. The only way to make the protected resource actually safe is a monotonic fencing token: each lock acquisition gets a strictly increasing number, every write to the protected resource carries that number, and the resource rejects any write whose token is lower than the highest it has seen. The lock service helps with liveness (mostly one holder, mostly); the resource enforces correctness. We'll see exactly why this matters in §7.

📎 Borrowed on credit: idempotency. Several patterns here — at-least-once stream delivery, lock-protected work that might run twice, retried cache rebuilds — only stay correct if the operation can be safely repeated. The general theory of idempotency (idempotency keys, dedup tables, exactly-once-effect from at-least-once-delivery) is derived properly in Ch 25. Here, just absorb the assertion: anything Redis might cause to happen twice must be designed so that twice is the same as once.

Cache-correctness vocabulary, stated precisely because the rest of the chapter uses these words as terms of art:

  • Cache-aside (lazy): the application owns the cache. Read → miss → load from source → populate cache → return. The cache is dumb storage; the app orchestrates.
  • Read-through: the cache itself loads from the source on a miss (a library/proxy sits in front of the source). The app only ever talks to the cache.
  • Write-through: every write goes to the cache and the source synchronously, keeping them coherent at the cost of write latency and coupling.
  • Write-behind (write-back): writes go to the cache and are flushed to the source asynchronously — fast writes, but a window where the source is behind and a crash loses data.

And two words people use interchangeably but must not: staleness is bounded, acceptable lag (the cached availability is up to 30 seconds old, and we decided that's fine). Incoherence is the cache contradicting the source in a way that corrupts behavior (the cache says a slot is open, it isn't, and we book it). Staleness is a tuning knob. Incoherence is a bug. Most "just add a longer TTL" advice quietly trades one for the other.


4. Under the hood​

Let's open each mechanism just far enough to kill the magic, because every production decision later is downstream of these internals.

Why single-threaded is fast (and what "I/O threads" really means)​

It sounds backwards that a single-threaded server outruns multi-threaded ones, until you account for where the time actually goes. Redis keeps everything in RAM, so there are no disk seeks in the hot path. Its data-structure operations are O(1) or O(log n) on structures tuned for exactly that. And critically, by running commands serially it pays zero of the coordination costs that dominate multi-threaded servers.

Here's the plain-terms picture before the jargon. In a multi-threaded server, several cores work on shared data at the same time, so they constantly have to stop and re-sync with each other so they don't corrupt it — like several people editing the same cell of one Google Doc, each waiting on the others' cursors. That coordination is pure overhead, and it has specific names:

  • lock acquisition and contention — threads queueing for the exclusive right to touch a shared structure;
  • cache-line ping-pong between cores — cores shuffling the same little chunk of memory back and forth between their private caches so everyone sees the latest value;
  • context-switch overhead — the OS pausing one thread mid-work to run another, saving and restoring state each time.

Redis skips all of it by only ever doing one thing at a time. The "work" of a typical command — bump a counter, add to a sorted set — is a handful of memory operations measured in nanoseconds. The expensive part of serving a request was never the command; it was the network I/O — reading the request bytes off the socket and writing the reply back.

Which is the one nuance that surprises people: modern Redis does use threads — for network I/O. It can read and parse incoming requests and write outgoing replies on multiple I/O threads, then hand the parsed commands to the single execution thread that still runs them one at a time. So "Redis is single-threaded" remains true where it matters (command execution, hence atomicity), while the network legs that were the real bottleneck get parallelized. When you read "I/O threads" in the config, that's this — not a relaxation of the atomicity guarantee.

The Node lane: one multiplexed connection, and pipelining​

Coming from Postgres, your instinct is "I need a connection pool." For Redis you mostly don't. A single Redis connection multiplexes — you can have thousands of commands in flight over one socket, because the protocol is request/reply in order and the client matches replies to requests by position. With ioredis or node-redis, one client object backed by one (or a few) connections serves your whole app fine. There's no per-connection transaction affinity to worry about the way there was with Postgres, because Redis commands are individually atomic.

The optimization that does matter is pipelining: instead of sending command, waiting for the round trip, sending the next, you send a batch of commands back-to-back and read all the replies together. You pay one network round trip for N commands instead of N round trips. When you're doing many small operations, this is the difference between "limited by Redis" (fast) and "limited by network latency" (slow).

import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL); // one client, multiplexed; reused app-wide

// Without pipelining: 3 sequential round trips.
// With pipelining: 1 round trip for all three.
const results = await redis
.pipeline()
.hset("session:abc", "user_id", "42")
.expire("session:abc", 1800)
.incr("metrics:logins")
.exec();

Lua: atomic multi-step logic, run inside the single thread​

When a pattern needs several operations to be atomic together — read a count, decide, then write — you can't do it as separate commands (another client could slip between them) and MULTI/EXEC can't make decisions mid-transaction. The answer is a Lua script run via EVAL (or EVALSHA, which runs a script you've already cached on the server by its SHA, saving you from shipping the source every call). The whole script executes atomically inside the single execution thread — exactly because of the serial model, nothing runs between its first and last line.

Three rules, learned the hard way by everyone:

  1. Pass keys through KEYS[], never string-interpolate them. This isn't just hygiene; in Cluster mode Redis routes a script to the right shard based on the declared keys, and a script that reaches keys it didn't declare is undefined behavior.
  2. Scripts must be deterministic — same inputs, same effect — because they may be replicated/logged as effects.
  3. Scripts must be fast. A Lua script blocks the entire server for its duration (single thread, remember). A script with a loop over a large collection is a server-wide stall. Keep them O(small).

Sorted-set internals — the dual structure that powers two patterns​

A sorted set is implemented as two structures sharing the same members: a hash table (member → score, giving O(1) "what's this member's score") and a skiplist ordered by score. Picture the skiplist as a sorted list with express lanes — extra forward pointers that let you jump ahead in big hops instead of stepping through every element — which is what makes "what's at rank N" and "what's in this score range" fast (O(log n)). You never touch its internals; you just get the fast ranking for free. That dual layout is why the leaderboard operations are all cheap:

ZADD leaderboard 150 "provider:42" -- set/update a score: O(log n)
ZINCRBY leaderboard 30 "provider:42" -- atomically add to a score: O(log n)
ZREVRANGE leaderboard 0 9 WITHSCORES -- top 10 by score, descending: O(log n + 10)
ZRANK / ZREVRANK leaderboard "provider:42" -- "what rank am I?": O(log n)
ZREMRANGEBYRANK leaderboard 0 -101 -- keep only top 100, trim the rest: O(log n + trimmed)

ZADD ... GT / ZADD ... LT update a score only if the new value is greater/less than the current — handy for "high score only." The point is that the ranking is maintained on every write, so reading the top-N is never a sort, it's a range scan over an already-sorted structure.

Sliding-window rate limiting, mechanically​

A sliding-window limiter answers "have there been more than N events in the last W seconds, as of right now." Model it as a sorted set per identity, where each member is a unique request marker and its score is the request's timestamp. To check-and-record one request atomically:

  1. ZREMRANGEBYSCORE key 0 (now - W) — evict every timestamp older than the window. The set now holds only events still inside the window.
  2. ZCARD key — count what remains. That's the current usage.
  3. If under the limit: ZADD key now <unique-member> to record this request, and EXPIRE key W so the key cleans itself up if traffic stops.
  4. Return allowed/denied plus how many remain.

All four steps must be one atomic unit — hence Lua. Contrast the alternatives:

  • Fixed window (INCR key + EXPIRE key W on the first hit): cheap and simple, but it has the boundary-burst flaw — a client can fire N requests at 0:59 and N more at 1:01, sending 2N in two seconds across the window edge, because the counter reset at 1:00. Fine for coarse quotas; dangerous for a brute-force gate.
  • Token bucket (a hash holding tokens + last_refill; on each request, refill based on elapsed time, then try to spend a token): allows controlled bursts, smooth refill, and is the classic choice when you want "steady rate but tolerate a short spike."

We'll use sliding-window for Pulsely's auth gate because brute-force protection is precisely where the boundary-burst flaw is unacceptable.

Distributed lock mechanics — and the release footgun​

Acquiring a lock is a single atomic test-and-set with an expiry:

SET lock:rebuild:provider:8842 <random-token> NX PX 5000

NX means "only if it doesn't exist" (so only one acquirer wins), and PX 5000 sets a 5-second auto-expiry so a crashed holder can't freeze the lock forever. The random token is your proof of ownership.

Releasing looks trivial and is where everyone bleeds. The naïve release is DEL lock:..., and it is wrong, because of this sequence: A acquires the lock with a 5s TTL; A's work runs slow (GC pause, a stalled query) and takes 6s; at 5s the lock auto-expires; B acquires the now-free lock; at 6s A finishes and runs DEL — deleting B's lock. Now A and B both think they hold it. The fix is a compare-and-delete in Lua: delete the key only if its value still equals my token, atomically.

-- release.lua: delete only if it's still my lock
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end

This closes the "delete someone else's lock" hole. It does not close the deeper hole — that A might still act on the resource during that 1-second overlap while believing it holds the lock — and nothing inside Redis can. That's the fencing-token problem we deferred to §7.

Pub/Sub vs Streams — fire-and-forget vs a durable log​

Pub/Sub is the simplest possible fan-out: PUBLISH channel message sends to whoever is SUBSCRIBEd right now. There is no persistence, no replay, no acknowledgment. If a subscriber is down, restarting, or simply not connected at the moment you publish, the message is gone — it was never stored. Pub/Sub is perfect for ephemeral, lossy fan-out (cache-invalidation pings, presence updates) and catastrophic as a queue.

Streams are an append-only log. XADD stream * field value appends an entry with a server-assigned monotonic ID; XREAD reads from an offset; and consumer groups (XGROUP, XREADGROUP, XACK) give you the real machinery: multiple workers share a group, each entry is delivered to exactly one worker in the group, unacknowledged entries sit in a pending-entries list and can be reclaimed (XCLAIM) if a worker dies mid-process. That's at-least-once delivery with per-consumer offsets — durable, replayable, and the right tool when "this message must not be lost" (a queued lab order, an inbound result to route). The cost is that you now own offset and pending-list management.

📎 Borrowed on credit: durable queues vs Streams. Redis Streams look like a job queue, and for lightweight cases they are one. But the full treatment of background job processing — retries, dead-letter queues, scheduling, when a Stream is enough vs when you want a dedicated queue (BullMQ) or a real broker — lives in Ch 26. Here, know that Streams can be a queue and why (consumer groups + PEL); the operational depth of running one is there.

📎 Borrowed on credit: log-based streaming. The "append-only log you replay" idea generalizes far beyond Redis into Kafka and event-driven architecture. The theory of the log as a primitive — ordering, partitioning, retention, replay as a first-class feature — is Ch 27. Redis Streams are a small, in-memory instance of that big idea.

Persistence: RDB, AOF, and the durability dial​

Redis is in-memory, but it can persist so a restart doesn't start empty:

  • RDB (snapshot): periodically makes a near-instant clone of itself and writes a frozen, point-in-time binary snapshot of the whole dataset to disk. (That near-instant clone is what fork() plus copy-on-write buys you: the clone shares memory with the original and only copies the pages that actually change afterward, so snapshotting a big dataset doesn't freeze the server.) Compact, fast to load on restart — but you lose every write since the last snapshot if you crash. The fork can cause a latency blip on huge datasets.
  • AOF (append-only file): logs every write command to a file. Durability depends on the fsync policy: always (fsync every write — safest, slowest), everysec (fsync once a second — lose at most ~1s, the sane default), or no (let the OS decide — fastest, loosest). AOF files grow, so Redis periodically rewrites them into a compact form.
  • Hybrid (the modern default): an RDB snapshot as the base plus an AOF tail for recent writes — fast restart and a small loss window.

The dial is "how much write loss can this workload tolerate on a crash?" For a pure cache, RDB or even no persistence is fine — you reconstruct from the source. For sessions and counters, you want AOF everysec so a crash loses at most a second. And remember the §3 invariant: persistence protects against crash-and-restart, not against failover dropping an un-replicated acked write — those are different loss windows.

Clustering: 16,384 hash slots and the cross-slot rule​

When your dataset outgrows one node's RAM or one node's write throughput, you shard with Redis Cluster. The keyspace is divided into 16,384 hash slots; a key's slot is CRC16(key) mod 16384; slots are distributed across primary nodes. A client that asks the wrong node for a key gets a MOVED (permanent: "go to node X") or ASK (transient, during a slot migration) redirection, and cluster-aware clients follow these automatically.

The rule that bites: a multi-key operation — MGET, a transaction, a Lua script touching several keys — only works if all its keys live in the same slot. Otherwise you get a CROSSSLOT error, because there's no node that owns all of them. The escape hatch is hash tags: if a key contains {...}, only the part inside the braces is hashed. So ratelimit:{user42}:login and ratelimit:{user42}:search both hash on user42 and land in the same slot, letting a Lua script touch both. Cluster also gives up cross-slot transactions and cross-slot scripts entirely — a real constraint you design around, not configure away.

📎 Borrowed on credit: consensus and quorum. "How does the cluster agree on which node owns a slot, and how does it decide to promote a replica during a failover?" is a quorum/consensus question. The theory — quorums, majority agreement, why an even number of nodes is dangerous — is Ch 24. Here we use the cluster; there we explain how it agrees with itself.

🛑 What we deliberately did not explain. The exact skiplist node layout and probabilistic level assignment (it's a beautiful data structure, but you don't need its internals to use a ZSET well). The full RESP wire protocol byte format. How fork() + copy-on-write interacts with the kernel's page tables during an RDB save. The Raft-like internals of cluster failover voting (that's Ch 24). We located each on the map; we didn't disassemble it.


5. In production: wiring all four into Pulsely​

Now we build. Four increments — sessions, leaderboard, rate limiter, stampede-proof cache — each derived from the mechanics above, each with the production details that the demo version skips.

Sessions as a hash with sliding expiry​

A Pulsely session is a small bag of fields, and a hash is exactly that — and lets us update one field without rewriting the blob. The session ID is a high-entropy, opaque, server-generated random string (never anything derived from the user — that's a forgeable-session security hole), and it's the only thing the client holds (in a cookie). The clinician's roles ride inside the session, server-side, because those roles drive RBAC and minimum-necessary access — the client never gets to assert its own.

// Create a session on login.
async function createSession(redis: Redis, user: User): Promise<string> {
const sid = crypto.randomBytes(32).toString("base64url"); // opaque, unguessable
const key = `sess:${sid}`;
await redis
.pipeline()
.hset(key, {
user_id: String(user.id),
roles: user.roles.join(","), // e.g. "provider,prescriber" — drives RBAC, held server-side
csrf: crypto.randomBytes(16).toString("hex"),
last_seen: String(Date.now()),
})
.expire(key, 1800) // 30-minute idle timeout
.exec();
return sid;
}

// On every authenticated request: validate + slide the expiry.
async function touchSession(redis: Redis, sid: string) {
const key = `sess:${sid}`;
const data = await redis.hgetall(key);
if (!data.user_id) return null; // expired or never existed → 401
await redis.expire(key, 1800); // sliding window: active users stay logged in
return data;
}

Two production decisions make this real. First, sliding expiry: every request resets the 30-minute TTL, so active clinicians stay in but idle ones drop out — exactly the session semantics an EHR wants (an unattended workstation shouldn't stay authenticated to a patient chart). Second, and this is the one teams miss: sessions must not share an eviction fate with the cache. Put sessions on a separate logical DB or, better, a separate Redis instance whose maxmemory-policy is noeviction (or use volatile-lru and only ever put TTLs on cache keys so the LRU only touches cache). Otherwise, the §4 trap fires — under allkeys-lru on a shared instance, a burst of cache writes evicts live sessions and logs random clinicians out for no reason they could ever diagnose. Server-side invalidation is now trivial and correct: logout or "log out everywhere" or a password change just DELs the key(s), and the user is genuinely, immediately logged out — something a stateless JWT can't do without extra machinery, and something you actually need when a compromised or offboarded account must lose access now.

The payoff against the §1 pain: sessions now live outside any pod, so a rolling deploy logs nobody out, any pod can serve any user, and you can throw away sticky sessions entirely.

Leaderboard: "top billers this week" as a sorted set​

An internal RCM ops dashboard ranks providers by dollars collected this week — an operations view for the billing team, not anything patient-facing. It's a sorted set keyed by the week, scored by collected dollars. When a payment posts (an 835 remit clears a claim), bump that provider's score; reading the top-N is a range query, never a sort.

function weekKey(d = new Date()): string {
// e.g. "leaderboard:providers:2026-W25" — the key *is* the time window
return `leaderboard:providers:${isoWeek(d)}`;
}

async function recordCollection(redis: Redis, providerId: number, amountCents: number) {
const key = weekKey();
await redis
.pipeline()
.zincrby(key, amountCents, `provider:${providerId}`) // atomic add-to-score
.zremrangebyrank(key, 0, -101) // keep only the top 100
.expire(key, 60 * 60 * 24 * 14) // auto-clean two weeks out
.exec();
}

async function topBillers(redis: Redis, n = 10) {
return redis.zrevrange(weekKey(), 0, n - 1, "WITHSCORES"); // top N, descending
}

The "reset weekly" requirement falls out for free: because the week is encoded in the key, a new week simply uses a new key — there's no reset job, no race, no "clear the leaderboard at midnight" cron that fails when a payment posts during the clear. Old weeks expire themselves. Note also that this is an excellent example of the §2 "move computation to the data" idea: you are never fetching provider rows and sorting them in Node; the ranking is maintained incrementally on every posted payment, and reads are O(log n + N).

One honesty note: this leaderboard is reconstructable (you could rebuild it by replaying posted payments from Postgres, which is the source of truth for collections), so it's safely in the "cache / ephemeral" role. If a failover dropped a few ZINCRBYs, the leaderboard would be slightly wrong until rebuilt — acceptable for an ops dashboard. You would not use a Redis counter as the authoritative record of how much a provider collected; that's a claim/payment-row fact in the durable store, and the money must reconcile against those rows, never against a cache.

The distributed sliding-window rate limiter​

One atomic Lua script does evict-old / count / record / decide, so it's correct no matter how many pods call it concurrently — the §1 "5 pods = 5× the limit" bug is structurally impossible because the counter lives in one place and the check-and-record can't be split.

-- sliding_window.lua
-- KEYS[1] = the limiter key (e.g. "rl:{user42}:login")
-- ARGV[1] = now (ms), ARGV[2] = window (ms), ARGV[3] = limit, ARGV[4] = a unique member id
local key, now, window, limit, member = KEYS[1], tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), ARGV[4]
redis.call("ZREMRANGEBYSCORE", key, 0, now - window) -- drop events outside the window
local count = redis.call("ZCARD", key) -- how many remain inside it
if count >= limit then
return {0, limit - count} -- denied; 0 remaining
end
redis.call("ZADD", key, now, member) -- record this request
redis.call("PEXPIRE", key, window) -- bound memory if traffic stops
return {1, limit - count - 1} -- allowed; remaining quota
async function rateLimit(redis: Redis, id: string, limit: number, windowMs: number) {
const member = `${Date.now()}-${crypto.randomBytes(6).toString("hex")}`; // unique per request
const [allowed, remaining] = (await redis.evalsha(
SLIDING_WINDOW_SHA, 1, `rl:{${id}}:login`, Date.now(), windowMs, limit, member,
)) as [number, number];
return { allowed: allowed === 1, remaining };
}

Production details that turn a toy into a control:

  • Key by identity and IP. Brute force against one account → key by account. Spray-across-accounts from one source → key by IP. Run both gates; trip on either. The {...} hash tag keeps a user's keys co-located for Cluster.
  • Return the right HTTP signals. On denial, 429 Too Many Requests with Retry-After and X-RateLimit-Remaining headers, so well-behaved clients back off instead of hammering.
  • Decide fail-open vs fail-closed per endpoint, deliberately. If Redis is unreachable, what does the limiter do? For most endpoints, fail-open (allow) — a Redis blip shouldn't take down your whole API. But for the login endpoint specifically, fail-closed (deny, or fall back to a strict local limit), because the limiter is your brute-force defense and failing open there hands an attacker an open door during exactly the outage they might be causing. This per-endpoint split is a senior decision; "fail-open everywhere" and "fail-closed everywhere" are both wrong as blanket policies.

Stampede-proof cache-aside for provider profiles (and the §1 fix)​

Finally, the cache that started the chapter — done so the herd never stampedes. Two mechanisms, both from §3/§4: jittered TTL so keys don't all expire in lockstep, and a single-flight guard so on a miss exactly one request rebuilds while the rest wait briefly and then read the fresh value.

async function getProvider(redis: Redis, db: Db, id: number): Promise<Provider> {
const key = `provider:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // hit — the common case

// Miss. Try to become the single rebuilder for this key.
const lockKey = `lock:provider:${id}`;
const token = crypto.randomBytes(8).toString("hex");
const gotLock = await redis.set(lockKey, token, "NX", "PX", 3000);

if (!gotLock) {
// Someone else is rebuilding. Wait briefly, then read what they wrote.
await sleep(50);
const retry = await redis.get(key);
if (retry) return JSON.parse(retry);
return loadFromDb(db, id); // bounded fallback; don't wait forever
}

try {
const provider = await loadFromDb(db, id); // exactly ONE DB query under the herd
const ttl = 60 + Math.floor(Math.random() * 30); // base 60s ± jitter — no lockstep expiry
await redis.set(key, JSON.stringify(provider), "EX", ttl);
return provider;
} finally {
await releaseLock(redis, lockKey, token); // Lua compare-and-delete from §4
}
}

Walk the herd through it now: at second 60-something the key expires (jittered, so not all keys at once), four thousand requests miss, one wins the SET NX lock and runs the single Postgres query, and the other 3,999 sleep 50 ms and find the freshly populated key. The database sees one query, not four thousand. The §1 cascade simply cannot form.

Invalidation is the other half, and we keep it simple on purpose: on a provider profile edit, delete the key (DEL provider:${id}) and let the next read repopulate it. We do not try to "update the cache in place" with the new value, because under concurrent writers two updates can race and leave the cache holding the loser's value forever — incoherence, not staleness. Delete-on-write is self-correcting: the worst case is a single extra cache miss. This choice, and the stampede protections, are exactly what ADR-021a records below.

🏭 Where the limiter and cache actually sit matters. A rate limiter at the API gateway / edge protects your app from traffic that never reaches it — good for crude volumetric limits. A limiter in the app (like ours) can key on authenticated identity and business rules the edge can't see. Real systems run both: a coarse edge limit and a precise app-level one. Same layering logic applies to caching — a CDN caches the truly public, a Redis layer caches the per-user-ish. (Note the boundary: you cache a public provider directory entry freely; you never push PHI — a chart, a patient's coverage — into a shared CDN edge.)

Operational hygiene that keeps all four alive in production:

  • Never KEYS * in prod — it's O(keyspace) and, single-threaded, stalls everything (§2). Use SCAN, which paginates cursor-style without blocking.
  • Always set maxmemory explicitly with a policy. An unbounded Redis grows until the OS OOM-kills it — a total outage from a config you forgot.
  • Separate cache from stateful workloads onto different instances (the eviction-fate point), so a cache memory storm can't evict sessions or limiter state.
  • Watch the SLIs. INFO gives used_memory, keyspace_hits/misses (your hit ratio — a real SLI), evicted_keys (alert on > 0 for the session/limiter instance — it means data loss), and blocked_clients. SLOWLOG surfaces the slow commands tail-latencying everyone. redis-cli --latency measures the round trip.
  • HA topology, eyes open: Sentinel gives automatic failover for a non-clustered primary/replica setup; Cluster gives sharding and failover. Either way, recall the §3 invariant — failover can drop an acked-but-unreplicated write — so design every Redis-held value to survive losing one.

6. Common pitfalls​

Each is signature → fix: the symptom, then the principle that resolves it.

Thundering herd / cache stampede. Signature: a synchronized miss spike (a popular key expired) drives N concurrent requests straight to the database; the pool saturates and p99 cliffs. Fix: jittered TTL so keys don't expire in lockstep, plus a single-flight recompute guard so exactly one request rebuilds while others wait or serve stale. Optionally serve-stale-while-revalidate.

Dogpile on cold start. Signature: after a deploy or a FLUSHALL, the cache is empty and every request recomputes at once — same shape as a stampede but triggered by an empty cache, not an expired key. Fix: warm critical keys on boot; the same single-flight guard; and probabilistic early expiration — recompute a key before its TTL with a probability that rises as expiry nears, so refreshes spread out instead of synchronizing on the deadline.

Bare DEL lock release. Signature: service A's work runs past its lock TTL, B acquires the freed lock, A finishes and DELs it — now B's lock is gone and two holders act. Fix: release with a Lua compare-and-delete (delete only if the value is still my token), and — for anything correctness-critical — a fencing token the resource enforces (§7). The Lua CAS fixes "delete someone else's lock"; only fencing fixes "two holders act."

Cache incoherence on write. Signature: a provider edits their profile, the UI keeps showing the old details for minutes or until the TTL — or, worse, forever because two writes raced. Fix: delete-on-write invalidation; never rely on a long TTL alone for mutable data; never "update the cache in place" under concurrent writers.

Per-instance rate counter. Signature: the limit silently scales with pod count; an attacker spreads load across pods and never trips it. Fix: centralize the counter in Redis with an atomic Lua check-and-record, as in §5.

Fixed-window boundary burst. Signature: roughly 2× the intended limit slips through across a window edge (N at 0:59, N at 1:01). Fix: sliding-window (sorted set) or token bucket, where "the last W seconds" is continuous rather than a resetting bucket.

Big-command / slow-Lua stalls. Signature: a server-wide latency spike and rising blocked_clients, traced to a KEYS *, an unbounded ZRANGE, or a Lua script with a loop. Fix: SCAN instead of KEYS, bounded ranges, and keep scripts O(small). One slow command blocks all clients (§2) — there is no "it only affects that one query."

No maxmemory set. Signature: Redis grows unbounded until the OS OOM-kills it — a sudden total outage with no warning in Redis's own logs. Fix: set maxmemory and an explicit eviction policy; alert on memory and evicted_keys.

Pub/Sub used as a durable queue. Signature: messages silently vanish whenever a subscriber is down, restarting, or briefly disconnected. Fix: Pub/Sub is fire-and-forget by design; use Streams with consumer groups for anything that must not be lost.

Cluster cross-slot error. Signature: a CROSSSLOT error from an MGET, transaction, or multi-key Lua whose keys hashed to different slots. Fix: hash tags ({...}) to co-locate the keys that must be operated on together, or redesign the access pattern so multi-key ops stay within a slot.

Mixing roles in one keyspace. Signature: sessions or rate-limit state get evicted under load because they share an allkeys-lru instance with the cache. Fix: separate instances/logical DBs per role; give the authoritative-ephemeral store a noeviction (or volatile-only) policy.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand.

Cache-aside ↔ write-through ↔ write-behind. Cache-aside is simple and resilient — the cache being down doesn't stop writes, because writes go straight to the source; the only cost is a miss window after each invalidation. Write-through keeps the cache coherent on every write but couples your write path to the cache's availability (cache down → writes fail or you must bypass) and adds write latency. Write-behind makes writes fast by flushing to the source asynchronously, but it can lose data on a crash and is genuinely hard to reason about (the source is transiently behind the cache). Pulsely picks cache-aside + delete-on-write. You'd reverse toward write-through only if read-after-write staleness becomes an actual correctness bug (a provider edits their availability and immediately must see the new value, and the miss-window is unacceptable) — and you'd accept the coupling that comes with it.

Strong ↔ eventual cache freshness. A longer TTL is cheaper (fewer recomputes) and staler; a shorter TTL is fresher and more expensive. The discipline is to write down an explicit staleness budget per entity: a provider's next open slot might tolerate seconds; a provider's display name and specialty, minutes; a clinician's role/permissions, possibly zero (you may not cache an authorization decision at all — an RBAC or minimum-necessary check that has gone stale is a HIPAA problem, not a performance one). "How stale may this be?" is a product decision you make per data type, not a global TTL you guess once.

Redlock ↔ single-node lock (and why Pulsely rejects Redlock). Redlock is the multi-node locking algorithm (acquire the lock on a majority of N independent Redis nodes) sold as "safer" than a single-node lock. Martin Kleppmann's well-known critique shows it still isn't safe for correctness under GC pauses or clock skew without fencing tokens — and once you have fencing tokens, the resource enforces correctness anyway, which is the part that actually matters (§3). Redlock buys availability of the lock service across node failures, at real operational weight, while leaving the correctness problem exactly where it was. So Pulsely rejects Redlock. A single-node SET NX PX lock is sufficient for non-critical mutual exclusion — e.g., "don't let two requests rebuild the same cache key simultaneously," where the worst case of a double-acquire is a wasted duplicate query, not a corrupted state. Any correctness-critical exclusion (don't double-submit a claim, don't double-book a slot) must enforce a fencing token at the resource — and at that point the lock is just an optimization to reduce contention, not the thing keeping you correct. You'd reconsider Redlock only if you genuinely need cross-AZ lock availability and you already have fencing — and even then, a real consensus system (or a database row lock) is usually the better answer.

Distributed-lock failure that NO Redis-only lock can prevent:
A: SET NX (TTL 5s) ──▶ [A stalls: GC pause, 7s] ─────────────▶ A resumes, WRITEs to resource
└─ at 5s lock expires ─▶ B: SET NX ─▶ B WRITEs to resource
Two writers. Only a fencing token at the resource ("reject token < highest seen") saves you:
A carries token 11, B carries token 12 → resource accepts 12, then REJECTS A's stale 11.

Redis as cache ↔ Redis as source of truth. Treating ephemeral state (sessions, counters, leaderboards) as authoritative means accepting that a failover can drop a recently-acked write (§3). That's fine for things that are reconstructable or survivable (a re-login, a slightly-off ops counter). It is not fine for anything you can't lose — a posted payment, a claim's adjudication state, a signed encounter, anything in the durable store's job description. The line: if losing this value on a failover would be a real incident (a lost claim, a chart entry that never persisted), it doesn't belong in Redis as the only copy.

RDB ↔ AOF. RDB restarts fast and is compact but has a larger data-loss window (everything since the last snapshot). AOF is more durable (down to ~1s loss with everysec) but larger and slower to replay on restart. The hybrid (RDB base + AOF tail) is the sane default; you pick by how much write loss the workload tolerates on a crash — near-zero for sessions/counters, "whatever, it's a cache" for a pure cache.

Pub/Sub ↔ Streams ↔ a real broker. Pub/Sub for cheap, ephemeral, loss-tolerant fan-out. Streams for lightweight durable queues and replay within an existing Redis, when you don't want to run more infrastructure. A dedicated broker (Kafka, SQS) when you outgrow Redis's throughput, retention, or ordering guarantees — the escalation path that Ch 26 and Ch 27 develop.

🚫 A framing this book rejects. "Add a Redis lock and the operation is now safe." A Redis lock provides liveness with high probability (usually one holder) — it does not provide correctness (definitely one effect). Conflating the two is how teams ship duplicate claim submissions and double-booked slots that pass every single-threaded test and only fail under the exact GC-pause-meets-failover timing that production eventually produces. Correctness lives at the resource (a fencing token, a UNIQUE constraint, an idempotency key from Ch 25) — the lock is at best an optimization on top.


8. Security & scale notes​

The threat surface starts with "Redis trusts the network." Historically Redis ships with no authentication and assumes anything that can reach it is allowed to do anything. An internet-exposed, unauthenticated Redis is a remote-code-execution waiting to happen: the classic attack uses CONFIG SET dir + CONFIG SET dbfilename to make Redis write an RDB file into ~/.ssh/authorized_keys or a cron directory, turning "I can reach your cache" into "I own your box." In a system holding PHI, that box may sit next to patient data — so: never expose Redis to the internet, bind it to a private network, require requirepass (or, better, ACL users with passwords), and use TLS in transit for anything crossing a network you don't fully control.

ACLs scope the blast radius. Modern Redis has per-user ACLs: restrict the app's user to the exact commands and key patterns it needs, and deny the dangerous ones (FLUSHALL, CONFIG, KEYS, DEBUG). If the app is compromised, the attacker inherits only what the app could already do — they can't FLUSHALL your keyspace or reconfigure the server. This is the same defense-in-depth principle as database constraints: assume the upstream is compromised and make the store refuse the dangerous operation anyway.

Session security is a checklist you don't get to skip. Opaque, high-entropy session IDs (never user-derived or guessable). Server-side invalidation on logout and on password change by DEL-ing the key(s) — the thing JWTs make awkward, you get for free here, and the thing you need when an offboarded clinician must lose chart access immediately. Sliding expiry so abandoned sessions die. And bind security-relevant fields (the CSRF token, roles) inside the session hash on the server, so the client can't tamper with them — the client holds only the opaque ID.

The rate limiter is a security control, so its failure mode is a security decision. It is your brute-force and credential-stuffing defense on /auth/login. Two non-negotiables: it must be fail-closed for login (if Redis is unreachable, deny or fall back to a strict local limit — never fail-open on the one endpoint protecting credentials to PHI), and its keys must not be forgeable by the client (key on server-established identity and the real source IP, not on a header the client controls — or an attacker just rotates the header and resets their own limit).

Behavior under load is a chain reaction, and Redis sits in the middle. Memory pressure → eviction → cache misses → more load on the database — a Redis capacity problem becomes a database outage, the §1 cascade in slow motion. A single slow command tail-latencies every client because of the serial model. And in Cluster mode, a single hot key — one viral provider profile everyone reads — concentrates all that traffic on the one shard that owns its slot, and you can't shard your way out of a single key. The mitigation for a hot key is a small in-process cache in the app for just the hottest handful of keys (a tiny local LRU with a short TTL), absorbing the read storm before it reaches Redis at all.

🔑 A Redis incident rarely stays a Redis incident. Because Redis sits between your app and your database as a load shield, its degradation removes the shield and dumps the full load on the database. So you size, monitor, and alert on Redis not as "is the cache up?" but as "is the thing protecting my database from the herd healthy?" evicted_keys > 0 on a cache instance isn't a Redis warning — it's an early warning of database load that hasn't arrived yet.

Scale ceilings, in order. Scale vertically first — a single Redis instance is shockingly capable, often hundreds of thousands of ops/sec, and most teams never outgrow one. Then read replicas for read-heavy workloads (replicas serve reads; remember they're async, so reads can be slightly stale). Then Cluster when your dataset exceeds one node's RAM or you hit single-node write throughput — accepting that Cluster forfeits cross-slot atomicity (no cross-slot transactions or scripts), which is a real design constraint, not a setting.

📎 Borrowed on credit: the WebSocket backplane. When we scale real-time fan-out across many app instances ("clinician X is online; push this critical-value alert to whichever pod holds their socket"), Redis Pub/Sub is the classic backplane that lets pods coordinate. That's a Ch 28 topic; here, just know the Pub/Sub primitive you learned is the building block that chapter assembles into cross-instance real-time delivery.


9. Interview lens & exercises​

Interview questions​

Interviews probe whether you reason about Redis or merely recite "it's fast because RAM."

"Redis is single-threaded — isn't that a bottleneck?"

  • Junior answer: "It's fast because it's in memory."
  • Senior answer: "In-memory plus an event loop over non-blocking I/O, and critically no lock contention or context-switch overhead because commands run serially — and modern Redis threads the network I/O while keeping execution serial, so the part that was actually the bottleneck got parallelized. The real risk isn't throughput, it's that one slow O(n) command — a KEYS *, an unbounded ZRANGE, a looping Lua script — stalls every client, because there's one execution thread. So you forbid those in prod and keep scripts O(small)." Names the mechanism and the failure mode it creates.

"How do you prevent a cache stampede?"

  • Junior: "Use a longer TTL."
  • Senior: "TTL jitter so keys don't expire in lockstep, plus a single-flight recompute guard so exactly one request rebuilds while the rest wait or serve stale, plus optionally probabilistic early expiration. And I'd frame why: the whole point is protecting the database connection pool from a synchronized miss spike — the stampede is a database-availability problem wearing a cache costume." Ties the cache fix to the downstream it protects.

"Is a Redis distributed lock safe?"

  • Junior: "Yes, use SETNX."
  • Senior: "Safe for liveness — usually one holder — but not for correctness. A holder can stall past its TTL while still thinking it holds the lock, so two processes act. SET NX PX plus a Lua compare-and-delete release fixes 'don't delete someone else's lock,' but the only thing that fixes 'two holders act on the resource' is a monotonic fencing token the resource rejects when stale. That's why Kleppmann's Redlock critique lands, and why I'd reject Redlock: it adds availability and operational weight without solving correctness, which still has to live at the resource." Distinguishes liveness from correctness — the whole game.

"Pub/Sub or Streams — when each?"

  • Junior: "Both send messages."
  • Senior: "Pub/Sub is fire-and-forget — no persistence, no replay, a subscriber that's down misses the message forever — so it's for ephemeral lossy fan-out like cache-invalidation pings. Streams are an append-only log with consumer groups, per-consumer offsets, and a pending-entries list for at-least-once redelivery, so they're for work that must not be lost — a queued lab order, an inbound result to route. And I'd escalate to Kafka when I outgrow Redis's retention or throughput." Names the durability/replay axis and the escalation path.

"Design a rate limiter for our login endpoint."

  • Junior: "INCR a counter with EXPIRE."
  • Senior: "Sliding-window in a single Lua script — ZREMRANGEBYSCORE to drop the old window, ZCARD to count, ZADD to record — so check-and-record is atomic and one shared counter survives N pods. Key by user and IP, return 429 with Retry-After, and fail-closed specifically for login because the limiter is the brute-force defense. I'd avoid plain fixed-window because of the boundary-burst flaw — 2× the limit across the window edge — which is exactly the gap an attacker exploits on a login gate." Picks the right algorithm and knows why the cheap one is dangerous here.

Exercises & the Pulsely increment​

Do these for real against a local Redis, not on paper — the failure modes only teach you when you watch them happen.

  1. Pulsely sessions. Migrate session storage to a Redis hash with sliding TTL on a dedicated logical DB with a non-evicting policy. Then prove the §1 fix: do a rolling restart of two app instances and confirm logged-in clinicians stay logged in across it. Then deliberately put sessions on a shared allkeys-lru instance, flood it with cache writes, and watch a session get evicted — so you feel why role separation matters.

  2. Pulsely leaderboard. Build "top billers this week" with a sorted set: ZINCRBY on payment posting, ZREVRANGE WITHSCORES for top-10, ZREMRANGEBYRANK to trim to top-100, and a key that encodes the ISO week so the weekly reset is free. Then rebuild the same leaderboard by replaying posted payments from Postgres and confirm they match — proving the sorted set is a reconstructable cache of a fact the durable store owns.

  3. Pulsely rate limiter (Lua). Implement the sliding-window limiter on /auth/login and /patients (patient search), load it with EVALSHA, add Retry-After and X-RateLimit-* headers. Then load-test with the app running as 5 pods and assert that the combined throughput respects one shared limit — the per-instance-counter bug from §1 must be impossible. Finally, kill Redis mid-test and verify login fails closed while /patients fails open.

  4. Stampede lab + the two ADRs. Instrument the provider-profile cache-aside path with a counter of how many DB queries fire per cache miss. Reproduce the herd: synchronize a key's expiry, fire a few thousand concurrent reads, and watch the DB-query counter spike to ~N. Then add jittered TTL + the single-flight guard and watch it drop to ~1. Write both ADRs below from what you observed.


ADR-021a — Pulsely caching strategy & invalidation​

  • Context. Hot read paths (a viral provider profile) risk a thundering herd; mutable data (a provider profile edit) risks incoherence. We need a strategy that protects the database pool and never serves a corrupting value.
  • Decision. Cache-aside (the app orchestrates load-on-miss) with delete-on-write invalidation (an edit DELs the key; the next read repopulates). On a miss, a single-flight guard (SET NX PX lock) ensures exactly one rebuild; cached values get a jittered TTL (base ± rand) so keys never expire in lockstep. A per-entity staleness budget is documented (provider availability: seconds; provider name/specialty: minutes; authorization/RBAC: not cached). PHI is never placed in a shared CDN/edge cache.
  • Rejected. Write-through — couples the write path to cache availability and adds write latency for a coherence we don't need given our read-after-write tolerance. "Update the cache in place" on edit — races between concurrent writers can leave the loser's value cached forever (incoherence). Long TTL alone — trades correctness for fewer recomputes; doesn't address mutable data or stampede.
  • Consequences. A small, bounded miss-window after each edit (acceptable staleness). Single-flight adds a brief wait for losers of the rebuild race. Requires monitoring hit ratio and evicted_keys; requires keeping cache and stateful workloads on separate instances. Revisit toward write-through only if read-after-write staleness becomes a correctness bug.

ADR-021b — Pulsely distributed-lock approach​

  • Context. We need cheap mutual exclusion for non-critical work (e.g., not rebuilding the same cache key twice) and a correctness-safe story for anything that must happen exactly once (no duplicate claim submission, no double-booked slot).
  • Decision. Single-node SET key <token> NX PX <ttl> to acquire, Lua compare-and-delete to release. For correctness-critical exclusion (no duplicate claim, no double-booked slot), correctness is enforced at the resource via a monotonic fencing token and/or a database UNIQUE/idempotency constraint — the lock is only a contention optimization, never the correctness guarantee.
  • Rejected. Redlock. Per Kleppmann's critique it is still not correctness-safe under GC pauses/clock skew without fencing tokens — and once fencing exists, the resource enforces correctness regardless of how many Redis nodes the lock spanned. Redlock adds operational weight and only buys lock-service availability, which Pulsely doesn't currently need.
  • Consequences. Lock availability is tied to the single Redis primary; a failover may briefly drop a lock (acceptable, because correctness lives at the resource, not the lock). Every correctness-critical path must carry a fencing token or a DB constraint — a code-review checklist item. Revisit Redlock only with both a measured cross-AZ availability need and fencing already in place.

Key takeaways​

  • Redis is a single-threaded, in-memory data-structure server, not a string cache. The one-command-at-a-time model is why atomicity is free and why one slow command stalls every client.
  • Keep its three roles separate: cache (lossy, reconstructable, TTL'd), authoritative-ephemeral (sessions, counters — losing them hurts), and coordination (locks, Pub/Sub, Streams). Different durability contracts; don't share an eviction policy across them.
  • A cache is a bet that recompute costs more than staleness. Every caching pattern answers "how wrong may we be, and who pays on a miss?" — and the stampede is what happens when you skip the second question.
  • The caching theory other chapters defer here: cache-aside / read-through / write-through / write-behind, and the pitfalls — stampede, dogpile, incoherence — fixed by jittered TTL + single-flight + delete-on-write. Staleness is a knob; incoherence is a bug.
  • The distributed rate limiter deferred to here is a sliding window in one Lua block (ZREMRANGEBYSCORE / ZCARD / ZADD), centralized so N pods share one limit; fail-closed on login.
  • Sorted sets power both leaderboards (ZINCRBY / ZREVRANGE / trim) and the sliding window — the ranking is maintained on every write, so reads are never a sort.
  • A lock provides liveness, not correctness. SET NX PX + Lua compare-and-delete stops "delete someone else's lock"; only a fencing token enforced at the resource stops "two holders act." This is why Pulsely rejects Redlock.
  • Redis is not linearizable across failover — async replication can drop an acked write — so design every Redis-held value to survive losing one, and treat a Redis incident as a database incident in waiting (it's the shield that protects your pool from the herd).

← Previous: Ch 20 — NoSQL Thinking & MongoDB · Up: Part IV overview · Master TOC · Next: Ch 22 — Search Infrastructure →