Chapter 28 — Realtime & Streaming Backends: WebSockets, SSE, Scaling Stateful Connections
Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 21, Ch 27 | Builds: Pulsely clinical alerts + care-team presence, scaled across instances
Everything you've built so far rests on one quiet assumption: a request comes in, a ruling goes out, and the server forgets you. That assumption is load-bearing. It's why "the server" can be twenty identical instances behind a load balancer, any of which can answer any request (the statelessness you've leaned on ever since). This chapter is where that assumption breaks — deliberately, and for a good reason — and you have to know exactly what you're giving up.
Realtime push inverts the model. Instead of the client asks, the server answers, you now have the server speaks first, whenever it wants, to a specific human who may be reachable through a TCP connection it opened ten minutes ago. That single inversion drags in everything hard about distributed systems at once: held state, the load balancer becoming part of your correctness logic, fan-out (getting one event out to many connections), backpressure (a fast server outrunning a slow client), authenticating a connection that outlives its own token. Don't worry if some of those are just words right now — each gets its own section below. The protocol is the easy 20%. The hard 80% is that realtime turns your stateless fleet into a distributed routing problem — and that's the part this chapter exists to teach.
1. The problem: why push breaks everything you've relied on
Let me start where these always start: a pager going off.
A patient's lab panel comes back with a critically high potassium — the kind of value that needs a clinician's eyes in minutes, not hours. The "critical result" alert reaches the on-call provider forty seconds later, because the client polls GET /alerts every thirty seconds and the result landed just after the last poll. Forty seconds is an eternity for a value that can stop a heart. So you tighten the poll to every five seconds. Now do the arithmetic: ten thousand concurrent clinicians, each hitting that endpoint every five seconds, is two thousand requests per second — and the overwhelming majority return nothing new. You've built a machine whose primary output is empty 304 Not Modified responses, and it's hammering your database's alerts table for the privilege. Polling is a busy-wait against a network. It's wrong twice: too slow when it matters, too expensive when it doesn't.
So you do the obvious thing. You reach for WebSockets, hold a connection open per clinician, and push the alert the instant the result commits. On one box, it's glorious. Latency drops to milliseconds, the poll storm evaporates, the demo lands.
Then you add a second instance behind the load balancer — because one box is one blast radius. And half your alerts silently disappear.
Nothing errors. No exception, no 500, no log line that says "delivery failed." The result commits on instance B, instance B publishes the alert… into its own process memory, where it checks its own list of open connections and finds nothing, because the recipient's socket is held by instance A. The message has nowhere to go, so it goes nowhere. Quietly. Clinicians don't file a bug that says "your fan-out is broken across instances"; they just stop trusting the alert badge, which is worse, because now your realtime feature is actively making a safety-critical product feel unreliable.
Here is the uncomfortable lesson, and it's the spine of the chapter: every layer before this one assumed a request maps to a response and the server forgets you afterward. Realtime requires the server to remember which human is reachable through which TCP connection on which process. That is exactly the state your load balancer and your horizontal-scaling instincts are designed to destroy. The load balancer's whole job is to make instances interchangeable; realtime makes them non-interchangeable, because the connection — the mailbox — lives on precisely one of them.
There's an economic shift hiding in here too. In the request/response world, a connection is free and ephemeral: open, transfer, close, gone. In the realtime world, a connection is a held resource you pay for whether or not data ever flows through it. Each one is an open file descriptor — the OS's numbered handle for one open connection, like a slot in a fixed-size table the kernel keeps; run out of slots and nobody new can connect — plus a chunk of kernel send/receive buffer, and a slice of heap for whatever you track per user. A hundred thousand idle connections — zero messages, zero throughput — is still a hundred thousand file descriptors and gigabytes of memory. (It's the server-side cost of every open EventSource or WebSocket a browser tab holds — but paid in the server's OS, not the tab.) Capacity is no longer "how many requests per second can I serve"; it's "how many humans and devices can I hold open at once before I run out of fds or RAM." That's a different question with a different ceiling, and most engineers meet it the hard way.
🧭 A useful distinction. "Realtime" is not a feature you bolt on; it's a change of model. Request/response is the client pulling on a string. Realtime is the server holding the other end of the string and tugging when it has news. The moment you hold that string open, you've signed up for connection state, fan-out routing, and backpressure — three problems that don't exist in pull, and don't go away once you're in push.
2. The mental model: mailboxes, routers, and the connection nailed to one process
Hold a few pictures in your head; we'll reuse them for the rest of the chapter.
Producer, router, transport
Tutorials smush realtime into one blob — "open a socket, send a message" — and that's exactly why their code falls over the moment you scale. Production separates three actors, and you should too:
- The producer of an event. "A critical result was posted." This is just your normal backend logic — the same domain event you'd already put on a log. It knows what happened. It does not, and should not, know who is connected where.
- The router. Given an event and its intended audience, it answers: which connections care about this, and which process holds each one? This is the brain, and it's the part that has to span instances.
- The transport. The thing that physically writes bytes to a client's socket. WebSocket frame, SSE chunk — this is the dumb pipe at the very end.
Keep these separate in your head and most of the chapter's complexity sorts itself into the right bin. The backplane you'll build is the router's reach across instances, nothing more.
A connection is a mailbox nailed to one process
This is the single most important sentence in the chapter, so I'll say it plainly: a connection is a mailbox nailed to exactly one specific process. When a clinician's browser opens a socket, that socket is a kernel object living inside one Node process on one instance. There is no "the user's connection" in the abstract — there is a file descriptor on instance A, full stop. Any event destined for that user must first be delivered to instance A, and only then written to the socket. The entire reason a backplane exists is to answer the question "which instance holds this mailbox, and how do I get my message to it?"
producer (critical result posted on instance B)
│
▼
router: "who cares about user 42, and where is their mailbox?"
│
│ user 42's mailbox is nailed to instance A
▼
┌──────────── how does B reach A? ────────────┐
│ THE BACKPLANE │ ← the whole problem
└──────────────────────────────────────────────┘
│
▼
transport: instance A writes the frame to user 42's socket
Two fan-outs, kept distinct
There are two different "send to many" problems here, and conflating them is a classic source of confusion:
- Fan-out across instances (cluster routing). The recipient's socket might be on any instance. This is the backplane's job.
- Fan-out across a user's devices and tabs. One human is often many sockets — phone, workstation, three open tabs on the floor. This is your connection registry's job: a map from
userIdto a set of sockets, all of which should receive the message.
These are orthogonal. The backplane gets the event to the right instances; the registry gets it to the right sockets on each instance. Solve them separately.
Presence is a cache that lies
"Who's online" feels like it should be a fact, but it's derived state — a projection of "which mailboxes are currently held" onto users. Treat it as a cache that can be stale and will occasionally lie, because the event that would correct it (a disconnect) is precisely the event most likely to be lost when someone's phone dies in a stairwell. More on this in §3; for now, just file presence under eventually-consistent, self-healing, never under source of truth.
🧭 Mental model. The server now keeps a switchboard: a live map of which humans are reachable through which sockets on which process. Producers don't push to users; they push to the switchboard, which routes. Once you see realtime as "operating a switchboard across a fleet" rather than "sending messages over a socket," the load balancer, the backplane, and presence all snap into their correct places — they're all just parts of the switchboard.
🚫 A framing this book rejects. "WebSockets are realtime, so use WebSockets." This skips the entire requirements step (§3) and pre-pays for bidirectional complexity you usually don't need. Realtime is a set of requirements — latency, direction, delivery guarantee — and the transport is derived from them, not chosen by reputation. Most "we need WebSockets" claims, examined honestly, need SSE.
3. Theory & invariants: requirements first, then the transport ladder
A mental model tells you how to picture realtime. Invariants tell you what must stay true once you ship it. Start with the requirements, because they decide everything downstream.
The realtime requirement spectrum
Before you write a line of socket code, pin down three independent dials. Almost every bad transport decision comes from skipping this:
- Latency budget. Is this sub-100ms (co-editing feels broken at 300ms; live cursors at 50ms) or "within a few seconds is fine" (a critical-result alert)? Pulsely alerts are the latter. That difference alone often decides the transport.
- Direction. Server→client only, or genuinely bidirectional? Alerts, worklist updates, presence, live vitals dashboards — all one-way pushes. Secure clinical chat, typing indicators, collaborative note editing, live-cursor co-charting — bidirectional. Be honest: "the client occasionally POSTs something" is not bidirectional realtime; that's just a normal HTTP request alongside a one-way stream.
- Delivery guarantee. Best-effort (a dropped presence blip is fine), at-least-once (you must not lose a critical-result alert), or ordered (event N must not appear before N−1)? This is the dial people forget, and it's the one that bites.
Pin all three before choosing a transport. Pulsely alerts: a few seconds of latency, server→client only, at-least-once-with-DB-backup. Read that back and notice it does not require a full-duplex socket.
The transport taxonomy is a derivation, not a menu
Don't memorize four options as equals. Derive them as a ladder where each rung removes one specific cost of the rung below it:
short-polling ──▶ long-polling ──▶ SSE ──────────▶ WebSocket
"ask repeatedly" "ask, server "one HTTP "full-duplex after
wasteful empty holds open response an HTTP upgrade;
responses, until data or streamed client can speak
high latency" timeout, then forever, too; the binary
re-ask" server→client" framed protocol"
each rung removes ──▶ the empty ──▶ the repeated ──▶ the one-way
the cost of: responses re-request limitation
- Short-polling: the baseline you already saw fail — a fresh HTTP request on a timer, mostly returning nothing.
- Long-polling: the client makes a request and the server holds it open until there's data or a timeout, then the client immediately re-requests. This removes the empty responses but keeps a request-per-message and churns connections through proxies. It's the universal-compatibility fallback (and, not coincidentally, what Socket.IO degrades to when nothing better works).
- SSE (Server-Sent Events): one HTTP response that never ends — the server streams events down it forever. Removes the repeated re-request entirely: open once, receive many. It's plain HTTP, one-directional (server→client), and — crucially — the browser's built-in
EventSourcehandles reconnection and resumption for you. Half of this chapter's ADR is "SSE gives you reconnect-with-replay nearly for free." - WebSocket: after an HTTP handshake that upgrades the connection, you get a full-duplex byte pipe — both sides can send, anytime, with low per-message overhead. Removes the one-way limitation. The cost is that it's no longer HTTP after the upgrade, which complicates every proxy, gateway, and load balancer in the path.
The senior move is to climb only as high as your requirements force you. One-way alerts stop at SSE.
Invariants you cannot violate
🔑 A socket write is not a delivery. When you write bytes into a socket's send buffer, you have handed them to the kernel, not to the human. The TCP connection may be half-open — the clinician's laptop closed its lid, the tablet lost signal — and your end won't know for minutes (until TCP's own timers give up, default measured in hours). "Fire into the socket and assume it arrived" is best-effort, period. Anything stronger requires the receiver to acknowledge, and you to be able to replay what they missed.
🔑 The resumption invariant. A client that reconnects must be able to say "the last event I saw was N," so the server can replay the gap (N+1 onward). SSE bakes this in: every event can carry an
id:, the browser remembers the last one, and on reconnect it sendsLast-Event-IDautomatically. Without some cursor — SSE's or your own — every reconnect is a silent data-loss window, and reconnects are not rare; they're the steady-state behavior of mobile clients on flaky hospital Wi-Fi.
🔑 Ordering is not free across the seams. A single connection preserves the order you wrote things. But across a reconnect, across the backplane, and across a user's multiple devices, order is not guaranteed. If "result ready" must not appear before "order placed," you need sequence numbers and client-side dedup — you cannot lean on the socket being a totally-ordered, exactly-once pipe, because it isn't once more than one connection or one hop is involved.
🔑 Presence must self-heal from heartbeats, never from disconnect events. Derive "online" from a TTL'd heartbeat the client refreshes, so that "online" expires if the heartbeats stop. Never derive it from "I saw a connect, I'll wait for the matching disconnect" — because the disconnect is the single event most likely to be lost (crash, partition,
kill -9, dead battery). If your presence depends on a clean goodbye, it will accumulate ghosts: clinicians shown online who logged off ten minutes ago.
🔑 The backpressure invariant. Your send rate to a client is bounded by that client's drain rate. A slow consumer that can't keep up will cause your per-connection outbound queue to grow — and an unbounded outbound queue is not a feature, it's an out-of-memory crash on a timer. Bound the queue. When it's full, you drop messages or disconnect the laggard. There is no third option that doesn't eventually OOM the instance.
📎 Borrowed on credit: token revocation. Notice the resumption and ordering invariants assume the connection is authorized the whole time it's open — but a connection can outlive the token that opened it, and tokens get revoked (logout, role change, offboarding). We'll use re-validation and forced eviction operationally in §5 and §8, but the real mechanics of tokens, revocation lists, and OAuth are owned by Ch 32. Here, take the assertion on credit: a long-lived connection's authorization is a thing you must actively re-check, not a one-time gate.
4. Under the hood: handshakes, frames, the registry, and the backplane
Let's kill the magic, one mechanism at a time. We'll go protocol → process → fleet, because that's the order the bytes travel.
The WebSocket handshake
A WebSocket connection is born as a normal HTTP/1.1 GET request — that's the trick that lets it traverse existing HTTP infrastructure. The client sends:
GET /ws HTTP/1.1
Host: api.pulsely.health
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
The server, if it agrees, replies not with 200 but with:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
That 101 Switching Protocols is the moment everything changes. The Sec-WebSocket-Accept is a SHA-1 hash of the client's key plus a fixed magic string — a handshake proof, not a security measure. After the 101, the bytes on that TCP socket are no longer HTTP. They're a framed binary protocol, full-duplex, on the same connection. Every proxy in the path that doesn't understand Upgrade will either strip it (and you get a 200 or a 426 Upgrade Required instead of 101 — a classic "works locally, breaks behind the proxy" bug) or buffer the stream (and break it more subtly). This is why "enable WebSocket passthrough" is a recurring incantation in load-balancer configs.
WebSocket frames and the dead-peer problem
Post-handshake, data travels in frames with opcodes: text, binary, close, ping, pong. Two details earn their keep:
- Masking. Every frame the browser sends is scrambled with a throwaway key — a simple XOR, not real encryption. Why bother? An old, WebSocket-unaware proxy sitting in the middle could otherwise mistake your message's bytes for a brand-new HTTP request and cache the wrong thing. Scrambling those bytes makes that impossible. You'll never write this yourself — the library does it — but this is why one occasionally complains about masking.
- Ping/pong control frames. This is how you detect a dead peer. TCP's own keepalive is far too slow (hours by default), so the protocol gives you application-level ping/pong: you send a ping, a live client's stack auto-replies pong, and a missed pong tells you the connection is dead long before the kernel figures it out. Heartbeats (§5) are built on this.
The lifecycle is a small state machine — CONNECTING → OPEN → CLOSING → CLOSED — with close status codes you'll learn to read like a clinician reads a chart: 1000 normal, 1001 going away (server shutting down), and 1006 abnormal — no close frame was received. You will see 1006 constantly. It means the connection died ungracefully — the client crashed, the network dropped, a proxy timed it out — without the polite close handshake. A 1006 spike after a deploy is your reconnect storm; a steady 1006 background rate is your flaky-mobile-network tax.
SSE under the hood — and why it's nearly free
SSE is almost embarrassingly simple, which is its superpower. The server responds with Content-Type: text/event-stream and just… keeps writing, in a tiny line format:
id: 1042
event: alert
data: {"type":"critical-result","observationId":"obs-8841","test":"potassium","value":6.8,"loinc":"2823-3"}
id: 1043
event: presence
data: {"userId":"u_77","status":"online"}
Each block is one event (a blank line terminates it). The browser's EventSource does the rest for you: it auto-reconnects on drop, and on reconnect it sends back the last id: it saw as a Last-Event-ID request header — handing you, the server, exactly the cursor you need to replay the gap. You also get retry: to suggest a reconnect delay. Compare that to WebSockets, where reconnection, backoff, and resumption are all your code. This near-free resumption is half the reason the Pulsely ADR lands on SSE.
Here's a minimal Pulsely SSE alert stream in Node/TS. Note how thin it is — and how the resumption hook is just reading a header:
// GET /alerts/stream — one HTTP response, streamed forever.
app.get('/alerts/stream', authConnection, async (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform', // no-transform stops proxies buffering
Connection: 'keep-alive',
});
res.flushHeaders();
const userId = req.user.id;
const lastSeen = Number(req.headers['last-event-id'] ?? 0);
// Resumption: replay anything this user missed while disconnected.
for (const ev of await alertStore.since(userId, lastSeen)) {
res.write(`id: ${ev.seq}\nevent: alert\ndata: ${JSON.stringify(ev.payload)}\n\n`);
}
// Register this live mailbox so the router can reach it.
const conn = registry.add(userId, res);
// App-level heartbeat: a comment line keeps the pipe warm and proves liveness.
const beat = setInterval(() => res.write(': ping\n\n'), 25_000);
req.on('close', () => { clearInterval(beat); registry.remove(userId, conn); });
});
The connection registry — and why it's stuck on one instance
The registry above is the heart of per-instance routing. It's just an in-process map:
// In-process only. Each instance has its OWN registry. This is the whole problem.
class ConnectionRegistry {
private byUser = new Map<string, Set<Connection>>(); // one user → many sockets/tabs
add(userId: string, res: Response): Connection {
const conn = { res, queue: [] as string[] }; // per-connection outbound buffer
(this.byUser.get(userId) ?? this.byUser.set(userId, new Set()).get(userId)!).add(conn);
return conn;
}
remove(userId: string, conn: Connection) {
this.byUser.get(userId)?.delete(conn);
}
// Deliver to every socket THIS instance holds for the user (the per-device fan-out).
deliverLocal(userId: string, frame: string) {
for (const conn of this.byUser.get(userId) ?? []) writeBounded(conn, frame);
}
}
This map lives in one process's heap. Instance A's registry knows nothing about instance B's sockets, and never will. That's not a flaw to fix — it's an inherent property of "a mailbox is nailed to one process." Which is exactly why an event produced on B can't be delivered by B if the recipient is on A. We need a way for B to announce the event to all instances and let whichever instance holds the mailbox do the actual write.
🛑 What we deliberately did not explain. How the kernel turns a socket into an event-loop readiness notification (epoll/kqueue — that's Ch 4 and Ch 8). How Node's stream backpressure (
res.writereturningfalse, thedrainevent) works under the hood — Ch 8 owns Node streams; here we only use the result to bound a queue. How TLS wraps the whole thing — Ch 6. We're located on those mechanisms; we didn't reopen them.
The Redis backplane: publish once, every instance filters locally
Now the payoff. We use Redis pub/sub (which you've already met) as the router's reach across the fleet. The pattern is "publish once, every instance filters locally":
critical result posted on instance B
│
▼ PUBLISH alert:user:42 {payload}
┌──────────────────┐
│ REDIS │ (pub/sub: fire-and-forget broadcast)
└──────────────────┘
│ │ │
┌────────┘ │ └────────┐
▼ ▼ ▼
instance A instance B instance C
SUBSCRIBE SUBSCRIBE SUBSCRIBE
alert:user:* alert:user:* alert:user:*
│ │ │
holds u42's holds nothing holds nothing
socket → WRITE → ignore → ignore
Every instance subscribes. Every instance receives every published event for its subscriptions. Each one then checks its own registry: do I hold a socket for this user? If yes, write the frame; if no, drop it on the floor. The producer (instance B) doesn't need to know where user 42 is — it shouts the event to everyone, and the one instance that holds the mailbox does the delivery.
// On every instance, at startup:
const sub = redis.duplicate(); // a dedicated connection for SUBSCRIBE
await sub.psubscribe('alert:user:*');
sub.on('pmessage', (_pattern, channel, message) => {
const userId = channel.slice('alert:user:'.length);
registry.deliverLocal(userId, toFrame(JSON.parse(message))); // local filter
});
// When a critical result is posted (anywhere):
await redis.publish(`alert:user:${recipientId}`, JSON.stringify(payload));
Now the critical design choice the ADR turns on. Redis pub/sub is fire-and-forget: if an instance isn't subscribed at the instant of publish, or Redis fails over mid-message, that message is gone — no persistence, no replay. That's perfectly fine for presence blips and for alerts that are also persisted to the database (the realtime push is an optimization; the DB row is the truth). It is not fine if the socket is your only copy of an important event — and in healthcare, a critical-value alert is exactly that kind of event.
The alternative is Redis Streams (conceptually the log you've already met, in miniature): the stream persists events, supports consumer groups, and lets you replay from an offset — at-least-once instead of best-effort. The price is that you now own offset bookkeeping and trimming. Past that sit real brokers — NATS, Kafka — with serious throughput and durability and serious operational weight. The ADR's job is to pick the cheapest rung that meets the delivery requirement.
🏭 Node's single event loop is a realtime-specific footgun worth naming here. One slow synchronous handler — a heavy JSON parse, a synchronous crypto call, a tight loop over thousands of connections in the broadcast path — blocks every connection on that instance, because there's one thread serving all of them. In request/response this shows up as a latency blip; in realtime it shows up as every user's stream stuttering at once. Never do synchronous work in the fan-out loop, and never
awaita slow operation while holding up delivery to others.
5. In production: heartbeats, deploys, the backplane, and the Pulsely path
The mechanics above are the teaching version. Here's what actually keeps a realtime fleet alive at 3am.
Heartbeats you actually run
Do not trust TCP keepalive (default ~2 hours) or the load balancer's idle timeout to clean up dead sockets — both are far too coarse, and a leaked connection is a leaked file descriptor that never comes back until you restart. Run an application-level heartbeat: every ~25–30 seconds, send a ping (WebSocket ping frame) or a comment line (SSE : ping). If a client misses N consecutive pongs, evict it — close the socket, free the fd, remove it from the registry, fire the presence-offline path. This is the only reliable way to reclaim half-open connections before they accumulate into an OOM over days of uptime.
Graceful shutdown: the deploy story nobody mentions
Here's the one tutorials skip entirely. You deploy. SIGTERM hits an instance holding 30,000 connections. If you just exit, all 30,000 clients see a 1006 abnormal close at the same instant and all reconnect at the same instant — a thundering herd that slams CPU on the surviving instances and can brown out the deploy. The correct shutdown sequence:
- On SIGTERM, stop accepting new connections (fail the readiness check so the LB stops routing to you).
- Send each held client a close/reconnect hint with a jittered backoff — "reconnect in a random 1–10s" — so the herd spreads over time instead of stampeding.
- Drain in-flight work, then exit.
The jitter is the whole trick. 30,000 reconnects spread over ten seconds is 3,000/s; the same 30,000 in one instant is a self-inflicted DoS.
Load balancer config that actually matters
- The LB idle timeout must exceed your heartbeat interval, or the LB will helpfully kill connections it thinks are idle — and you'll see exactly that
1006-every-60-seconds pattern that screams "LB timeout shorter than heartbeat." - Enable
Upgrade/Connectionheader passthrough for WebSockets, and disable response buffering for SSE (a buffering proxy will hold your stream and deliver it in one lump, silently breaking realtime). - Sticky sessions: WebSockets need stickiness for the handshake-to-same-process guarantee once a connection is established. Put plainly: once a browser is talking to instance A over a live socket, every later byte has to keep landing on instance A — the load balancer can't reshuffle it mid-conversation the way it freely does with normal HTTP requests. The bytes must keep flowing to the exact process that completed the WebSocket handshake (the
101 Switching Protocolsresponse from earlier). SSE plus a backplane can sometimes avoid stickiness entirely, since any instance can serve the stream and the backplane reaches whichever one holds it.
The Pulsely alert path, end to end
Here's the increment wired together — and notice where the durable truth lives:
critical result posted ─▶ PERSIST alert row in Postgres (the source of truth)
│
▼
PUBLISH alert:user:42 on Redis
│
┌─────────────┴─────────────┐
▼ ▼ ▼
instance A instance B instance C (all SUBSCRIBE)
│
holds u42's socket ─▶ write SSE frame ─▶ client renders badge, acks via Last-Event-ID
The non-negotiable rule: persist the alert to the database first, then push. Realtime is an optimization on top of durable state, never the only copy. If the clinician is disconnected when the result lands, the push goes nowhere — and that's fine, because on their next page load they fetch unacknowledged alerts from the DB. The push makes it instant when they're online; the DB makes it correct when they're not. Lose this and a single dropped Redis message becomes a permanently lost alert — and a missed realtime push must never be a lost clinical alert. That's not a UX nicety here; it's patient safety and the reason persist-first is non-negotiable in a health system.
Presence in practice
Heartbeats double as the presence mechanism. Each heartbeat sets a Redis key with a TTL of ~2.5× the heartbeat interval:
// On each heartbeat from user 42:
await redis.set(`presence:user:42`, '1', 'EX', 75); // 30s heartbeat → 75s TTL
// "online" = key exists. It EXPIRES on its own if heartbeats stop — self-healing.
// "last seen" is a separate timestamp, updated on heartbeat and on clean disconnect.
Online means the key exists. If the client vanishes — crash, stairwell, kill -9 — the heartbeats stop, the key expires, and presence flips to offline automatically, with no disconnect event required. That's the self-healing property from §3 made concrete. Fan presence changes out only to interested parties (the rest of that patient's care team), not globally — a global presence firehose is how you accidentally build an O(users²) broadcast.
🛑 What we deliberately did not explain here. The full reliability story — circuit breakers around the backplane, retry budgets, what your SLO for delivery latency should be — is Ch 33. The observability story — how you actually trace a publish→client-ack across instances, what dashboards catch a presence flap — is Ch 34. We name the metrics you need next; we don't build the telemetry pipeline here.
The metrics that earn a dashboard: open connections per instance (your capacity gauge), message send/drop counters, per-connection send-queue depth (your backpressure early-warning — a climbing queue means a slow consumer before it OOMs you), reconnect rate (spikes = a deploy or an LB problem), end-to-end delivery latency (publish → client ack), and presence flap rate (thrashing means your TTLs are wrong).
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Alerts vanish after scaling past one instance. Signature: works flawlessly on one box; you add a second behind the LB and roughly half of all alerts silently stop arriving — no errors, just missing messages. Fix: add a backplane. The publishing instance rarely holds the recipient's socket; publish the event to all instances and let the one holding the mailbox deliver it. This is the defining realtime bug and the reason this chapter exists.
File descriptors and memory climb forever; the instance OOMs after days. Signature: a slow leak — fd count and heap grow with uptime even though active users are stable; eventually the box dies. Fix: app-level heartbeats with missed-pong eviction. You're leaking half-open connections that TCP never reaped because its keepalive is measured in hours. Reclaim them yourself.
Clients drop every ~60 seconds with code 1006. Signature: a metronomic disconnect-reconnect cycle, always abnormal close, always at the same interval. Fix: your LB's idle timeout is shorter than your heartbeat interval, so the LB kills the "idle" connection. Raise the LB timeout above the heartbeat, or lower the ping interval below the timeout.
A deploy spikes CPU to 100% and a reconnect storm browns out the new instances. Signature: every deploy causes a thundering-herd of simultaneous reconnects; the fresh instances buckle under the synchronized load. Fix: jittered exponential backoff on the client plus staggered, hinted close on graceful shutdown. Spread 30k reconnects over ten seconds instead of one instant.
Alerts duplicate or arrive out of order after a reconnect.
Signature: after a flaky-network blip, a clinician sees the same alert twice, or "result ready" before "order placed."
Fix: sequence numbers + Last-Event-ID/cursor replay + client-side dedup. The socket is not a totally-ordered, exactly-once pipe once a reconnect or the backplane is in the path. Make duplicates boring and gaps replayable.
Presence shows clinicians "online" who logged off ten minutes ago. Signature: ghost users in the online list; "seen just now" for someone who closed the tab long ago. Fix: stop trusting disconnect events; derive presence from a TTL'd heartbeat so missing the disconnect self-heals. The disconnect is the event most likely to be lost — never make correctness depend on receiving it.
One slow client degrades everyone (Node).
Signature: a single user on a terrible connection, and suddenly every connection on that instance stutters.
Fix: never await or block in the broadcast loop; use a bounded per-connection outbound queue and drop-or-disconnect the slow consumer when it fills. One slow drain must not become everyone's problem — that's the single-event-loop tax.
The WebSocket upgrade returns 200 or 426 instead of 101 behind a proxy.
Signature: works direct, fails through the load balancer or gateway; the handshake never completes.
Fix: enable Upgrade/Connection passthrough on the proxy. A buffering proxy silently breaks SSE the same way — disable response buffering / set no-transform.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
SSE ↔ WebSocket (the first ADR).
SSE wins for server→client-only delivery: it's plain HTTP, it gives you free reconnect and resumption via EventSource/Last-Event-ID, it sails through proxies and gateways that choke on Upgrade, and it never makes the load balancer a correctness participant the way a sticky WebSocket does. WebSocket wins when you genuinely need bidirectional or sub-100ms client→server traffic — secure clinical chat, typing indicators, collaborative charting, live-cursor co-editing. You'd reverse the choice the moment Pulsely adds client→server realtime; until then, don't pre-pay full-duplex complexity for one-way alerts.
Long-polling ↔ SSE ↔ WebSocket. Long-polling is the universal-compatibility fallback (and what Socket.IO degrades to when nothing better is available). Its cost is a fresh HTTP request per message and constant connection churn through proxies. It's correct as a fallback, wrong as a default — reach for it only when you must support an environment that breaks SSE and WebSockets both.
Backplane: Redis pub/sub ↔ Redis Streams ↔ a broker (the second ADR). Pub/sub is simplest and lowest-latency with zero durability — messages in flight during a failover are simply lost, which is acceptable for presence and for alerts-that-are-also-in-the-DB. Streams add replay and at-least-once delivery at the cost of offset bookkeeping. Kafka/NATS bring serious throughput, durability, and multi-region — and serious operational weight you don't need yet. You'd reverse toward Streams or a broker the day delivery guarantees, replay, or multi-region cross the requirement line.
Sticky sessions ↔ stateless routing. Stickiness simplifies the per-instance registry (a user's connection always lands on the process it handshook with) but undermines even load distribution and complicates draining on deploy. A backplane lets you lean less on stickiness. The real tradeoff is registry complexity vs LB complexity — you're paying one or the other.
Stateful realtime ↔ polling. Realtime cuts latency and DB load but buys you held state and a genuinely harder scaling and ops story. For low-frequency, latency-tolerant updates, polling — or even just refresh-on-navigation — is the correct senior choice, not a cop-out. If the data changes twice an hour and "within a minute" is fine, holding 100k sockets open to save a few cheap polls is bad engineering dressed up as sophistication. Match the machinery to the requirement. (The exception that proves the rule: a critical-value alert is neither low-frequency nor latency-tolerant when it fires — that's exactly why it earns a push channel.)
In-process rooms ↔ externalized routing. Socket.IO "rooms" are fast and ergonomic — but they're an in-memory map that evaporates on restart and doesn't cross instances without an adapter. Externalizing routing to the backplane is simply the price of horizontal scale; the in-process version is a single-box convenience that lies about being production-ready.
8. Security & scale notes
Security and scale aren't a separate chapter; they're properties of every connection you hold. And in Pulsely every frame you push is PHI — a socket write is subject to the same minimum-necessary and audit rules as a GET on a chart.
Authenticating a connection you can't put a header on. The browser's EventSource and WebSocket constructors cannot set custom headers — you can't just attach Authorization: Bearer …. The standard patterns: (1) issue a short-lived signed ticket over a normal authenticated request, then pass it as a query param (/ws?ticket=…) or as the first message after connect; (2) cookie-based auth on the handshake, with SameSite/CSRF care; and critically (3) re-validate periodically, because a connection opened an hour ago may now belong to a clinician who logged out, changed roles, or was offboarded.
The revocation problem is unique to realtime. A stateless token is checked once at handshake — but the connection outlives the token. You therefore need a way to forcibly evict sockets on logout, role change, or offboarding: publish a kill:user:42 message over the backplane, and every instance holding that user's sockets closes them. Without this, "log out everywhere" and "revoke this account's access" are lies for the lifetime of the open connection — and in a HIPAA system, a socket still streaming PHI to a revoked account is a live compliance problem.
📎 Borrowed on credit: the token mechanics themselves. How that ticket is signed and verified, how a revocation list or short-token-TTL scheme actually works, the OAuth flows behind it — all Ch 32. Here we use auth operationally (validate at handshake, re-check periodically, evict on revocation) and defer the why and the cryptographic detail.
Authorize every event, not just the connection. Holding a socket is not entitlement to a given message. Filter at fan-out so clinician A never receives clinician B's patient's alert even if a topic is misrouted or a bug widens a channel. "They're connected, so they can see it" is exactly the trust-boundary violation you already know to reject — just at the message level. And here it has real teeth: one patient's alert delivered to the wrong clinician is a PHI disclosure to an unauthorized recipient, a reportable HIPAA breach, not a cosmetic bug. Enforce minimum-necessary on the frame, and log the delivery — every pushed PHI event belongs in the same immutable audit trail as every chart view.
The threat surface of holding connections open. A socket is cheap to open and expensive to hold — a gift to attackers. Defenses: per-IP and per-user connection caps, auth before upgrade (don't 101 an anonymous client), and rate-limited reconnects. Watch for Slowloris-style and slow-consumer attacks (clients that open and never drain, forcing your outbound queues to grow — the backpressure invariant is also a security control). And validate the Origin header on the handshake to stop CSWSH (cross-site WebSocket hijacking) — WebSockets are not bound by same-origin/CORS the way fetch is, so a malicious page can open a socket to your API with the user's cookies unless you check Origin yourself.
Scale ceiling honesty. Be able to state your limits before you hit them. The vertical ceiling is file descriptors plus memory-per-connection — realistically tens of thousands of mostly-idle connections per instance, not millions; do the arithmetic (fds available, heap per connection) and know the number. This matters most for the RPM firehose, where each monitoring device is its own held connection streaming vitals. The horizontal ceiling is the backplane's fan-out cost: naive pub/sub is O(instances) per event — every instance receives every message and filters locally, so adding instances increases per-event work. Past a point you need topic sharding (partition channels so not every instance hears everything), a tiered/edge connection layer, or a dedicated realtime service. Know which limit you'll hit first and at what scale.
Graceful degradation order under load. When the realtime tier saturates, degrade in this order: shed new connections before dropping existing ones, drop the slowest consumers first, and fall back to polling when the tier is overwhelmed. The alert badge being a few seconds stale beats the whole fleet OOMing. A realtime system that can't gracefully become a polling system under stress is a realtime system that takes the product down with it — and taking a clinical alerting product down is not an outage you want to explain.
9. Interview lens & exercises
Interview questions
"Realtime alerts work on one server; you add a second behind a load balancer and half of them stop arriving. What's happening, and how do you fix it?" The defining question of this chapter.
- Junior answer: "Add sticky sessions." (Which doesn't help — stickiness pins a user's own connection to a process; it does nothing for cross-user fan-out, where the producer is on a different instance than the recipient's socket.)
- Senior answer: names the per-instance connection registry, explains that the recipient's socket is a mailbox nailed to the other box, and introduces a backplane (publish once, every instance filters locally) — then discusses pub/sub vs Streams based on whether the alert needs durability or is DB-backed.
"SSE or WebSockets for an alert feed — defend your choice."
- Junior: "WebSockets, they're realtime."
- Senior: asks for the three requirements first — direction, latency, delivery guarantee — observes that alerts are server→client, seconds-tolerant, and DB-backed, and picks SSE for its free resumption and proxy-friendliness, naming the exact condition (client→server realtime) that would flip the decision to WebSocket.
"How do you know a connection is still alive, and how do you authenticate one that lives for hours?"
- Junior: "The socket fires a close event" / "check the JWT at connect."
- Senior: app-level heartbeats with missed-pong eviction (TCP keepalive is far too slow); short-lived ticket at handshake plus periodic re-validation plus backplane-driven forced eviction on revocation, because the connection outlives the token.
"How many connections can one instance hold, and what breaks first?"
- Junior: "Just scale horizontally." (No ceiling reasoning.)
- Senior: fds and memory-per-connection set the vertical ceiling (tens of thousands, with the arithmetic to back it); then backplane fan-out cost — O(instances) per event — sets the horizontal one, with topic sharding named as the next step.
"A slow client on a Node server is degrading everyone — why, and what do you do?"
- Junior: "Add more servers." (Which spreads the problem, not fixes it.)
- Senior: single event loop plus an unbounded outbound queue; fix with bounded per-connection queues, drop-or-disconnect the slow consumer, and backpressure metrics on send-queue depth.
Exercises & the Pulsely increment
Build these for real; realtime bugs only appear under the conditions tutorials never set up (a second instance, a reconnect, a slow client).
-
SSE alerts with replay. Implement Pulsely realtime alerts via SSE for
critical-result,care-team-assignment, andresult-available. Persist each alert to the DB first, then push. Prove resumption: disconnect a client mid-stream, fire two events while it's away, reconnect, and verify both arrive viaLast-Event-IDreplay with no duplicates and no gaps. -
Cross-instance backplane. Add a Redis pub/sub backplane and run two Pulsely instances behind a local NGINX. Connect a client through instance B, publish an event from instance A, and prove it arrives. Then remove the backplane and watch it vanish — make the bug reproducible, because that's how you'll recognize it in production.
-
Self-healing presence. Build care-team presence with TTL'd heartbeats (
presence:user:{id}, TTL ≈ 2.5× heartbeat). Connect several clinicians, thenkill -9an entire instance — without any clean disconnect — and confirm those users flip to offline automatically as their keys expire. Then add "last seen Nm ago" from a separate timestamp. -
Write both ADRs. (a) SSE vs WebSocket for the alert channel: requirement-driven (direction/latency/guarantee), chosen SSE, with an explicit "we'd reverse this when Pulsely adds secure clinical messaging / live care-team chat" trigger and the WebSocket upgrade path left open. (b) Backplane choice: Redis pub/sub vs Streams vs broker, chosen pub/sub (alerts are DB-backed, so lost-on-failover is acceptable; presence is best-effort by nature), with the "reverse toward Streams when we need replay/at-least-once" trigger recorded.
-
Backpressure under a slow consumer (stretch). Add a client that never drains its socket. Implement a bounded per-connection send queue that drops-and-disconnects when full, and graph send-queue depth over time so you can see backpressure engage before the instance is endangered.
Key takeaways
- Realtime inverts the model: the server speaks first to a specific human reachable through a held connection. That breaks statelessness on purpose — and turns your fleet into a distributed routing problem.
- A connection is a mailbox nailed to one process. Any event for a user must reach that instance first. The backplane exists solely to solve "which instance, and how do I reach it?"
- Requirements before transport. Pin direction, latency budget, and delivery guarantee; then climb the ladder (short-poll → long-poll → SSE → WebSocket) only as high as those force you. One-way alerts stop at SSE, whose free reconnect-with-replay (
Last-Event-ID) is a real advantage. - A socket write is not a delivery; the peer may be half-open. Ordering and exactly-once are not free across reconnects, the backplane, or a user's many devices — use sequence numbers, cursors, and client dedup.
- Persist first, then push. Realtime is an optimization on top of durable state, never the only copy. A dropped Redis message must never be a lost clinical alert.
- Presence self-heals from TTL'd heartbeats, never from disconnect events — because the disconnect is the event most likely to be lost.
- Bound every outbound queue (backpressure), run app-level heartbeats (dead-peer detection), and drain gracefully with jitter on deploy. Connections are held resources you pay for whether or not data flows.
- Know your ceilings before you hit them: vertical = fds + memory-per-connection (tens of thousands/instance); horizontal = O(instances) backplane fan-out. Authenticate long-lived connections operationally and re-validate, because the connection outlives its token — and every frame you push is PHI, so authorize the event, not just the socket.
← Previous: Ch 27 — Log-Based Streaming & EDA · Up: Part V overview · Master TOC · Next: Ch 29 — Scalability Building Blocks →