CodePark/ questions / Real-time updates
START PRACTICINGPRACTICE
Frontend question · Frontend system design › Real-time updates

Your app uses a WebSocket for live updates. How do you handle disconnects, reconnection, missed messages and message ordering on the client?

Detect drops with heartbeats, reconnect with backoff and jitter, fill gaps with sequence numbers, and apply events in order exactly once.

Detecting drops: browsers do not always fire close quickly on a dead network. So I send application heartbeats: small ping messages at a regular interval. If the pong reply does not arrive, I treat it as a disconnect. I also listen to the online/offline and visibilitychange events.

Reconnecting: wait before each retry, and double the wait each time, up to a cap (a maximum wait). This is exponential backoff. Add a small random extra to each wait. This is jitter. Why? When a server restarts, every client disconnects at the same moment. Without jitter, they all reconnect at the same moment too, and the server can fall over again. This is called a thundering herd. The UI shows a quiet "reconnecting" state, instead of silently showing stale data.

Missed messages: the server gives each message a sequence number per channel. The number only ever goes up (it is monotonically increasing). On reconnect, the client sends the last sequence number it saw. The server replays the gap. If the gap is too large, the client refetches a snapshot over HTTP instead, and resumes from there.

Ordering and duplicates:

  • The client applies events in sequence order.
  • It buffers events that arrive early.
  • It drops events it already applied. So handlers are idempotent: applying the same event twice has no extra effect.
  • Events carry ids that match the client's temporary ids from optimistic updates. So a server confirmation replaces the temporary item instead of duplicating it.

After reconnecting, the client resubscribes to its channels.

  • Send heartbeats to detect dead connections.
  • Reconnect with exponential backoff and jitter, so clients do not all reconnect at once.
  • Use sequence numbers. On reconnect, replay the gap or load a snapshot.
  • Apply events in order and idempotently, so duplicates have no effect.
  • Resubscribe after reconnecting, and show the connection status.