06 — Real-time infrastructure
StreamManager V2
Resilient streaming with automatic reconnection, inactivity detection, exponential backoff and gap recovery.
- SSE
- gRPC
- State Machines
Overview
StreamManager V2 is real-time infrastructure for consuming long-lived data streams — server-sent events and gRPC streams — reliably. It owns connection lifecycles so application code can simply subscribe to data.
The problem
Streams fail quietly. A socket can stay open while the server stops sending. A laptop sleeps and wakes up with a dead connection. A reconnect succeeds, but the messages sent in between are gone. Naive implementations either flood the server with reconnects or show users stale data without any indication.
Engineering challenges
- Silent failure. An open connection doesn't mean a healthy one.
- Reconnection storms. Thousands of clients reconnecting at the same instant can take down the server they depend on.
- Lost messages. Reconnecting is not the same as recovering.
- Many streams, one policy. Order books, trades, positions and balances should all share the same reliability behavior.
Architecture
- Consumers
- Order book
- Trades
- Positions
- Manager
- Subscription registry
- Lifecycle machineconnecting · live · stale · reconnecting · recovering
- Policies
- Inactivity detector
- Backoff + jitter
- Gap recoveryby sequence
- Transports
- SSE
- gRPC stream
Key decisions
Explicit lifecycle states
live, stale, reconnecting and recovering are first-class states, not booleans. The UI can tell users exactly what is happening, and transitions are testable.
Inactivity is a failure
If no message or heartbeat arrives within a window, the stream is considered stale and is recycled — even though the connection never closed.
Exponential backoff with jitter
Reconnect delays grow exponentially and are randomized, spreading reconnects over time instead of synchronizing them.
Recover the gap, don't just reconnect
Messages carry sequence numbers. After reconnecting, missing ranges are fetched, out-of-order messages are buffered, and consumers receive every message exactly once, in order.
Patterns
- State machine for connection lifecycle
- Heartbeat / inactivity detection
- Exponential backoff with full jitter
- Sequence-based gap recovery and de-duplication
- Transport abstraction (SSE, gRPC)