skip to content

In a mobile live trivia-show app, how should each client reconnect after its socket drops, including when the server drops thousands of players at once?

level: middleimportance: should knowfreq 47%

answer

  1. not all drops look alike
  2. wait for the network, not the clock
  3. capped exponential delays, randomised
  4. randomise the first try after mass drops
  5. reset only after staying healthy

basics

~20 s

Try at once when the phone's own network just returned, otherwise back off exponentially with a cap and random jitter. After a server-wide drop, randomise even the first try, honour Retry-After, and reset the backoff only after a healthy spell.

solid answer

~50 s

Reconnect depends on why the socket dropped. If the phone was offline, do not spend attempts: wait for the OS to report a network, then try immediately. Otherwise use capped exponential backoff with full jitter, for example a random delay up to `min(30 s, 1 s x 2^attempt)` with both numbers this scenario's assumptions. When the server closed everyone at once, saying it is going away or overloaded, randomise even the first attempt over a spread window so thousands of phones do not return in the same second, and honour a `503` with `Retry-After` on the upgrade. Reset the attempt counter only after the connection has stayed healthy for a while, not when it merely opens, or a flapping server gets hammered. A `401` is not a backoff case: refresh the token once and reconnect. Meanwhile the player sees 'Reconnecting...', and after repeated failures a manual retry.

code

pseudocode · 29 lines
pseudocode
attempt = 0

function reconnect(first_delay):
    show_state("reconnecting")
    wait(first_delay)                    # random spread after a server-wide close, else 0
    refreshed = false
    loop:
        if not network_available():
            wait_for_network_change()    # no attempts while offline
            attempt = 0                  # the network is back: try now
        result = open_socket_and_resume(last_applied_seq)
        if result.ok:
            show_state("live")
            after 30 seconds connected: attempt = 0
            return
        if result.status == 401:
            if refreshed or not refresh_access_token():
                show_state("signed out")
                return
            refreshed = true
            continue                     # retry now with the new token
        attempt = attempt + 1
        ceiling = min(30 seconds, 1 second * 2 ^ attempt)
        delay = random_between(0, ceiling)
        if result.retry_after:
            delay = max(delay, result.retry_after)
        if attempt >= 6:
            show_state("offer manual retry")
        wait(delay)

go deeper

for a junior

Recall that reconnects wait longer after each failure, with a cap and a random element, and that the player sees a reconnecting state.

for a middle

Explain the phone-specific triggers: wait for the network signal, try at once when it returns, and treat a 401 as a token refresh.

for a senior

Show the client's share of preventing a reconnect storm: jittered first attempt after a mass close, Retry-After, and resetting only after a healthy spell.

for a principal

Decide which reconnect parameters the server should control at runtime, and how the client and server sides together bound a whole audience's return.

## Not all drops look alike A phone's live socket drops for different reasons, and each one asks for a different first move: | Cause | What the client knows | First move | |---|---|---| | The phone lost its network | The OS reports no connectivity | Wait for the network signal, then connect at once | | The phone changed networks | The OS reports a new default network | Connect at once on the new network | | A single dead path | Heartbeat deadline missed, network still up | Connect at once; back off with jitter if that fails | | The server closed many sockets | A close saying the server is going away, or many failures | Randomised first attempt over a spread window | | The server is overloaded | `503` on the upgrade, maybe with `Retry-After` | Wait at least the stated time | | The session expired | `401` on the upgrade | Refresh the token once, then connect | The theory of backoff and jitter is general; what is specific to a phone is that the OS can tell the client when the network itself is gone or back, and that a whole audience of phones may be dropped at the same moment. ## Waiting for the network, not the clock While the phone has no network, every attempt fails instantly and burns battery. So the loop does not count attempts while offline: it waits for the OS's connectivity signal and then tries **immediately**, because the most likely cause of the drop has just been fixed. This is also what makes reconnects feel fast after a tunnel. The same signal matters while connected: if the OS reports a new default network, the old socket is suspect and the client reconnects on the new one at once rather than waiting for a heartbeat to fail. ## Backing off, with a cap and jitter When the network is up and attempts still fail, the client spaces them out: - **Exponential growth**: each failure doubles the ceiling of the delay (1 s, 2 s, 4 s, ...). - **A cap**: the ceiling stops growing at, say, 30 seconds (an assumption), so a player is never left waiting minutes once the server recovers. - **Full jitter**: the actual delay is random between zero and the ceiling, so clients that failed together do not retry together. - **Server hints win**: if the upgrade is refused with `503` and `Retry-After`, the client waits at least that long. ## The reconnect storm, from the client's side In a game show the audience is synchronised by design: thousands of players are connected to the same show. If the server restarts or a node closes its sockets, all of them lose the connection in the same second. If every client tries again immediately, the recovering server receives the whole audience at once and may fall over again. The server side owns draining and capacity; the client's share is: 1. **Randomise the first attempt** after a server-side close, over a spread window of a few seconds (an assumption, ideally sent by the server). 2. **Back off with jitter** on every later failure. 3. **Reset the counter only after a healthy spell**, such as 30 seconds connected (an assumption). Resetting on open lets a server that accepts and then drops connections pull every client into a tight loop. The spread window, the cap and the healthy spell are best sent by the server in the connect handshake, so the team can widen them for a show with a record audience without shipping a new build. ## Expired sessions and what the player sees A reconnect after a long time away may fail because the access token expired. That is not a network failure: the client refreshes the token once through its normal request pipeline and connects again, or sends the player to sign in if the refresh fails. Backing off on a `401` only delays an attempt that can never succeed. On screen, the state is honest: a 'Reconnecting...' banner, answer buttons disabled, and after several failed attempts a message with a manual Retry. The live question and its remaining time come from the server once the socket is back. ## Common mistakes - Retrying immediately in a loop when the server drops everyone. - Counting failed attempts while the phone has no network at all. - Resetting the backoff the moment a connection opens. - Backing off on an expired token instead of refreshing it.

  • Why should the backoff counter reset after a healthy spell rather than when the socket opens?
    A server in trouble may accept the upgrade and drop the socket a second later. If the counter resets on open, every client goes back to the shortest delay each time and the whole audience retries in a tight loop. Requiring, say, 30 seconds of healthy connection before resetting keeps the delays growing while the server is unstable.
  • The phone reports that the network is back after a tunnel; why reconnect immediately instead of waiting the current backoff delay?
    The delay was protecting the server from a client whose problem it could not see. Now the client knows the cause, its own missing network, has just been fixed, and the server has no reason to be overloaded by this one phone. An immediate attempt makes recovery feel instant; backoff resumes if that attempt fails.

  • Reconnect immediately in a tight loop until the socket opens again.
  • Every client should use the same fixed delay before reconnecting.
  • Reset the backoff counter as soon as a connection opens.
  • Keep counting reconnect attempts while the phone has no network.
  • A 401 on reconnect should be retried with backoff like a network error.