Skip to the page

Real-time communication · senior

Keeping real-time connections reliable: reconnect, heartbeats, ordering

Real connections drop all the time on mobile, so a production client reconnects with exponential backoff and jitter, detects dead connections with heartbeats, resumes from the last sequence number, de-duplicates and orders messages, and batches UI updates so a flood of messages does not freeze the page.

The notes

What you must know

  • Reconnect with exponential backoff + full jitter (random between 0 and min(cap, base x 2^attempt)) so thousands of clients don't reconnect at the same moment after an outage. Reset the attempt counter after a stable connection.
  • Heartbeats: ping/pong every 20 to 30 s; if no pong, treat the socket as dead (TCP can stay 'open' for minutes on a dead mobile link). Also listen to online/offline and visibilitychange.
  • Resume: every message has a sequence number or id; after reconnect, ask for messages after the last one you processed (SSE does this with Last-Event-ID). Fetch missed state over HTTP if the gap is large.
  • Delivery is at-least-once in practice: de-duplicate by message id; order by server sequence, not arrival time; use client-generated ids for optimistic sends.
  • UI: batch updates (for example once per animation frame) for high-frequency streams like stock ticks; keep only the latest value per key; virtualise long message lists.
  • Scaling notes: sticky sessions or a pub/sub layer (Redis, Kafka) behind WebSocket servers; authenticate on connect and re-check on reconnect; close idle connections on hidden tabs to save battery.

The red pen

Common traps: mistake → fix

  • Mistake: "Reconnect immediately in a loop"

    Fix: creates a thundering herd that keeps the server down; use backoff with jitter.

  • Mistake: "If the socket is open, it is alive"

    Fix: a half-open TCP connection looks open; use heartbeats.

  • Mistake: "Render every message as it arrives"

    Fix: 200 updates per second will block the main thread; batch per frame.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you handle reconnection for a WebSocket client?
  2. Why add jitter to backoff?
  3. How do you make sure no chat messages are lost or shown twice after a reconnect?
  4. A trading screen receives 500 price updates per second. How do you keep the UI responsive?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview