Skip to the solution
MediumFrontendAsked in 20246 min read

WebSocket reconnect logic

3.9k views

The problem

Problem, as an interviewer would state it: "Implement an auto-reconnecting WebSocket wrapper: when the connection closes unexpectedly, retry with exponential backoff, resetting the backoff once a connection genuinely succeeds."

Examples:

Code
const socket = createReconnectingSocket(() => new WebSocket(url));
// on a real disconnect, retries after 1s, 2s, 4s, 8s... up to a max delay

Clarifying questions expected:

  • Should the backoff RESET to the base delay after a real successful reconnection, or keep growing indefinitely across the whole session?
  • Is there a maximum delay cap, or does the backoff grow unbounded?
  • Should a real, deliberate .close() call by the application itself trigger a reconnect attempt, or only an unexpected disconnect?

Code / implementation expected: Yes — real, direct proof against a mock socket that genuinely fails a fixed number of times before succeeding, confirming the real, measured backoff delays correctly double and the connection eventually recovers.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: reconnect delays genuinely double across real failures, and the connection eventually succeeds after a mock socket stops failing

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 48 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Wire Up Debounced Resize and Throttled Scroll Handlers on a Real Component

Continue