Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Reliability and Acknowledgements

Acknowledgements and Timeouts

Use Socket.IO acknowledgements as request/response, add timeouts, await them with emitWithAck, collect replies from rooms and handle missing answers.

A plain emit is fire-and-forget: you send an event and learn nothing about what happened. An acknowledgement (ack) turns it into a request/response: the receiver calls a function you passed as the last argument, and the answer travels back to your callback. Combined with a timeout, acks are the basic tool for knowing whether a message was handled.

Socket.IO itself is not installed in the runner on this site. The real API appears in read-only blocks. The runnable examples use a small in-memory stand-in (a fake client/server pair, no network) that follows the same call shapes, including ack timeouts.

The basic ack

JavaScript
// client
socket.emit("create-todo", { title: "Buy milk" }, (response) => {
  console.log(response.status, response.id);
});

// server
io.on("connection", (socket) => {
  socket.on("create-todo", (payload, callback) => {
    const todo = saveTodo(payload);
    callback({ status: "ok", id: todo.id });
  });
});

The last argument of the emit, if it is a function, is not sent as data. Socket.IO assigns it an id, sends the id with the packet, and keeps the function. When the other side calls callback(...), an ack packet with that id returns and your function runs. Arguments must be serializable, like any event data.

It works in both directions: the server can also emit with a callback and the client answers.

JavaScript
// server asks the client
socket.emit("confirm-delivery", orderId, (answer) => { /* ... */ });

// client
socket.on("confirm-delivery", (orderId, callback) => callback(true));

The missing-answer problem

If the receiver never calls the callback, because it crashed, disconnected or simply forgot, the sender waits forever. Do not leave that open: add a timeout.

JavaScript
socket.timeout(5000).emit("create-todo", { title: "Buy milk" }, (err, response) => {
  if (err) {
    // the other side did not acknowledge within 5 seconds
    showRetryButton();
  } else {
    render(response);
  }
});

With .timeout(ms), Node-style arguments are used: the first is an error (or null), then the answers.

Node.js Ack with and without a timeout (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.

The slow job fails the 100 ms timeout, even though the server may still finish the work later. That is an important point: a timeout does not undo anything. The server might have saved the todo. If you retry blindly you can create duplicates, which is why handlers should be idempotent (see delivery guarantees).

Promises: emitWithAck

In modern code you rarely want callbacks. Since Socket.IO 4.6, emitWithAck returns a promise:

JavaScript
try {
  const response = await socket.timeout(5000).emitWithAck("create-todo", { title: "Buy milk" });
  console.log(response.id);
} catch (err) {
  console.error("no ack in time", err.message);
}

On the server, a broadcast can wait for many acknowledgements. The result is an array with one answer per client that received the event:

JavaScript
// every socket in the room must answer within 2 seconds
try {
  const answers = await io.timeout(2000).to("room-1").emitWithAck("are-you-ready");
  console.log(answers); // [true, true, false]
} catch (err) {
  console.log("some players did not answer in time");
}

If any client misses the timeout, the promise rejects. To also see the answers that did arrive, use the callback form, which receives an error and the partial list:

JavaScript
io.timeout(2000).to("room-1").emit("are-you-ready", (err, responses) => {
  if (err) console.log("late clients; answers so far:", responses);
});

Use this for "ready check" flows in games and for collaborative tools that need all participants to confirm.

Node.js Waiting for the whole room (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.

Designing good acks

Return a result object, not a bare string. { status: "ok", id } and { status: "error", message } leave room to grow and make errors explicit. Do not throw inside a handler for expected failures; return an error object through the callback, because a thrown exception in an event handler does not reach the sender.

Guard against a missing callback. A malicious or old client may omit it, and then callback(...) throws a TypeError. Make it safe:

JavaScript
socket.on("create-todo", (payload, callback) => {
  const ack = typeof callback === "function" ? callback : () => {};
  ack({ status: "ok" });
});

Validate inputs before acting. The ack is the natural place to report validation problems:

JavaScript
socket.on("rename", (name, callback) => {
  if (typeof name !== "string" || name.length < 1 || name.length > 30) {
    return callback({ status: "error", message: "Name must be 1-30 characters" });
  }
  socket.data.name = name;
  callback({ status: "ok" });
});

Use one ack, once. Calling the callback twice sends nothing more: the second call is ignored by the sender side, so do not rely on it for streaming progress. For progress, emit separate events.

Prefer a global default. The client option ackTimeout sets a default for every emit with an ack, and combined with retries it enables automatic resending (covered in the next lesson):

JavaScript
const socket = io({ ackTimeout: 10000, retries: 3 });

Acks across rooms and servers

With an adapter (see Redis adapter), io.timeout(...).to(room).emitWithAck(...) collects answers from clients on every server, as long as the adapter supports acknowledgements (the official ones do). Server-to-server questions use serverSideEmit, also with a callback.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if the receiving side never calls the acknowledgement callback and no timeout is set?

    Without a timeout there is no failure path. Use socket.timeout(ms) so you get an error argument.
  2. 2. In socket.timeout(5000).emit('x', cb), what is the first argument of cb?

    Timed-out emits use Node-style callbacks, so the first argument is an error and the answers follow.
  3. 3. A client times out waiting for an ack. What can you conclude about the server?

    A timeout only tells you that no ack arrived. The work may have completed, so retries should be idempotent.
  4. 4. What does io.timeout(2000).to(room).emitWithAck(...) resolve with when every client answers?

    It resolves with all answers, or rejects if some client does not answer in time.

Summary

  • A function passed as the last emit argument becomes an acknowledgement callback.
  • Always pair acks with .timeout(ms) or ackTimeout; timed-out calls receive an error first.
  • emitWithAck returns a promise; on the server it collects answers from every client in a room.
  • A timeout does not cancel work, so design handlers to be idempotent.
  • Return structured results ({ status, ... }) and validate input before acknowledging.

Next: Delivery Guarantees and Recovery