Publisher Confirms: Know the Broker Has Your Message
Turn on publisher confirms in amqplib, compare waiting one by one, in batches and asynchronously on 10,000 jobs, and handle nacks and timeouts.
On this page (12)
- The problem: sendToQueue proves nothing
- The big picture: a receipt for every message
- Turn on confirms in amqplib
- Run it: 10,000 jobs, four ways
- Why waiting one by one is so slow
- What do confirms tell you when the broker dies?
- What a nack means
- What to do on a nack, a timeout or a lost connection
- Why not use transactions instead?
- Summary
- What comes next: routing with exchanges
- Sources
The previous lesson ended with a crash that lost persistent jobs from a durable queue. The publisher never found out. This lesson gives the publisher that missing signal: a publisher confirm, a receipt the broker sends back for each message it has taken responsibility for. You will turn confirms on, measure their cost on 10,000 Darkroom jobs, and crash the broker mid-run.
The problem: sendToQueue proves nothing
In Darkroom, the upload API publishes a resize job for every photo. sendToQueue returns true or false, and that value only says whether the client's write buffer is full. It does not mean the broker has the job. The confirms guide says a client that has written a message to its socket "cannot assume that the message has reached the server and was successfully processed".
The API needs to know which jobs are safe, so that it can send the others again.
The big picture: a receipt for every message
Confirms are switched on per channel. The client sends confirm.select, and from then on the channel is in confirm mode. From the first message on, both sides number every publish on that channel: 1, 2, 3 and so on. Each basic.ack carries one of those numbers in its delivery tag. When the multiple flag is set, the ack also covers every lower number still waiting.
When does the ack come? The docs list the cases under when published messages are confirmed:
- a message that reaches queues is acked once every one of those queues has taken it;
- if the message is persistent and the queue durable, taking it includes writing it to disk;
- for a quorum queue, a majority of its replicas must have the message;
- if no queue matches, the broker confirms as soon as the exchange has found that out.
So an ack alone does not prove that a queue holds the job. The lesson on the AMQP model showed how to catch unroutable messages with mandatory.
Turn on confirms in amqplib
In amqplib 2.4.2 you open a different kind of channel with createConfirmChannel. On a confirm channel, publish and sendToQueue take one more argument: a callback. From the 2.4.2 source (lib/channel.js): an ack calls it with null, a nack with an Error('message nacked'), and if the channel closes first, every waiting callback gets Error('channel closed'). When you pass a callback you also have to pass options, even if it is just {} (API reference).
waitForConfirms() gives you a promise for everything published so far: it resolves once all of it is confirmed, and rejects on a nack or when the channel closes first. The 2.4.2 source (lib/channel.js) sets no timeout on it.
Run it: 10,000 jobs, four ways
The RabbitMQ docs describe three strategies, and the Java tutorial codes them; there is no JavaScript version of that tutorial. Here they are in amqplib, plus a baseline without confirms. Create a project as in the Node.js lesson (type=module, amqplib@2.4.2), with the broker from the Docker lesson, and save publish-jobs.js:
// publish-jobs.js: publish 10,000 Darkroom resize jobs one of four ways and time it.
// Usage: node publish-jobs.js none|one-by-one|batch|async
import amqp from 'amqplib';
import { once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';
const QUEUE = 'darkroom.confirms.lab'; // a lab queue, not the real darkroom.resize
const TOTAL = 10_000;
const BATCH_SIZE = 100;
const mode = process.argv[2] ?? 'async';
const url = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const connection = await amqp.connect(url, {
clientProperties: { connection_name: `publish-jobs-${mode}` },
});
connection.on('error', (err) => console.error('connection error:', err.message));
// 'none' uses a plain channel; every other mode switches confirms on
const channel = mode === 'none'
? await connection.createChannel()
: await connection.createConfirmChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
await channel.purgeQueue(QUEUE); // start every run from an empty queue
const options = { persistent: true, contentType: 'application/json' };
const job = (i) => Buffer.from(JSON.stringify({ photoId: `p-${i}`, sizes: [320, 1080] }));
// sendToQueue returns false when the client's write buffer is full: wait for 'drain'
async function send(i, onConfirm) {
if (!channel.sendToQueue(QUEUE, job(i), options, onConfirm)) {
await once(channel, 'drain');
}
}
// amqplib's waitForConfirms has no timeout of its own, so add one
const CONFIRM_TIMEOUT_MS = 60_000; // not lower than the heartbeat timeout (60 s by default)
async function confirmsOrTimeout() {
const timer = sleep(CONFIRM_TIMEOUT_MS, 'timeout', { ref: false });
if (await Promise.race([channel.waitForConfirms(), timer]) === 'timeout') {
throw new Error(`no confirms after ${CONFIRM_TIMEOUT_MS} ms`);
}
}
const started = performance.now();
const pending = new Map(); // async mode: sequence -> photoId, until the broker answers
const nacked = [];
for (let i = 1; i <= TOTAL; i++) {
if (mode === 'async') {
pending.set(i, `p-${i}`);
await send(i, (err) => {
if (err) nacked.push(pending.get(i)); // nack: keep it to publish again
pending.delete(i);
});
} else {
await send(i);
}
if (mode === 'one-by-one') await confirmsOrTimeout();
if (mode === 'batch' && (i % BATCH_SIZE === 0 || i === TOTAL)) {
await confirmsOrTimeout(); // on a nack or timeout: publish this batch again
}
}
if (mode === 'async') {
try {
await channel.waitForConfirms();
} catch (err) {
console.error('not every job was confirmed:', err.message); // the callbacks counted the nacks
}
}
await channel.close(); // for 'none' this also flushes the client buffer
const ms = performance.now() - started;
const check = await connection.createChannel();
const { messageCount } = await check.checkQueue(QUEUE);
const rate = Math.round(TOTAL / (ms / 1000));
console.log(`${mode.padEnd(10)} ${Math.round(ms)} ms ${rate} msg/s queue: ${messageCount}`
+ (mode === 'async' ? ` nacked: ${nacked.length}` : ''));
await check.close();
await connection.close();
The scripts use a lab queue, darkroom.confirms.lab, a quorum queue like darkroom.resize from earlier lessons, so your real queue is left alone. Every job is persistent. Run each mode:
node publish-jobs.js none
node publish-jobs.js one-by-one
node publish-jobs.js batch
node publish-jobs.js async
First round on our machine:
none 1280 ms 7812 msg/s queue: 10000
one-by-one 35808 ms 279 msg/s queue: 10000
batch 902 ms 11090 msg/s queue: 10000
async 305 ms 32775 msg/s queue: 10000 nacked: 0
These numbers come from one laptop (16 CPUs, Linux, broker in Docker on the same machine), three rounds in a row, with other containers running. An earlier set of rounds gave 219–349 msg/s one by one. Treat the numbers as orders of magnitude, not a benchmark:
| Mode | Round 1 | Round 2 | Round 3 |
|---|---|---|---|
none | 7,812 msg/s | 32,349 msg/s | 36,305 msg/s |
one-by-one | 279 msg/s | 269 msg/s | 437 msg/s |
batch (100) | 11,090 msg/s | 8,314 msg/s | 11,217 msg/s |
async | 32,775 msg/s | 31,019 msg/s | 38,251 msg/s |
Why waiting one by one is so slow
Each wait costs a full round trip plus the broker's work before it can ack: for a quorum queue, writing to its Raft log on disk (and replicating it, in a cluster). The Java tutorial warns that this approach "won't deliver more than a few hundred published messages per second", which is what we saw, and the publishers guide says publish-and-wait "is not recommended". A batch pays that wait once per 100 jobs. The async mode never stops to wait, so many jobs are in flight and the broker can answer with multiple acks. For persistent messages under constant load, the confirms guide warns that "latency for basic.ack can reach a few hundred milliseconds", and recommends asynchronous or batched handling.
What do confirms tell you when the broker dies?
crash-test.js publishes the same 10,000 jobs with async confirms, but slowly (20 jobs every 10 ms), so you have time to stop the broker in the middle:
// crash-test.js: publish 10,000 jobs with async confirms, 20 every 10 ms,
// and save which photoIds the broker confirmed before the connection died.
import amqp from 'amqplib';
import { writeFileSync } from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
const QUEUE = 'darkroom.confirms.lab';
const TOTAL = 10_000;
const url = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const connection = await amqp.connect(url, {
clientProperties: { connection_name: 'crash-test' },
});
connection.on('error', (err) => console.error('connection error:', err.message));
const channel = await connection.createConfirmChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
await channel.purgeQueue(QUEUE);
let sent = 0;
const confirmed = []; // photoIds the broker acked
const unconfirmed = new Set(); // photoIds still waiting for an answer
const failed = []; // nacked, or lost when the channel closed
let closed = false;
channel.on('close', () => {
closed = true;
const notConfirmed = [...unconfirmed, ...failed];
writeFileSync('confirmed.json', JSON.stringify({ confirmed, notConfirmed }));
console.log(`channel closed: sent ${sent}, confirmed ${confirmed.length}, not confirmed ${notConfirmed.length}`);
});
const options = { persistent: true, contentType: 'application/json' };
try {
for (let i = 1; i <= TOTAL && !closed; i++) {
const photoId = `p-${i}`;
unconfirmed.add(photoId);
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify({ photoId, sizes: [320, 1080] })),
options, (err) => {
unconfirmed.delete(photoId);
if (err) failed.push(photoId); // 'message nacked' or 'channel closed'
else confirmed.push(photoId);
});
sent++;
if (i % 20 === 0) await sleep(10);
}
if (!closed) {
await channel.waitForConfirms();
await connection.close();
}
} catch (err) {
console.error('publish stopped:', err.message);
}
Start it, and about two seconds later kill the broker from a second terminal. docker kill sends SIGKILL, so RabbitMQ gets no chance to shut down cleanly:
node crash-test.js # terminal 1
docker kill rabbitmq # terminal 2
connection error: Unexpected close
channel closed: sent 3640, confirmed 3581, not confirmed 59
The script saved both lists of photoIds in confirmed.json. After the restart, reconcile.js drains the lab queue and compares ids:
// reconcile.js: after a restart, drain the lab queue and compare its photoIds
// with what crash-test.js saved in confirmed.json.
import amqp from 'amqplib';
import { readFileSync } from 'node:fs';
const QUEUE = 'darkroom.confirms.lab';
const url = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const { confirmed, notConfirmed } = JSON.parse(readFileSync('confirmed.json', 'utf8'));
const connection = await amqp.connect(url, {
clientProperties: { connection_name: 'reconcile' },
});
connection.on('error', (err) => console.error('connection error:', err.message));
const channel = await connection.createChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
const { messageCount } = await channel.checkQueue(QUEUE);
if (messageCount < confirmed.length) {
// seen right after a restart: the count was still climbing
console.log(`queue has ${messageCount}, fewer than ${confirmed.length} confirmed: wait and run again`);
} else {
const present = new Set();
let msg;
while ((msg = await channel.get(QUEUE, { noAck: true })) !== false) {
present.add(JSON.parse(msg.content.toString()).photoId);
}
const missing = confirmed.filter((id) => !present.has(id));
const extra = notConfirmed.filter((id) => present.has(id));
console.log(`in the queue: ${present.size}`);
console.log(`confirmed and present: ${confirmed.length - missing.length}`);
console.log(`confirmed but missing: ${missing.length}`);
console.log(`not confirmed but present: ${extra.length} of ${notConfirmed.length}`);
}
await channel.close();
await connection.close();
Start the broker and wait until it is up; --since "$started" skips the log lines of the previous boot. In a trial run, rabbitmqctl list_queues showed fewer messages than confirmed during the first seconds after startup. That is our observation, not a documented rule, so wait another 20 seconds. If reconcile.js still reports fewer messages than you confirmed, it does not drain: wait and run it again. Once it has drained, the lab queue is empty, so run it only once per crash test.
started=$(date +%s)
docker start rabbitmq
until docker logs --since "$started" rabbitmq 2>&1 | grep -q 'Server startup complete'; do sleep 1; done
sleep 20
node reconcile.js
in the queue: 3584
confirmed and present: 3581
confirmed but missing: 0
not confirmed but present: 3 of 59
No confirmed photoId was missing. Of the 59 unconfirmed jobs, 3 were stored and 56 lost, and the publisher could not have told which. We repeated the run with docker stop, a clean shutdown:
| How the broker stopped | Sent | Confirmed | Confirmed but missing | Not confirmed but present |
|---|---|---|---|---|
docker kill | 3,640 | 3,581 | 0 | 3 of 59 |
docker stop | 3,600 | 3,580 | 0 | 1 of 20 |
A job without a confirm may or may not be in the queue.
What a nack means
A nack is the broker saying it refuses responsibility for a message. The confirms guide says "basic.nack will only be delivered if an internal error occurs in the Erlang process responsible for a queue". The length limit guide names one more case you can trigger: a queue with x-overflow: reject-publish that is full rejects new messages, and a publisher with confirms gets a basic.nack. nack-demo.js uses that:
// nack-demo.js: a queue that refuses new messages when full, so the broker nacks them.
import amqp from 'amqplib';
const QUEUE = 'darkroom.confirms.full';
const url = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const connection = await amqp.connect(url, {
clientProperties: { connection_name: 'nack-demo' },
});
connection.on('error', (err) => console.error('connection error:', err.message));
const channel = await connection.createConfirmChannel();
channel.on('error', (err) => console.error('channel error:', err.message));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum', 'x-max-length': 5, 'x-overflow': 'reject-publish' },
});
await channel.purgeQueue(QUEUE);
for (let i = 1; i <= 8; i++) {
const photoId = `p-${i}`;
channel.sendToQueue(QUEUE, Buffer.from(photoId), {}, (err) => {
console.log(photoId, err ? `nack (${err.message})` : 'ack');
});
try {
await channel.waitForConfirms(); // one by one, so the queue sees each message in turn
} catch (err) {
console.log(' waitForConfirms rejected:', err.message);
}
}
const { messageCount } = await channel.checkQueue(QUEUE);
console.log(`queue holds ${messageCount}`);
await channel.deleteQueue(QUEUE);
await channel.close();
await connection.close();
p-1 ack
p-2 ack
p-3 ack
p-4 ack
p-5 ack
p-6 ack
p-7 nack (message nacked)
waitForConfirms rejected: message nacked
p-8 nack (message nacked)
waitForConfirms rejected: message nacked
queue holds 6
The sixth job got in although the limit is 5: the quorum queue implementation "allows a quorum queue to overshoot its limit by at least one message". The channel stays open after a nack, so the publisher can carry on. When you are done, delete the lab queue:
docker exec rabbitmq rabbitmqctl delete_queue darkroom.confirms.lab
Deleting queue 'darkroom.confirms.lab' on vhost '/' ...
Queue was successfully deleted with 0 ready messages
What to do on a nack, a timeout or a lost connection
In all three cases the publishers guide hands the message back to the publisher.
- Nack. The guide says to "remove the entry and schedule its message for republishing (or something else that's suitable)". Our advice: republishing straight into a full queue just gets another nack, so back off or alert.
- Timeout. In batch mode, "republish the entire batch or only the relevant messages". The timeout itself "should not be lower than the effective heartbeat timeout", and RabbitMQ suggests 60 seconds for that by default.
- Lost connection. "Messages that were not confirmed should be considered undelivered after a period of time. Those messages can be republished if it's safe to do so for the application."
The experiment shows why that last condition matters. Republishing all 59 unconfirmed jobs after the kill would have queued the 3 that did survive twice. Once a publisher republishes, a job can arrive more than once, so the worker must tolerate duplicates. A later lesson on idempotent consumers deals with that.
| Strategy | Throughput here | After a failure you know | Docs verdict |
|---|---|---|---|
| No confirms | 7,812–36,305 msg/s | nothing | the publisher cannot assume the message arrived |
| One by one | 269–437 msg/s | exactly which job failed | "highly discouraged" |
| Batch of 100 | 8,314–11,217 msg/s | which batch failed | "The larger the batch, the smaller the effect will be." |
| Async (streaming) | 31,019–38,251 msg/s | exactly which jobs are unconfirmed | "safe publishing with very little overhead" |
The Java tutorial's summary notes that async handling gives the best performance but "can be involved to implement correctly". For Darkroom's upload API, async confirms with a pending map are the default. Batches are fine for a one-off import script.
Why not use transactions instead?
AMQP 0-9-1 also has transactions. The confirms guide says they are the only standard way to make sure a message is not lost, but they are "unnecessarily heavyweight and decrease throughput by a factor of 250". One channel cannot use both.
Summary
sendToQueuereturningtruedoes not mean the broker has the message. A publisher confirm does.createConfirmChannelturns confirms on; the publish callback getsnullfor an ack and anErrorfor a nack or a closed channel.- Waiting after every message managed a few hundred messages per second here. Batches and async confirms are far faster, and async names each unconfirmed job.
- After a crash, every confirmed photoId was back in the queue. Unconfirmed jobs are unknown: some were stored, some lost.
- On a nack, a timeout or a lost connection, republish if that is safe for the application, and expect duplicates.
What comes next: routing with exchanges
This lesson closes chapter 2. Chapter 3 moves past the default exchange: fanout exchanges, so one photo.uploaded event reaches several services, then direct and topic exchanges that pick queues by routing key.
Sources
Looked up on 2026-11-29 against RabbitMQ 4.4 (Docker image rabbitmq:4.4.1-management), amqplib 2.4.2 and Node.js 24.18.0. Every output above comes from a real run on that date.
- RabbitMQ docs: Consumer acknowledgements and publisher confirms, Publishers, Queue length limit, Quorum queues, Heartbeats
- RabbitMQ tutorial: Publisher Confirms (Java)
- amqplib: API reference, source at tag v2.4.2 (
lib/channel.js,lib/channel_model.js)
