Advanced Concepts · Concept lesson
Realtime Connections: Presence, Backpressure, and Reconnection
Operate long-lived client connections as distributed state with explicit fanout, flow control, heartbeat, and recovery policies.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Distinguish transport connectivity from application delivery and presence.
- Estimate connection capacity and design bounded fanout and backpressure.
- Build reconnect behavior that handles duplicate, delayed, and missed events.
A socket being open does not mean a user received an event
Realtime systems maintain many long-lived transport connections so a server can push updates without waiting for a client to poll. A WebSocket gives bidirectional framed communication over a connection; server-sent events provide a simpler one-way stream; polling can remain adequate when update frequency is modest or infrastructure cannot support long-lived sessions. The transport reports whether bytes can move, not whether a human saw a notification, whether the client persisted it, or whether the business action completed. Separate connection state, application acknowledgement, and durable domain state. If a browser sleeps, a mobile radio changes, or a proxy times out an idle stream, an apparently established connection may stop receiving useful data.
Presence is an estimate, not a fact. A heartbeat every 20 seconds with a 60-second lease might mark a user offline only after three missed periods, which avoids rapid flapping but makes offline status slow to update. Network partitions can make a healthy user appear absent. Multi-device users need a presence set rather than one boolean, and logout should not be inferred solely from a broken socket. Publish presence only when the product has a clear use for it, since online status can reveal behavior and creates privacy expectations. Model a connection with an opaque connection ID, authenticated principal, last-seen time, subscription set, and expiration; do not treat a client-provided user ID as proof of identity.
Authenticate, subscribe, and bound every connection
At connection establishment, authenticate using an established session or a short-lived ticket and validate origin, tenant, and allowed protocol. Recheck authorization when subscriptions change and when sensitive events are delivered; a socket can outlive a permission revocation. Keep credentials out of query strings and connection logs where possible. Apply per-user and per-IP connection limits, message-size caps, subscription quotas, and idle timeouts. A connection server should not keep unbounded per-client history in memory. Persist important events separately and send a sequence number or cursor so a reconnecting client can request a bounded resume window. If that window has expired, send a clear resynchronization instruction rather than pretending no messages were missed.
A broker can distribute events among connection gateways, but routing requires a mapping from user or topic to live gateways. That mapping is ephemeral and may be stale after a node failure. TTL leases, heartbeats, and cleanup make stale subscriptions expire; a shared broker or pub/sub layer carries fanout. A user with ten thousand followers can overwhelm a single gateway if each publish expands in one process. Partition fanout, coalesce replaceable updates, and enforce queue bounds per connection. For each client, choose whether to drop low-priority updates, disconnect a slow consumer, or switch it to snapshot-and-resume. Make that policy explicit. A server should expose the current reconnect cursor but avoid exposing internal node IDs or other users' subscription information.
Capacity planning with connection and fanout math
Assume 100,000 concurrent connections, 32 KiB of application-managed state per connection, and 40% runtime overhead for buffers, TLS state, and bookkeeping. Raw state is 100,000 × 32 KiB = about 3.05 GiB; adding 40% yields roughly 4.27 GiB before operating system and runtime headroom. This is illustrative and must be measured with the actual protocol stack and payload pattern. If each connection sends a 150-byte heartbeat every 25 seconds, the system receives about 4,000 heartbeats per second and roughly 600 KB/s payload before framing and network overhead. Heartbeats themselves can become material write load if every update is persisted. Keep ephemeral lease refreshes in an appropriate low-cost store and avoid turning every ping into a durable database transaction.
Now suppose a popular room emits 2,000 messages per second to 5,000 members. Naive fanout attempts 10 million deliveries per second. Most applications cannot process that in one gateway; the architecture may need room partitioning, coalescing, a snapshot endpoint, or a lower update frequency. If each client can drain only 10 messages per second, queue depth increases by 1,990 messages per second; a 500-item queue fills in about 0.25 seconds. This argues for dropping replaceable state updates or disconnecting slow clients rather than buffering without limit. Measure connection count, reconnect rate, outgoing queue age, dropped/coalesced updates, authorization failures, and end-to-end acknowledged event age. The p99.9 write-to-client latency matters more than a mean when users depend on alerts.
Maintains cursor and reconnects with jitter.
Authenticates and enforces bounded per-client queues.
Checks current access on subscription and delivery.
Distributes transient fanout between gateways.
Retains important events for cursor-based recovery.
Reconciles client state after the resume window expires.
- Client → Connection gateway: authenticated socket / SSE
- Connection gateway → Authorization service: authorize subscription
- Durable event store → Event broker: event notification
- Event broker → Connection gateway: fanout event
- Connection gateway → Client: bounded push
- Client → Durable event store: resume from cursor
- Client → Snapshot API: snapshot if cursor is too old
Choose the least complex push mechanism
Polling is easy to cache, retry, and operate, and can be more efficient than persistent connections for rare changes or small audiences. Long polling reduces empty responses but still requires careful timeout and proxy behavior. Server-sent events work well for one-way server updates with built-in event IDs and browser reconnection support, while WebSocket supports interactive, bidirectional messaging but requires application-level conventions for acknowledgements, heartbeats, and resumption. A managed realtime service may simplify connection gateways and scaling, but creates vendor, region, message-size, and access-policy constraints. A message broker is not itself a client connection service; clients should not receive broad broker credentials.
Compare actual traffic patterns: concurrent connections, events per client, fanout, payload size, acceptable delay, and how much history clients need after a disconnect. If every screen can cheaply refresh a snapshot once a minute, persistent connections may add more operational burden than user value. If an event triggers a financial or safety-critical action, a best-effort socket is not a durable command channel; persist the business event and require an explicit acknowledgement at the domain layer. Realtime delivery should accelerate awareness, while an authoritative API remains available for reconciliation.
Reconnect storms and slow consumers need deliberate recovery
A regional network flap can cause thousands of clients to reconnect together. Use exponential backoff with random jitter, a maximum delay, and a server retry hint. The client should restore authentication, subscriptions, and last acknowledged cursor without replaying an unbounded history. Gate new connections if a gateway is overloaded, and expose a retryable response rather than letting it fail unpredictably. During deployments, drain connections gradually and support rolling reconnects. A client with a stale token should refresh through the ordinary auth flow; do not accept a long-lived socket as proof that an expired credential remains valid.
Slow consumers need bounded queues. When limits are reached, coalesce repeated state updates, drop explicitly lossy events, or disconnect and require a snapshot; never silently drop a durable event while telling the client it is current. For an important notification, store it durably and deliver a cursor that can be fetched after reconnection. Duplicate delivery is expected around reconnect boundaries, so clients deduplicate using event ID or sequence. If a gateway dies, presence leases expire and clients reconnect elsewhere; stale gateway mappings must not route new events into a dead node indefinitely. Test network loss, mobile background suspension, token expiry, full queues, node drain, and broker partition. Recovery should not require operator edits to every session.
When persistent connections are a poor fit
Do not use a socket for an operation that needs a durable audit record but has no server-side persistence. Do not promise delivery just because a message was written to a TCP connection; acknowledgement at the application layer is required for stronger claims. Persistent connections may be unsuitable behind infrastructure with short idle timeouts, for clients that sleep frequently, or where the product has no compelling latency need. They complicate deployment, load balancing, authentication expiry, connection draining, and scaling; polling can be more robust for infrequent updates.
Presence should not be collected simply because it is easy to expose. It can reveal working patterns, relationships, and user activity. Set a clear purpose, retention, visibility controls, and an explanation of what 'online' means. Avoid high-frequency heartbeats that drain mobile batteries or produce unnecessary storage writes. A transport fallback must preserve privacy and authorization, not use a weaker path. For large public broadcasts, per-user sockets may be the wrong distribution mechanism; a CDN-hosted snapshot or coarse-grained update can be more scalable.
Senior questions for realtime design
Ask what 'delivered' means: bytes written, client handler invoked, state persisted, or user action confirmed? What is durable and replayable, and what may be coalesced or dropped? How does a reconnect establish a cursor and recover gaps? What are connection memory and egress costs at peak, and were they benchmarked with TLS and real client behavior? How are heartbeats, presence leases, authentication expiration, and permission revocation handled? What prevents one noisy room or slow client from consuming every gateway's buffers?
Challenge the failure modes: what happens during node loss, deployment drain, broker partition, regional network flap, and a synchronized reconnect storm? Which limits cause rejection, and is the client backoff randomized? Does the product need sockets at all, or would polling meet its latency objective? How are presence and connection metadata retained, access-controlled, and deleted? For sensitive updates, can a stale subscription leak an event after permission removal? The design should identify current authorization checks, durable source APIs, tail-latency SLI, reconnect SLI, and a drill that proves resumption does not duplicate irreversible work.
Terms in plain language
- Heartbeat
- A periodic signal used to detect whether a peer or connection is still responsive.
- Backpressure
- A mechanism that slows, rejects, or sheds work when a consumer cannot keep up.
- Presence lease
- A time-limited claim that a user or device is online, refreshed by heartbeat and expired after silence.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Primary protocol specification for WebSocket framing and connection behavior; application delivery guarantees must be designed separately.
Primary browser standard for EventSource, reconnection, and event IDs for one-way server streams.