How do you build reliable realtime UI over WebSockets or similar?
Connection state, reconnection, ordering, optimistic updates, and the UI contracts users need when the live link is imperfect.
Useful prerequisites
A WebSocket connection can deliver updates as they happen, but an open socket does not guarantee that the client has the latest state. Phones sleep, networks change and servers restart. A realtime interface needs to handle reconnecting, missed messages and reconciliation with the server, not only the happy path where the connection stays open.
A WebSocket connection can deliver updates as they happen, but an open socket does not guarantee that the client has the latest state. Phones sleep, networks change and servers restart. A realtime interface needs to handle reconnecting, missed messages and reconciliation with the server, not only the happy path where the connection stays open.
The quick version
Realtime UI is a state machine on top of an unreliable channel. Model connection status explicitly, reconnect with backoff, make messages idempotent or ordered where it matters, and decide what the user sees when the link drops mid-action. Optimistic updates help perceived speed; they need a clear rollback or reconciliation path when the server disagrees or the message never lands.
Build the mental model
HTTP request/response is a single exchange. A WebSocket (or SSE, or a realtime SDK) is a long-lived session that can:
- Connect and disconnect at any time.
- Be processed out of order by application code if asynchronous handlers race. WebSocket frames on one connection are ordered, but reconnects, multiple producers, and replay/fan-out introduce ordering questions across sessions.
- Lose continuity across disconnects. Applications may queue, coalesce, or discard updates while disconnected or overloaded; the transport does not provide durable delivery across reconnects.
- Survive a tab backgrounded on mobile only until the OS kills it.
If the UI assumes “connected forever” and “every message arrives once in order,” it will lie to users the first time the network blips. Treat connectivity as visible state and every message as something that might need deduplication or conflict handling.
Connection state the UI should know
A minimal set:
- Connecting — initial or reconnect attempt in progress.
- Connected — channel open; you can send and receive.
- Disconnected — clean or unclean close; you are not live.
- Reconnecting — automatic recovery in progress (with attempt count / next try time if useful).
Optional but useful:
- Degraded — connected but falling behind (large buffer, high latency).
- Failed — gave up reconnecting; user must act (reload or retry).
Surface a quiet indicator for short blips; be louder when the user is about to lose work or is clearly offline. Avoid a banner that flashes on every brief mobile handoff.
Reconnection
Typical approach:
- On close or error, schedule a reconnect with exponential backoff and jitter.
- Cap the backoff; after N failures, move to a “failed” state with a manual retry.
- On successful reconnect, resynchronise — do not assume the client’s local state still matches the server. Common patterns: request a snapshot, replay missed events from a sequence number, or invalidate and refetch critical queries.
Auth tokens often expire while the socket is open. Refresh the token and reconnect rather than sending forever with a dead credential.
Message design
Idempotency
If the client retries a send, or the server retries a push, the same logical message must not apply twice unless the operation is naturally safe. Client-generated message ids or server-side deduplication help.
Ordering
If order matters (chat, sequential state machines), include a sequence number or use a channel that preserves order per stream. WebSocket messages on a single live connection arrive in order, but TCP does not give you a durable application-level order across reconnects, multiple tabs, producers, or replay. Use sequence numbers or explicit ordering rules where the domain requires them.
Event vs snapshot
Small events (“item 42 updated”) are efficient; they require the client to already have a baseline. Snapshots are heavier but simpler to reason about after a reconnect. Many systems use snapshots on join/reconnect and events thereafter.
Optimistic UI on a live channel
Same rules as optimistic HTTP, with extra failure modes:
- Apply the optimistic update locally.
- Send the message.
- On ack, mark confirmed (or replace with server truth).
- On nack or timeout, roll back or mark conflict.
- On disconnect before ack, keep the pending state visible as “not yet synced,” not as final truth.
Users should be able to tell the difference between “saved live” and “waiting to send.”
Multi-tab and multi-device
Two tabs on the same account will both receive pushes unless you demux. Decide:
- Both stay live and must handle duplicate events idempotently, or
- One leader tab holds the socket and others use a secondary path (BroadcastChannel, shared worker, or just independent sockets with care).
Presence (“who is online”) is especially easy to get wrong with multiple tabs.
Concrete pattern
type ServerEvent = {
id: string;
sequence: number;
type: 'message.created';
payload: Message;
};
function onServerEvent(event: ServerEvent) {
if (seenEventIds.has(event.id)) return; // replay / duplicate delivery
if (event.sequence !== lastAppliedSequence + 1) {
markConnectionState('resyncing');
requestAuthoritativeSnapshot();
return;
}
seenEventIds.add(event.id);
applyMessage(event.payload);
lastAppliedSequence = event.sequence;
}
The server-issued sequence is scoped to a well-defined stream. A gap triggers reconciliation instead of guessing; event IDs make replay idempotent. Bound the deduplication set or persist a high-water mark in production, and define what happens when the snapshot races with newer events.
Where it gets tricky
Mobile backgrounding
OS may freeze or kill the socket. On foreground, treat as a reconnect and resync, not as “we were connected the whole time.”
Server restart
All clients disconnect. Reconnect storms can overload the server — backoff and jitter exist for this reason. Clients should resync, not assume continuity.
Partial delivery
You sent three messages; the socket died after one. On reconnect, only the missing ones should be retried, and the server must handle duplicates.
Security
Sockets still need authz on every sensitive message. Do not trust the client’s claim of room membership or user id without server verification.
A common misunderstandings
-
“WebSocket means realtime is solved.”
The transport is only the pipe. State, reconnect, and UX are the product. -
“Show a full-screen error whenever the socket drops.”
Brief disconnects are normal on mobile. Reserve strong UI for prolonged or failed recovery. -
“Optimistic updates are always safe if we have a socket.”
They are only as safe as your ack/rollback and conflict rules.
What this changes in an application
Realtime features feel magical when the link is stable and broken when it is not. The difference is almost never the library choice; it is whether connection state, resync, and pending work are first-class in the UI. Teams that model those states ship chat, collaboration, and live dashboards that degrade honestly. Teams that do not ship demos that fail the first time someone rides the subway.
Questions worth exploring next
- How do you resynchronise client state after a reconnect?
- What should the UI show for a message that was sent but not acknowledged before disconnect?
- How do you prevent a reconnect storm after a server deploy?
- When would you choose SSE over WebSockets (or vice versa)?
References and next steps
- MDN — WebSocket — the platform API.
- MDN — Server-Sent Events — simpler one-way alternative when it fits.
- Operational guides from realtime providers (Ably, Pusher, Socket.IO, native) — reconnection and presence patterns are well documented in vendor material; apply the same principles if you roll your own.