Latticework

Command Palette

Search for a command to run...

WebSockets

Reconnection Patterns

16 min

Explanation

Network connections drop — servers restart, wifi hiccups, load balancers cycle instances. A WebSocket client needs a reconnection strategy, and retrying instantly, over and over, is actively harmful: if a server goes down and every single client reconnects the SAME instant it comes back up, that flood of simultaneous reconnects can knock it back down (a "thundering herd"). Exponential backoff fixes this by doubling the wait between attempts, capped at some maximum so it doesn't grow forever.

def next_retry_delay(attempt, base=1, cap=30):
    return min(base * (2 ** attempt), cap)
Try it

Real production systems also add random 'jitter' on top of this (a small random offset per client) so that even clients which started retrying at the exact same moment don't all reconnect in lockstep -- the cap alone solves 'don't grow forever,' jitter solves 'don't all arrive at once.'

Loading editor…
Exercise

Write `next_retry_delay(attempt, base=1, cap=30)`: return `base * 2^attempt`, capped at `cap`. `attempt` starts at 0 for the first retry.

Quiz

Why does a WebSocket client use EXPONENTIAL backoff (doubling the delay each retry) instead of retrying immediately every time?

Checkpoint

You can implement capped exponential backoff and explain why it prevents a reconnection storm from overwhelming a recovering server.