Distributed systems7 min read
Building Resilient Real-Time Streams
Heartbeats, inactivity detection, reconnection with backoff and sequence-gap recovery for SSE and gRPC streams.
Real-time UIs fail in ways that are easy to miss in development. Your laptop never sleeps mid-session, the local server never stalls, and the Wi-Fi never drops for eight seconds. Production users experience all three before lunch.
For a trading interface, a stream that silently stops is worse than one that loudly fails: users act on prices that stopped being true minutes ago. This article covers the four mechanisms that make a stream trustworthy.
1. Treat lifecycle as explicit state
A stream isn't just "connected" or "not". At minimum it moves through:
- connecting — opening the transport
- live — receiving messages
- stale — the connection is open but nothing has arrived for too long
- reconnecting — waiting out a backoff delay before trying again
- recovering — reconnected, fetching what was missed
Making these explicit states (rather than a couple of booleans) means the UI can tell the user exactly what's happening, and each transition can be tested.
2. Detect inactivity
Sockets don't always close when they die. A proxy can drop the connection without either end noticing; a server can stall while keeping the TCP session alive. The only reliable signal is time since the last message.
function armInactivityTimer() {
clock.clearTimeout(inactivityTimer);
inactivityTimer = clock.setTimeout(() => {
transition("stale");
transport.close();
scheduleReconnect();
}, options.inactivityTimeoutMs);
}
function onMessage(message: StreamMessage) {
armInactivityTimer(); // every message — including heartbeats — proves liveness
handle(message);
}If the server publishes heartbeats, the timeout can be tight. If it doesn't, pick a window comfortably longer than the quietest normal period for that stream.
3. Back off, with jitter
When a server restarts, every client loses its connection at the same moment. If they all reconnect immediately — and again after a fixed delay — they arrive in synchronized waves that can knock the server over again.
function nextDelay(attempt: number) {
const ceiling = Math.min(options.maxDelayMs, options.baseDelayMs * 2 ** attempt);
return random() * ceiling;
}Exponential growth limits the rate; randomizing within the window (full jitter) breaks the synchronization. Reset the attempt counter only after the stream has been healthy for a while, not the instant it connects.
4. Recover the gap
Reconnecting restores future messages. It does nothing for the ones sent while you were away. If messages carry a sequence number, the client can tell exactly what it missed:
function onMessage(message: StreamMessage) {
if (message.seq <= lastDelivered) return; // duplicate — drop it
if (message.seq > lastDelivered + 1) {
buffer.set(message.seq, message); // hold out-of-order messages
void recover(lastDelivered + 1, message.seq - 1); // fetch the missing range
return;
}
deliver(message);
drainBuffer(); // deliver anything now contiguous
}The guarantees consumers get are simple and strong: every message, exactly once, in order. If the server can't provide history, the fallback is to fetch a fresh snapshot and resume from its sequence number — still far better than silently skipping updates.
Centralize it
Every stream in an app needs the same behavior, so none of it should live in components. A stream manager owns transports, timers and recovery; components subscribe to data and, optionally, to lifecycle state for a "reconnecting…" indicator. Swapping SSE for gRPC streams becomes a transport change, not a rewrite.