What you'll learn: By the end of this lesson you will be able to say why order is a property of one connection and not of your application, number and acknowledge messages so that a reconnect loses nothing and delivers nothing twice, decide what a receiver does with a duplicate or a gap, space reconnection attempts with exponential backoff and jitter, and say when a client has to give up and reload its state.
Imagine reading a book aloud to a friend over the phone. The call drops. When you call back, "carry on" is not enough: your friend needs to say "I heard up to the end of page 12", and you need to know which pages you said while the line was dead. And if you both redial at the same moment, you keep getting a busy tone. Everything in this lesson is that: page numbers, "I heard up to here", and not redialling in lockstep.
The running example is a support chat widget on a product page. The customer types, an agent replies, and both sides must see every message once and in order, even on a train. The lab's messages and timings are made up for the lesson, and the lab is a model: a fake transport and a virtual clock stand in for a real network.
The core idea
- Order is a property of a connection. Within one connection, transport guarantees order. A new connection starts from nothing, and bytes that were "sent" on the old one may be gone.
- Correct reconnection is a protocol you add on top. Number each message, acknowledge what you received, keep what is unacknowledged, resend it after reconnecting, and drop what you have already delivered.
- Reconnecting must be polite and bounded. Wait a random, growing delay between attempts, forget past failures only when the server proves it is alive, and know when to stop and reload.
Three illustrations run through the lesson: a minimal example (two messages and a resend), a realistic example (the chat widget on a flaky network) and a failure example (replayed messages shown twice).
What a drop takes away
TCP gives an application "a reliable, in-order, byte-stream service" (RFC 9293). That promise holds for one connection. When a connection is aborted, its state is discarded, and the RFC does not promise anything about data still in flight. A WebSocket sits on top of TCP, so it inherits this. And the browser does not repair the loss: the WebSocket standard describes no automatic reconnection. When a connection fails, an error event fires and then a close event, and once the object is CLOSED the standard defines no retry. Any reconnect logic is yours, for example creating a new WebSocket in the close handler. The standard also says scripts must not be told why a connection failed, so a refused connection and a DNS failure look the same, with close code 1006 reserved for "closed abnormally".
So after a drop there are three things to worry about.
| Problem | How it happens | Effect on the user |
|---|---|---|
| Loss | A message was sent just before the drop and never arrived | A reply is missing |
| Duplicate | The sender resends what the receiver already has | A message shows twice |
| Reordering or a gap | Messages from two connections, or two sources, interleave; one is missing | Replies appear out of order, or a reply to a question that is not visible |
Figure 1. Two ends, each with a queue and a counter
How to read this: the widget talks to a layer that survives connections. Only that layer knows about sequence numbers; the app sees an ordered stream with nothing repeated.
Numbers, acknowledgements and resend
The lab's protocol has two frames. msg {seq, data} carries a message numbered 1, 2, 3 per direction. ack {ack: N} says "I have delivered everything up to and including N". This is the lab's own protocol, not a standard.
- The sender keeps every message until it is acknowledged. Messages sent while disconnected just wait in that queue.
- On every connect the client first sends
ackwith the last number it delivered, then resends everything still unacknowledged, with its original numbers. - The receiver delivers a message only if its number is exactly one more than the last it delivered. A lower number is a duplicate, a higher one means a gap. Either is dropped and answered with a fresh
ack, so the peer learns where the receiver is and resends from there.
That rule is why a resend can never deliver twice, and why order survives: a message is never delivered ahead of one before it.
Figure 2. A drop, a reconnect and a resend
How to read this: the client never asks "did 3 arrive?". It keeps 3 until an ack covers it, and sends it again on the next connection.
Figure 3. What the receiver does with each incoming message
How to read this: only one branch delivers. The two drop branches answer with the same ack, which tells the peer where to resend from.
Ordering is not free. Dropping on a gap is simple, and it makes the sender repeat more than needed. The alternative is to hold out-of-order messages until the gap fills, which costs memory and a rule for how long to wait. The lab chooses the simple rule and lists the buffered version as an exercise. When a gap can never fill (the server restarted, or the history is gone), no resend helps: the client must reload its state, as it must when a server's replay window has moved past what the client has.
Backoff and jitter
If every client reconnects at once after a server restart, the server is hit by all of them in the same moment. RFC 6455 says clients should back off: the first reconnection attempt after an abnormal closure should wait a random delay, and later failures should wait progressively longer, for example with truncated binary exponential backoff. It suggests a random initial delay between 0 and 5 seconds as reasonable. The AWS Builders' Library puts the general point briefly: "When failures are caused by overload, retries that increase load can make matters significantly worse", and jitter "adds some amount of randomness to the backoff to spread the retries around in time".
The lab uses full jitter: the wait is a random number between 0 and min(cap, base * 2^(failures - 1)). With base 500 ms and cap 8000 ms, the first failure waits up to 500 ms and the second up to 1000 ms. The random number is injected, so a test can choose the dice.
Two details matter more than the formula:
- Reset the failure count only on proof of life. The lab resets it when the server sends a well-formed frame, not when the socket merely opens. A server that accepts and immediately drops would otherwise reset the count every time and cause a storm of fast reconnects.
- Know when to stop. The lab can give up after a number of consecutive failures. Then the UI must say so and offer a retry, instead of a spinner forever.
Figure 4. Phases of the reconnecting socket
How to read this: waiting is where time is spent after a failure. Everything else is a short step.
Choosing
| Choice | Gain | Cost |
|---|---|---|
| Number, ack and resend (this lab) | No loss, no duplicates, order kept | Queue memory on both sides, a protocol to keep |
| Server resumes from your last number | Little client state | The server must keep history for each client |
| Drop on a gap and re-ack | Simple, correct | More resending after a long gap |
| Buffer out of order messages | Fewer resends | Memory and a timeout rule |
| Reload the state when resume is impossible | Always correct in the end | A full fetch, and a UI for it |
Server-Sent Events carry the same idea in the standard: the server numbers events with id, and the browser sends Last-Event-ID on reconnect. The Server-Sent Events in Depth lesson of this module (named here as plain text) covers that variant.
Build it: drops, a refused reconnect, and a replay
Goal. Run a model of a reconnecting socket through a session with a drop, a refused reconnect, messages queued while offline, and a server that replays something the client already has.
Setup. The lab reconnecting-socket is in the course's example workspace (Node 26). The logic is a pure reducer, step(config, state, event, random), plus a thin shell with real timers; the lab runs on a fake transport and a virtual clock. It has no browser and no network.
cd examples/frontend
pnpm install
cd labs/reconnecting-socket
pnpm test # 46 tests, including 12 seeded flaky-network simulations
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 2, message
cis lost in flight. Find theunacknowledged: 1in the phase line: the client kept it. - In section 4, the first reconnect is refused and the second succeeds. Check the waits: 0.5 of the 500 ms window is 250, and 0.8 of the 1000 ms window is 800, so the second attempt starts at 1050.
- After the reconnect the client sends
ack 0and then resendscanddwith their original numbers, in order.
Expected output, captured from a real run (Node 26.12.1, 2026-11-07), sections 2 to 4:
--- 2. send 'c', then the connection breaks before the frame arrives
t= 0 network: connection #1 dropped (1 frame(s) lost in flight)
t= 0 dice roll 0.5 for the backoff delay
t= 0 phase -> waiting (failed attempts in a row: 1, unacknowledged: 1)
--- 3. while disconnected, 'd' is queued; the server also has two messages for us
--- 4. the first reconnect attempt fails, the second succeeds
t= 250 phase -> connecting (failed attempts in a row: 1, unacknowledged: 2)
t= 250 network: connection #2 refused
t= 250 dice roll 0.8 for the backoff delay
t= 250 phase -> waiting (failed attempts in a row: 2, unacknowledged: 2)
t= 1050 phase -> connecting (failed attempts in a row: 2, unacknowledged: 2)
t= 1050 network: connection #3 opened
t= 1050 phase -> open (failed attempts in a row: 2, unacknowledged: 2)
t= 1050 client -> server ack 0
t= 1050 client -> server msg #3 "c"
t= 1050 client -> server msg #4 "d"
t= 1050 server -> client msg #1 "x"
t= 1050 app received "x"
t= 1050 server -> client msg #2 "y"
t= 1050 app received "y"
t= 1050 server -> client ack 3
t= 1050 server -> client ack 4
t= 1050 client -> server ack 1
t= 1050 client -> server ack 2
The failure count stays at 2 until the server's first frame arrives, which the lab treats as proof of life. Section 5 is the duplicate: the server resends z after a reconnect.
Expected output, captured from a real run (Node 26.12.1, 2026-11-07), section 5 to the end:
--- 5. the server sends 'z', the link drops after the app saw it but before the ack arrived;
--- this server replays unacknowledged messages on connect, so 'z' arrives a second time
t= 1050 server -> client msg #3 "z"
t= 1050 app received "z"
t= 1050 network: connection #3 dropped (1 frame(s) lost in flight)
t= 1050 dice roll 0.25 for the backoff delay
t= 1050 phase -> waiting (failed attempts in a row: 1, unacknowledged: 0)
t= 1175 phase -> connecting (failed attempts in a row: 1, unacknowledged: 0)
t= 1175 network: connection #4 opened
t= 1175 phase -> open (failed attempts in a row: 1, unacknowledged: 0)
t= 1175 client -> server ack 3
t= 1175 server -> client msg #3 "z"
t= 1175 client -> server ack 3
--- 6. the app closes the socket
t= 1175 phase -> closing (failed attempts in a row: 0, unacknowledged: 0)
t= 1175 phase -> closed (failed attempts in a row: 0, unacknowledged: 0)
server delivered, in order, exactly once: ["a","b","c","d"]
app received, in order, exactly once: ["x","y","z"]
duplicate frames the app side dropped: 1, the server side dropped: 0
connections used: 4
What the lab does not show. No real WebSocket, no real timing, and no heartbeats, so a connection that dies silently is not noticed. The ack handshake is this lab's own protocol: real servers need to speak it too. The unacknowledged queue is unbounded, and the numbering restarts at 1 for each side, so it does not survive a server that forgets its state.
Break it. In src/machine.ts, change the receiver's exact-next test to accept any higher number. Tests for gaps and the seeded simulations fail. Revert it.
In practice: a support chat that showed replies twice
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop's product pages have a support chat widget over a WebSocket. Customers often use it on a phone while moving, so connections drop several times per conversation. Agents see the customer's messages in a console and answer.
Starting architecture
Figure 5. Starting point: reconnect, send everything again
How to read this: the red edge is the problem. The replay has no numbers, so the widget cannot tell new messages from old ones.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Replay nothing | No duplicates | Messages lost during every drop | Agent replies vanish |
| Replay everything, dedupe by text | Nothing lost | Fragile: a customer can type "ok" twice | Real messages dropped |
| Number messages, ack, resume from the last number | No loss, no duplicates | A small protocol on both sides | Numbering must survive server restarts |
The decision
| Field | Decision record |
|---|---|
| Context | Frequent drops, and a replay with no numbers that shows replies twice. |
| Decision | Number messages per direction, acknowledge cumulatively, resend only what is unacknowledged, drop duplicates and gaps at the receiver, and use full jitter backoff with the failure count reset on the first frame. |
| Consequences, good | Each reply is shown once and in order, and reconnect storms are spread out. |
| Consequences, bad | Both ends keep a queue, and a server restart needs a defined answer (reload the conversation). |
| Revisit when | Conversations become long (bound the queue) or silent dead connections appear (add heartbeats). |
Rollout and verification
- Test with a seeded flaky network before shipping: random drops, refusals and replays, with the assertion "each message once, in order".
- Ship the receiver first, so it tolerates numbered frames, then the sender.
- Watch the duplicate and gap counters. A rising gap counter means the server is losing or reordering messages.
The 2 a.m. failure
Support reports that a customer saw an agent's reply twice, and a second customer saw replies in the wrong order after a lift ride. The widget retried every second after a drop, the server replayed the last messages on each connect, and the widget appended whatever arrived (illustrative).
First three checks: (1) does each message carry a number or id; (2) does the receiver remember the last number it delivered; (3) does a reconnect reset anything that should persist. Mitigation: deliver a message only when its number is exactly next, and answer others with an ack. Follow-up: add the seeded simulation to CI, count duplicates and gaps in monitoring, and make the failure count reset on proof of life.
The other side of this topic
On the back end, ordering and delivery are a producer-and-broker problem: at-most-once, at-least-once and exactly-once, idempotent consumers, and ordering per key. The front-end version is the same trade at the last hop. See Delivery Guarantees and Idempotency Keys and Safe Retries.
Architect's notes
- Decide who numbers messages and for how long the numbers live. A number that restarts when a server restarts needs a defined reset.
- Resend plus drop-duplicates is the simple, robust pair. Cleverer schemes need a reason.
- Make every retry loop bounded and visible. A silent infinite loop is an outage nobody sees.
- Test with seeded randomness. A flaky network is easy to simulate and hard to reproduce by hand.
Common mistakes
- Trusting the connection's order across reconnects.
- Resetting the failure count on
open, so a server that accepts and drops causes a storm. - Fixed delay, no jitter, so every client returns at the same moment.
- Deduplicating by content instead of by number.
- Appending whatever arrives after a replay.
Key takeaways
- Order and reliability belong to one connection; a new connection has no memory of the old.
- The browser's WebSocket does not reconnect: reconnecting is application code.
- Number, acknowledge, keep, resend, drop duplicates: a message is delivered once and in order.
- A gap that cannot fill means resume is impossible: reload the state.
- Exponential backoff with jitter spreads reconnects; reset it only when the server proves it is alive.
- Every loop needs a bound and a message to the user.
Practice exercises
Exercise 1, Starter (45 min): Run the lab's demo and write the receiver's decision (deliver, duplicate, gap) for each frame in section 5.
Exercise 2, Intermediate (2 hours): Change the lab so the receiver buffers out of order messages and delivers them when the gap fills. Add a test where the gap never fills and decide what the receiver does.
Exercise 3, Advanced (half day): Bound the unacknowledged queue. Decide what the user sees when it overflows, and add a test for it.
Related reading
In this course:
- WebSockets, SSE and Long Polling, the server side of the transports.
- Offline-First Sync and Conflict Resolution, what to do when a gap cannot be filled and two copies disagree.
- Error, Loading and Empty States, what the UI shows while the socket is
waiting. - Delivery Guarantees, the back-end view of ordering and delivery.
Official documentation
- RFC 6455: The WebSocket Protocol, recovering from abnormal closure and the close status codes.
- WHATWG: WebSockets, the
errorandcloseevents and the ready states. - RFC 9293: Transmission Control Protocol, the in-order, reliable byte stream of one connection.
- AWS Builders' Library: Timeouts, retries and backoff with jitter, why retries need backoff and jitter.
- WHATWG HTML: Server-sent events, the event ID and
Last-Event-IDvariant of the same resume idea.