Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Reliability and Acknowledgements

Delivery Guarantees and Connection State Recovery

What Socket.IO guarantees about message delivery, how retries cause duplicates, how connection state recovery works, and an offset-based pattern for exact replay.

Real networks drop connections: a phone enters a tunnel, a laptop sleeps, a server restarts. This lesson is about what happens to messages around those moments. Socket.IO gives you useful building blocks, but not magic: by default delivery is at most once. Knowing the guarantees (and their holes) decides how you design chats, notifications and anything where a lost message matters.

The socket.io package is not available in the runner on this site. Real configuration is shown in read-only blocks. The runnable examples are stand-ins written in plain Node.js that reproduce the behavior being discussed.

What Socket.IO guarantees

Guarantee Holds?
Messages on one connection arrive in the order they were sent Yes (one transport at a time, TCP underneath)
A message is delivered exactly once No
A message sent while disconnected is delivered later Only if you buffer or recover it
The server knows a client received an event Only with an acknowledgement

Delivery is at most once by default: if the connection breaks while an event is in flight, it is lost, and neither side is told. On the client, events you emit while disconnected are put in a send buffer and flushed after reconnection. Events the server emits to a disconnected client are simply not delivered to it.

Two switches change the picture: the client's retries option, which resends unacknowledged messages, and connection state recovery on the server.

Retries: at least once

JavaScript
const socket = io({
  retries: 3,        // resend up to 3 times if no ack arrives
  ackTimeout: 10000, // per attempt, wait 10 s for the ack
});

socket.emit("order:create", { sku: "A1", qty: 2 });

With retries, the client keeps a packet until the server acknowledges it. If the ack does not arrive in ackTimeout, it sends again, so the guarantee becomes at least once. That solves loss and introduces duplicates: the first attempt may have reached the server, which processed it but whose ack was lost. The remedy is an idempotency key: an id generated by the client and checked by the server.

JavaScript
import { randomUUID } from "node:crypto"; // in a browser: crypto.randomUUID()

socket.emit("order:create", { requestId: randomUUID(), sku: "A1", qty: 2 });
Node.js Retries without and with idempotency (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without the key the server stored three orders for one click. With it, one. Make handlers idempotent whenever you enable retries.

Connection state recovery

Reconnecting is easy; getting back your state is the hard part. After a short disconnect the new connection is a fresh socket with a new socket.id, and it has lost its rooms and the events it missed. Connection state recovery (Socket.IO 4.6+) restores all of that if the disconnect was short:

JavaScript
const io = new Server(httpServer, {
  connectionStateRecovery: {
    maxDisconnectionDuration: 2 * 60 * 1000, // keep session state for 2 minutes
    skipMiddlewares: true,                   // do not re-run auth middleware on recovery
  },
});

io.on("connection", (socket) => {
  if (socket.recovered) {
    // the id, rooms, data and missed events were restored
  } else {
    // new or too-late session: initialize state (join rooms, send full history, ...)
  }
});

On the client, socket.recovered is also set after a successful recovery. What is restored: socket.id, socket.rooms, socket.data, and the events that were broadcast to the rooms the socket was in while it was away. What is not restored: events emitted directly to that socket with socket.emit(...), the client-side buffer is unaffected, and anything beyond maxDisconnectionDuration.

The server stores each broadcast for the retention period, and the client remembers the id of the last event it processed. When it reconnects it sends that offset, and the server replays everything after it.

Recovery in four moves

Connection drops Network or server blip.
Server keeps state Session and missed broadcasts, for up to maxDisconnectionDuration.
Client reconnects It sends the id of the last event it saw.
Replay Same id and rooms, missed broadcasts arrive.

Too late? A normal fresh connection.

1 / 2
Node.js State recovery with an event log (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When recovery is not enough

Connection state recovery is excellent for short blips, and it has real limits:

  • It is best effort. After a server crash, or when the retention period passes, the client gets a fresh session. Your code for the recovered === false branch must produce a correct state anyway.
  • With multiple servers it needs an adapter that supports it, such as the Redis Streams adapter, and the default in-memory buffer lives in one process.
  • The server keeps the replay buffer in memory (for the default adapter), so a long window with chatty rooms costs RAM.
  • It does not cover messages emitted straight to one socket.

For anything that must not lose data (chat history, payments, orders) the dependable approach is to store events in your database and let the client ask for what it missed.

The offset pattern

Give every message a monotonically increasing id when you persist it. The client remembers the last id it processed and sends it when it connects:

JavaScript
// client
const socket = io({
  auth: (cb) => cb({ offset: lastOffset }), // evaluated on every (re)connection
});
socket.on("chat message", (msg, serverOffset) => {
  render(msg);
  lastOffset = serverOffset;
});
JavaScript
// server
io.on("connection", async (socket) => {
  if (!socket.recovered) {
    const rows = await db.all("SELECT id, content FROM messages WHERE id > ?", socket.handshake.auth.offset ?? 0);
    for (const row of rows) socket.emit("chat message", row.content, row.id);
  }
});

socket.on("chat message", async (content, ack) => {
  const { lastID } = await db.run("INSERT INTO messages (content) VALUES (?)", content);
  io.emit("chat message", content, lastID);
  ack?.({ ok: true });
});

Because the message exists in the database first, nothing depends on the buffer, and this works across servers, restarts and long outages. Combine it with socket.recovered, which avoids the query in the common short-blip case.

Volatile events: when loss is fine

Some data is useless once it is old: cursor positions, game state at 60 frames per second. For those, send volatile events, which are dropped if the connection is not ready instead of piling up in a buffer:

JavaScript
socket.volatile.emit("cursor", { x: 120, y: 80 });

Choosing which events are volatile is part of delivery design: critical ones use acks, retries and persistence; ephemeral ones use volatile.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is Socket.IO's default delivery guarantee?

    A message in flight when the connection breaks is lost and nobody is notified, unless you add acks, retries or recovery.
  2. 2. Why should handlers be idempotent when the client uses retries?

    Retries move from at-most-once to at-least-once, so duplicates are possible and must be harmless, for instance via a request id.
  3. 3. Which is restored by connection state recovery?

    Recovery restores the session and replays broadcasts missed within maxDisconnectionDuration; direct emits are not replayed.
  4. 4. Where is the safest place to get messages for data that must never be lost?

    A persistent store with ordered ids lets a client fetch everything after its last offset, regardless of outage length.

Summary

  • By default delivery is at most once; add acks and retries for at least once, and use request ids to make duplicates harmless.
  • Connection state recovery restores id, rooms, data and missed room broadcasts for short disconnects.
  • It is best effort: always handle recovered === false correctly.
  • For critical data, persist messages and replay from the client's last offset.
  • Use volatile emits for data that is worthless once stale.

Next: Reconnection and Backoff