BACK
Use casesWebSocket reconnect — backoff after a drop
Use cases · 45

WebSocket reconnect — backoff after a drop

Pattern

The connection dropped — the network blinked, the phone went to sleep, the backend deployed. You need to reconnect, but with a growing delay (backoff) so you don't choke the server with thousands of simultaneous reconnects.

The problem it solves

Without backoff, thousands of clients after a network blip all reconnect at once and knock the backend over. An imperative setTimeout(reconnect, 1000) often creates parallel sockets and forgets to stop when you leave the page.

Operators and why they matter

  • retry({count, delay}) — re-subscribes to the connection factory after an error. That's the reconnect.
  • timer(retryIndex * 10) — backoff: each next attempt waits longer.
  • scan — counts successful connections or attempts for telemetry.

Gotchas

  • retry with no delay — a tight loop, a thousand attempts a second. It knocks out both the backend and the battery.
  • Retrying auth errors (401) is pointless until the token refreshes. Use a conditional retry, like for HTTP.
  • Don't confuse the shared socket lifecycle with component subscriptions. Destroying one component shouldn't close the socket for the whole app.

What you get

Transient network failures don't break the realtime feature. Reconnect is bounded, observable, and won't choke the server.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...