Publisher confirm: biết chắc broker đã nhận message
Bật publisher confirm trong amqplib, so cách chờ từng message, theo lô và bất đồng bộ trên 10.000 job, và xử lý nack, timeout.
Trong bài này (12)
- Vấn đề: sendToQueue không chứng minh được gì
- Bức tranh tổng thể: mỗi message một biên nhận
- Bật confirm trong amqplib
- Chạy thử: 10.000 job, bốn cách
- Vì sao chờ từng cái lại chậm đến vậy
- Confirm cho bạn biết gì khi broker chết?
- Nack nghĩa là gì
- Làm gì khi gặp nack, timeout hay mất kết nối
- Sao không dùng transaction?
- Tóm tắt
- Tiếp theo: định tuyến bằng exchange
- Nguồn
Bài trước kết thúc bằng một lần crash làm mất job persistent trong một queue durable. Publisher không hề biết. Bài này cho publisher tín hiệu còn thiếu đó: publisher confirm, một tờ biên nhận broker gửi lại cho mỗi message mà nó đã nhận trách nhiệm. Bạn sẽ bật confirm, đo cái giá của nó trên 10.000 job Darkroom, và làm broker crash giữa chừng.
Vấn đề: sendToQueue không chứng minh được gì
Trong Darkroom, upload API publish một job resize cho mỗi tấm ảnh. sendToQueue trả về true hoặc false, và giá trị đó chỉ cho biết write buffer của client đã đầy chưa. Nó không có nghĩa là broker đã có job. Hướng dẫn confirm nói một client đã ghi message vào socket "cannot assume that the message has reached the server and was successfully processed" (không thể cho rằng message đã tới server và được xử lý thành công).
API cần biết job nào an toàn, để gửi lại những job còn lại.
Bức tranh tổng thể: mỗi message một biên nhận
Confirm được bật theo từng channel. Client gửi confirm.select, và từ đó channel ở chế độ confirm. Từ message đầu tiên, cả hai bên đánh số mọi lần publish trên channel đó: 1, 2, 3, v.v. Mỗi basic.ack mang một trong các số đó trong delivery tag. Khi cờ multiple được bật, ack còn phủ mọi số nhỏ hơn đang chờ.
Khi nào ack tới? Tài liệu liệt kê các trường hợp ở mục khi nào message đã publish được confirm:
- message tới được queue thì được ack khi mọi queue đó đã nhận nó;
- nếu message persistent và queue durable, nhận nghĩa là đã ghi xuống đĩa;
- với quorum queue, đa số replica của nó phải có message;
- nếu không queue nào khớp, broker confirm ngay khi exchange biết điều đó.
Vậy riêng một ack chưa chứng minh có queue nào giữ job. Bài về mô hình AMQP đã chỉ cách bắt message không route được bằng mandatory.
Bật confirm trong amqplib
Trong amqplib 2.4.2, bạn mở một loại channel khác bằng createConfirmChannel. Trên một confirm channel, publish và sendToQueue nhận thêm một tham số: một callback. Theo mã nguồn 2.4.2 (lib/channel.js): ack gọi nó với null, nack gọi với Error('message nacked'), và nếu channel đóng trước, mọi callback đang chờ nhận Error('channel closed'). Khi truyền callback, bạn cũng phải truyền options, dù chỉ là {} (API reference).
waitForConfirms() cho bạn một promise cho mọi thứ đã publish tới lúc đó: resolve khi tất cả được confirm, và reject khi có nack hoặc channel đóng trước. Mã nguồn 2.4.2 (lib/channel.js) không đặt timeout nào cho nó.
Chạy thử: 10.000 job, bốn cách
Tài liệu RabbitMQ mô tả ba chiến lược, và tutorial Java viết code cho cả ba; tutorial này không có bản JavaScript. Dưới đây là ba cách đó bằng amqplib, thêm một mốc so sánh không dùng confirm. Tạo project như ở bài Node.js (type=module, amqplib@2.4.2), dùng broker của bài Docker, rồi lưu 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();
Các script dùng một queue thí nghiệm, darkroom.confirms.lab, là quorum queue giống darkroom.resize của các bài trước, nên queue thật của bạn không bị đụng tới. Mọi job đều persistent. Chạy từng chế độ:
node publish-jobs.js none
node publish-jobs.js one-by-one
node publish-jobs.js batch
node publish-jobs.js async
Lượt đầu trên máy của mình:
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
Các số này đến từ một chiếc laptop (16 CPU, Linux, broker chạy Docker trên cùng máy), ba lượt liên tiếp, trong lúc các container khác vẫn chạy. Một loạt lượt chạy trước đó cho 219–349 msg/s khi chờ từng cái. Hãy xem các số này là cỡ độ lớn, không phải benchmark:
| Chế độ | Lượt 1 | Lượt 2 | Lượt 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 |
Vì sao chờ từng cái lại chậm đến vậy
Mỗi lần chờ tốn trọn một round trip (một lượt đi-về mạng) cộng phần việc broker phải làm trước khi ack: với quorum queue là ghi vào Raft log trên đĩa (và nhân bản, nếu chạy cluster). Tutorial Java cảnh báo cách này "won't deliver more than a few hundred published messages per second" (không vượt quá vài trăm message mỗi giây), đúng như mình thấy, và hướng dẫn publisher nói publish-rồi-chờ "is not recommended" (không được khuyến nghị). Theo lô thì trả cái giá chờ đó một lần cho mỗi 100 job. Chế độ async không bao giờ dừng để chờ, nên nhiều job cùng đang bay và broker có thể trả lời bằng ack multiple. Với message persistent khi tải đều liên tục, hướng dẫn confirm cảnh báo "latency for basic.ack can reach a few hundred milliseconds" (độ trễ của basic.ack có thể tới vài trăm mili giây), và khuyên xử lý ack bất đồng bộ hoặc theo lô.
Confirm cho bạn biết gì khi broker chết?
crash-test.js publish cùng 10.000 job với confirm bất đồng bộ, nhưng chậm (20 job mỗi 10 ms), để bạn kịp dừng broker giữa chừng:
// 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);
}
Chạy nó, khoảng hai giây sau thì kill broker từ terminal thứ hai. docker kill gửi SIGKILL, nên RabbitMQ không có cơ hội tắt êm:
node crash-test.js # terminal 1
docker kill rabbitmq # terminal 2
connection error: Unexpected close
channel closed: sent 3640, confirmed 3581, not confirmed 59
Script lưu cả hai danh sách photoId vào confirmed.json. Sau khi restart, reconcile.js lấy hết message khỏi queue thí nghiệm và so id:
// 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();
Khởi động broker và đợi tới khi nó chạy xong; --since "$started" bỏ qua các dòng log của lần khởi động trước. Ở một lượt chạy thử, rabbitmqctl list_queues hiện ít message hơn số đã confirm trong vài giây đầu sau khi khởi động. Đó là quan sát của mình, không phải quy tắc có trong tài liệu, nên hãy đợi thêm 20 giây. Nếu reconcile.js vẫn báo ít message hơn số bạn đã confirm, nó sẽ không lấy message ra: hãy đợi rồi chạy lại. Khi nó đã lấy hết thì queue thí nghiệm trống, nên mỗi lần crash test chỉ chạy nó một lần.
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
Không photoId đã confirm nào bị thiếu. Trong 59 job chưa confirm, 3 được lưu và 56 mất, và publisher không thể biết job nào là job nào. Mình chạy lại thí nghiệm với docker stop, một lần tắt êm:
| Broker dừng bằng cách nào | Đã gửi | Đã confirm | Đã confirm nhưng thiếu | Chưa confirm nhưng có mặt |
|---|---|---|---|---|
docker kill | 3.640 | 3.581 | 0 | 3 trên 59 |
docker stop | 3.600 | 3.580 | 0 | 1 trên 20 |
Một job chưa có confirm có thể có hoặc không có trong queue.
Nack nghĩa là gì
Nack là broker nói nó từ chối nhận trách nhiệm cho một message. Hướng dẫn confirm nói "basic.nack will only be delivered if an internal error occurs in the Erlang process responsible for a queue" (chỉ gửi khi có lỗi nội bộ trong process Erlang phụ trách một queue). Hướng dẫn giới hạn độ dài nêu thêm một trường hợp bạn tự tạo được: queue có x-overflow: reject-publish khi đầy sẽ từ chối message mới, và publisher có bật confirm nhận basic.nack. nack-demo.js dùng cách đó:
// 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
Job thứ sáu vẫn vào dù giới hạn là 5: cách quorum queue được hiện thực "allows a quorum queue to overshoot its limit by at least one message" (cho phép vượt giới hạn ít nhất một message). Channel vẫn mở sau một nack, nên publisher làm tiếp được. Làm xong thì xoá queue thí nghiệm:
docker exec rabbitmq rabbitmqctl delete_queue darkroom.confirms.lab
Deleting queue 'darkroom.confirms.lab' on vhost '/' ...
Queue was successfully deleted with 0 ready messages
Làm gì khi gặp nack, timeout hay mất kết nối
Cả ba trường hợp, hướng dẫn publisher đều trả message về cho publisher.
- Nack. Hướng dẫn bảo "remove the entry and schedule its message for republishing (or something else that's suitable)" (xoá mục đó và lên lịch publish lại message, hoặc làm việc khác cho phù hợp). Lời khuyên của mình: publish lại thẳng vào một queue đầy chỉ nhận thêm một nack, nên hãy chờ lùi dần (back off) hoặc báo động.
- Timeout. Ở chế độ theo lô, "republish the entire batch or only the relevant messages" (publish lại cả lô hoặc chỉ những message liên quan). Bản thân timeout "should not be lower than the effective heartbeat timeout" (không nên thấp hơn heartbeat timeout thực tế), và RabbitMQ đề xuất mặc định 60 giây cho giá trị đó.
- Mất kết nối. "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." (Message chưa được confirm nên coi là chưa giao sau một khoảng thời gian, và có thể publish lại nếu việc đó an toàn với ứng dụng.)
Thí nghiệm cho thấy vì sao điều kiện cuối quan trọng. Publish lại cả 59 job chưa confirm sau lần kill sẽ đưa 3 job đã sống sót vào queue hai lần. Một khi publisher publish lại, một job có thể tới nhiều hơn một lần, nên worker phải chịu được trùng lặp. Một bài sau về consumer idempotent sẽ xử lý chuyện đó.
| Chiến lược | Throughput ở đây | Sau sự cố bạn biết | Tài liệu đánh giá |
|---|---|---|---|
| Không confirm | 7.812–36.305 msg/s | không biết gì | publisher không thể cho rằng message đã tới |
| Từng cái một | 269–437 msg/s | chính xác job nào lỗi | "highly discouraged" (rất không khuyến khích) |
| Lô 100 | 8.314–11.217 msg/s | lô nào lỗi | "The larger the batch, the smaller the effect will be." (lô càng lớn, ảnh hưởng càng nhỏ) |
| Bất đồng bộ (streaming) | 31.019–38.251 msg/s | chính xác job nào chưa confirm | "safe publishing with very little overhead" (publish an toàn, chi phí rất nhỏ) |
Phần tóm tắt của tutorial Java ghi rằng xử lý bất đồng bộ cho hiệu năng tốt nhất nhưng "can be involved to implement correctly" (có thể khá rắc rối để viết cho đúng). Với upload API của Darkroom, confirm bất đồng bộ kèm một map đang chờ là mặc định. Theo lô thì ổn cho một script import chạy một lần.
Sao không dùng transaction?
AMQP 0-9-1 còn có transaction. Hướng dẫn confirm nói đó là cách chuẩn duy nhất để chắc message không mất, nhưng transaction "unnecessarily heavyweight and decrease throughput by a factor of 250" (nặng nề không cần thiết và giảm throughput 250 lần). Một channel không thể dùng cả hai.
Tóm tắt
sendToQueuetrả vềtruekhông có nghĩa broker đã có message. Publisher confirm mới cho biết điều đó.createConfirmChannelbật confirm; callback của publish nhậnnullkhi ack và mộtErrorkhi nack hoặc channel đóng.- Chờ sau mỗi message chỉ được vài trăm message mỗi giây ở đây. Theo lô và bất đồng bộ nhanh hơn nhiều, và bất đồng bộ chỉ đích danh từng job chưa confirm.
- Sau một lần crash, mọi photoId đã confirm đều có lại trong queue. Job chưa confirm là chưa rõ: có job được lưu, có job mất.
- Khi gặp nack, timeout hay mất kết nối, publish lại nếu điều đó an toàn với ứng dụng, và chuẩn bị cho trùng lặp.
Tiếp theo: định tuyến bằng exchange
Bài này khép lại chương 2. Chương 3 đi xa hơn default exchange: fanout exchange, để một sự kiện photo.uploaded tới được nhiều service, rồi direct và topic exchange chọn queue theo routing key.
Nguồn
Tra ngày 2026-11-29 trên RabbitMQ 4.4 (Docker image rabbitmq:4.4.1-management), amqplib 2.4.2 và Node.js 24.18.0. Mọi output ở trên đến từ một lần chạy thật trong ngày đó.
- Tài liệu RabbitMQ: Consumer acknowledgements and publisher confirms, Publishers, Queue length limit, Quorum queues, Heartbeats
- Tutorial RabbitMQ: Publisher Confirms (Java)
- amqplib: API reference, mã nguồn ở tag v2.4.2 (
lib/channel.js,lib/channel_model.js)
