Skip to content

    Frontend System Design

    Reconnection and Message Ordering

    Keep a live connection correct when it drops: backoff with jitter, sequence numbers, acknowledgements, resend and deduplication, shown in a runnable lab model.

    By Published 12 min read

    • frontend-system-design
    • real-time
    • websockets
    • reconnection
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: WebSockets in Depth

    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

    1. 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.
    2. 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.
    3. 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

    A reliable layer on top of a socket: each side numbers what it sends, keeps it until acknowledged, and counts what it deliveredChat widget to Reliable layer (messages); Reliable layer to Connection (msg seq, ack N); Connection to Chat server (frames)Chat widget: send, onMessageChat widgetsend, onMessageReliable layer: unacked, lastDeliveredReliable layerunacked,lastDeliveredConnection: may drop at any timeConnectionmay drop at anytimeChat server: its own queue and counterChat serverits own queue andcountermessagesmsg seq, ack Nframes

    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 ack with 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

    sequenceDiagram accTitle: Reconnect with resend of unacknowledged messages accDescr: The client sends messages 1 and 2 and the server acknowledges both. The client sends message 3 and the connection drops before it arrives. The client waits, reconnects and sends an ack of what it delivered, then resends message 3, which is the only unacknowledged one. The server delivers it once and acknowledges it. participant C as Client participant S as Server C->>S: msg 1, msg 2 S-->>C: ack 2 C->>S: msg 3 Note over C,S: the connection drops, msg 3 is lost C->>C: wait (backoff), reconnect C->>S: ack 0 (resume), then resend msg 3 S-->>C: ack 3

    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

    flowchart TD accTitle: Receiver rule for numbered messages accDescr: The receiver compares the sequence number of a message with the last number it delivered. If it is exactly one more, it delivers the message and acknowledges it. If it is lower or equal it is a duplicate and is dropped. If it is higher there is a gap and the message is dropped. In both drop cases the receiver sends an ack of the last delivered number. M["msg seq arrives"] --> Q{"seq vs lastDelivered"} Q -->|"seq = last + 1"| D["Deliver, ack seq"] Q -->|"seq <= last"| U["Duplicate: drop, re-ack last"] Q -->|"seq > last + 1"| G["Gap: drop, re-ack last"]

    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

    stateDiagram-v2 accTitle: Phases of a reconnecting socket accDescr: The socket starts idle. Connect moves it to connecting. When the transport opens it is open. An unexpected close moves it to waiting for the backoff delay and then back to connecting. A user close moves it through closing to closed. It may also give up and close after too many consecutive failures. [*] --> idle idle --> connecting: connect connecting --> open: transport opens open --> waiting: unexpected close connecting --> waiting: connection fails waiting --> connecting: backoff elapsed open --> closing: user close connecting --> closing: user close closing --> closed waiting --> closed: user close or give up closed --> [*]

    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.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In section 2, message c is lost in flight. Find the unacknowledged: 1 in the phase line: the client kept it.
    3. 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.
    4. After the reconnect the client sends ack 0 and then resends c and d with 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

    NOTE

    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

    Starting architecture: the widget reconnects after a delay and the server replays the whole recent conversationChat widget to Mobile network (reconnect); Mobile network to Chat server (new connection); Chat server to Chat widget (replay, no numbers)Chat widget: fixed 1 s retryChat widgetfixed 1 s retryMobile networkMobile networkChat server: replays recent messagesChat serverreplays recentmessagesreconnectnew connectionreplay, no numbers

    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

    1. Test with a seeded flaky network before shipping: random drops, refusals and replays, with the assertion "each message once, in order".
    2. Ship the receiver first, so it tolerates numbered frames, then the sender.
    3. 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.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments