Work queue và chia việc công bằng bằng prefetch
Chạy ba worker RabbitMQ trên một queue, thấy round-robin dồn hết job chậm cho một worker, và sửa bằng prefetch theo consumer trong amqplib.
Ở bài trước, một worker ack từng job sau khi làm xong. Giờ Darkroom đông việc, nên bạn chạy ba worker trên cùng một queue. RabbitMQ chia job cho chúng, nhưng khi job to nhỏ khác nhau, cách chia có thể để hai worker ngồi không. Trong bài này, bạn đo thời gian xong một lô job lẫn lộn, xem worker nào nhận job nào, và sửa cách chia bằng một dòng: channel.prefetch(1).
Vấn đề: một queue, ba worker, job không đều
Job resize của Darkroom không cùng cỡ. Một thumbnail mất chưa tới một giây. Một ảnh panorama lớn mất vài giây. Bạn chạy ba bản worker trên darkroom.resize và mong lô job xong nhanh gấp khoảng ba lần.
Mẫu này gọi là work queue: nhiều consumer trên một queue, mỗi message chỉ do đúng một consumer xử lý. Tutorial work queue chính thức minh hoạ nó bằng đúng client bạn dùng ở đây. Mặc định, RabbitMQ chia message cho các consumer theo vòng, mỗi lượt một cái. Job đều nhau thì ổn. Job lẫn lộn thì một worker có thể ôm hết các job nặng.
Chạy thử và quan sát
Bạn cần broker của bài 2 (container rabbitmq) và một project dựng như ở bài 3, với amqplib@2.4.2.
Worker: photo-worker.js
Worker nhận một giá trị prefetch tuỳ chọn từ dòng lệnh. Không có giá trị đó, worker không đặt giới hạn nào. Phần "resize" là một vòng lặp bận, nên mỗi process làm từng job một, giống một lần resize tốn CPU thật trong Node.js: 200 ms cho thumbnail, 2.000 ms cho panorama. AMQP_URL chỉ để bạn trỏ sang broker khác; mặc định là broker trên máy.
// photo-worker.js: one Darkroom resize worker.
// Usage: node photo-worker.js <name> [prefetch] (no prefetch = no limit)
import amqp from 'amqplib';
const QUEUE = 'darkroom.resize';
const URL = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const name = process.argv[2] ?? 'w1';
const prefetch = process.argv[3];
const WORK_MS = { thumbnail: 200, panorama: 2000 };
// Stands in for resizing: busy CPU work that blocks this process, like a real resize.
function resize(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {}
}
const connection = await amqp.connect(URL, {
clientProperties: { connection_name: `photo-worker-${name}` },
});
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));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
if (prefetch !== undefined) {
await channel.prefetch(Number(prefetch)); // per consumer, for consumers started after this
}
await channel.consume(QUEUE, (msg) => {
if (msg === null) return;
const job = JSON.parse(msg.content.toString());
resize(WORK_MS[job.kind]);
channel.ack(msg);
const at = ((Date.now() - job.sentAt) / 1000).toFixed(1);
console.log(`${name} done ${job.photoId} ${job.kind} at ${at}s`);
});
console.log(`${name} ready, prefetch ${prefetch ?? 'unlimited'}`);
process.once('SIGINT', async () => {
await channel.close();
await connection.close();
});
Mỗi dòng log cho biết job xong lúc nào, tính từ lúc gửi lô. Dòng cuối cùng trên cả ba terminal là thời gian cả lô.
Lô job: send-batch.js
Mười hai job. Cứ ba job thì có một panorama, bắt đầu từ job đầu tiên.
// send-batch.js: the Darkroom API drops a batch of 12 resize jobs into the queue.
// Every third job is a large panorama; the rest are small thumbnails.
import amqp from 'amqplib';
const QUEUE = 'darkroom.resize';
const URL = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const connection = await amqp.connect(URL, {
clientProperties: { connection_name: 'send-batch' },
});
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));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
const sentAt = Date.now();
for (let i = 1; i <= 12; i++) {
const kind = i % 3 === 1 ? 'panorama' : 'thumbnail';
const job = { photoId: `p-${100 + i}`, kind, sentAt };
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(job)), {
contentType: 'application/json',
});
}
console.log('sent 12 jobs: 4 panoramas, 8 thumbnails');
await channel.close();
await connection.close();
Lượt 1: không giới hạn prefetch
Chạy ba worker trước, mỗi worker một terminal, để cả ba đã đăng ký nhận trước khi job nào tới:
node photo-worker.js w1
node photo-worker.js w2
node photo-worker.js w3
Kiểm tra RabbitMQ thấy ba consumer, ack thủ công và không giới hạn. Trong tài liệu rabbitmqctl, cột prefetch là "an integer indicating the prefetch limit (with 0 meaning "none")" (một số nguyên chỉ giới hạn prefetch, 0 nghĩa là không có):
docker exec rabbitmq rabbitmqctl list_consumers queue_name ack_required prefetch_count -q
queue_name ack_required prefetch_count
darkroom.resize true 0
darkroom.resize true 0
darkroom.resize true 0
Gửi lô bằng node send-batch.js. Ba terminal in ra:
w1 ready, prefetch unlimited
w1 done p-103 thumbnail at 0.2s
w1 done p-106 thumbnail at 0.4s
w1 done p-109 thumbnail at 0.6s
w1 done p-112 thumbnail at 0.8s
w2 ready, prefetch unlimited
w2 done p-101 panorama at 2.0s
w2 done p-104 panorama at 4.0s
w2 done p-107 panorama at 6.0s
w2 done p-110 panorama at 8.0s
w3 ready, prefetch unlimited
w3 done p-102 thumbnail at 0.2s
w3 done p-105 thumbnail at 0.4s
w3 done p-108 thumbnail at 0.6s
w3 done p-111 thumbnail at 0.8s
Lô job mất 8,0 giây. w2 nhận job 1, 4, 7 và 10: cả bốn panorama. Worker nào nhận chúng tuỳ vào thứ tự các worker đăng ký nhận; trong lần chạy của mình là w2. w1 và w3 làm xong thumbnail trước giây thứ 1, rồi ngồi không 7 giây trong khi ba panorama nằm chờ sau panorama đầu tiên của w2.
Lượt 2: prefetch 1
Dừng các worker bằng Ctrl+C và chạy lại với prefetch 1:
node photo-worker.js w1 1
node photo-worker.js w2 1
node photo-worker.js w3 1
Giờ list_consumers cho thấy prefetch_count bằng 1 với cả ba consumer. Gửi lại đúng lô đó:
w1 ready, prefetch 1
w1 done p-103 thumbnail at 0.2s
w1 done p-105 thumbnail at 0.5s
w1 done p-106 thumbnail at 0.7s
w1 done p-107 panorama at 2.7s
w2 ready, prefetch 1
w2 done p-102 thumbnail at 0.2s
w2 done p-104 panorama at 2.3s
w2 done p-110 panorama at 4.3s
w3 ready, prefetch 1
w3 done p-101 panorama at 2.0s
w3 done p-108 thumbnail at 2.2s
w3 done p-109 thumbnail at 2.4s
w3 done p-111 thumbnail at 2.6s
w3 done p-112 thumbnail at 2.8s
Lô job mất 4,3 giây. Mỗi job đến tay worker nào đang rảnh. Bốn panorama trên ba worker nghĩa là một worker phải làm hai cái, nên 4 giây là mức thấp nhất cho lô này.
| Không giới hạn prefetch | prefetch(1) | |
|---|---|---|
w1 nhận | 4 thumbnail | 3 thumbnail, 1 panorama |
w2 nhận | 4 panorama | 1 thumbnail, 2 panorama |
w3 nhận | 4 thumbnail | 1 panorama, 4 thumbnail |
| Lô xong lúc | 8,0 s | 4,3 s |
| Ngồi không trong khi job còn chờ | khoảng 7 s (w1, w3) | không; w1 và w3 dừng lúc 2,7 s và 2,8 s, khi queue đã hết job |
Vì sao round-robin chia sai
Tutorial giải thích chuyện này: "This happens because RabbitMQ just dispatches a message when the message enters the queue. It doesn't look at the number of unacknowledged messages for a consumer." (Chuyện này xảy ra vì RabbitMQ cứ gửi message đi khi nó vào queue, không nhìn số message chưa ack của consumer.) Không có giới hạn, cả mười hai job rời queue cùng lúc, chia lần lượt cho ba worker. Cứ ba job thì một job về cùng một worker, và trong lô này cứ ba job thì có một panorama. Các job đó đã giao cho w2 và chưa được ack, nên không worker nào khác lấy được.
Giới hạn prefetch đổi luật chơi. Theo trang consumer prefetch, basic.qos có mặt "to limit the number of unacknowledged messages" (để giới hạn số message chưa ack). Với giới hạn 1, worker chỉ nhận job kế tiếp sau khi ack job hiện tại. Phần còn lại nằm trong queue, chờ worker nào ack trước. Vì thế chia việc công bằng cần ack thủ công: với auto ack, docs ghi "there is no such limit by definition" (theo định nghĩa không có giới hạn như vậy).
Prefetch theo consumer và prefetch global
AMQP 0-9-1 đặt prefetch bằng method basic.qos, mang một con số và một cờ global. Trang consumer prefetch ghi nghĩa theo spec là "shared across all consumers on the channel" (chia chung cho mọi consumer trên channel), còn nghĩa của RabbitMQ là "applied separately to each new consumer on the channel" (áp riêng cho từng consumer mới trên channel). RabbitMQ dùng global bằng true cho một giới hạn theo channel, chia chung cho các consumer đó.
Mã nguồn amqplib 2.4.2 cho thấy channel.prefetch(count, global) ánh xạ vào đó thế nào. prefetch là tên khác của qos, hàm gửi basic.qos (lib/channel_model.js). Tham số thành prefetchCount: count || 0, prefetchSize: 0 và global: !!global, nên bỏ trống global thì gửi false (lib/api_args.js):
| Lệnh amqplib | basic.qos gửi đi | Ý nghĩa trên RabbitMQ 4.4 |
|---|---|---|
prefetch(1) | count 1, global false | tối đa 1 message chưa ack cho mỗi consumer tạo sau lệnh |
prefetch(0) hoặc không gọi | count 0, hoặc không gửi gì | không giới hạn: 0 "is treated as infinite" (được coi là vô hạn) |
prefetch(15, true) | count 15, global true | một giới hạn chung cho các consumer của channel; deprecated, mặc định không được phép từ 4.3 |
Vì giới hạn áp cho từng consumer mới, hãy gọi prefetch trước consume, như worker đang làm.
Trang consumer prefetch ghi: "Global (per-channel) QoS prefetch is deprecated and disabled by default starting with RabbitMQ 4.3." (Prefetch QoS global, theo channel, đã deprecated và tắt mặc định từ RabbitMQ 4.3.) Quorum queue hoàn toàn không hỗ trợ nó. Docs quorum queue ghi: "If an attempt is made to consume from a quorum queue from a channel with global QoS activated a channel error will be returned." (Nếu consume từ quorum queue qua một channel đang bật global QoS, bạn sẽ nhận channel error.) Đây là điều một broker 4.4.1 với cấu hình mặc định đã làm. global-qos.js publish 20 job vào một queue dùng một lần, đặt prefetch, rồi mở hai consumer trên một channel và không bao giờ ack:
// global-qos.js: does prefetch(count, true) share one limit across a channel?
// Usage: node global-qos.js <count> <global: true|false>
import amqp from 'amqplib';
const QUEUE = 'darkroom.qos-test'; // a throwaway queue, deleted at the end
const URL = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
const count = Number(process.argv[2] ?? 3);
const global = process.argv[3] === 'true';
const connection = await amqp.connect(URL, {
clientProperties: { connection_name: 'global-qos-test' },
});
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));
await channel.assertQueue(QUEUE, {
durable: true,
arguments: { 'x-queue-type': 'quorum' },
});
for (let i = 1; i <= 20; i++) channel.sendToQueue(QUEUE, Buffer.from(`job ${i}`));
await channel.prefetch(count, global);
let received = 0;
// two consumers on the same channel, neither ever acks
await channel.consume(QUEUE, () => { received++; });
await channel.consume(QUEUE, () => { received++; });
await new Promise((r) => setTimeout(r, 1000));
console.log(`prefetch(${count}, ${global}): ${received} of 20 delivered to 2 consumers on one channel, no acks`);
await channel.deleteQueue(QUEUE);
await connection.close();
node global-qos.js 3 false
node global-qos.js 3 true
docker logs rabbitmq 2>&1 | grep -m1 -A4 'Feature `global_qos`'
prefetch(3, false): 6 of 20 delivered to 2 consumers on one channel, no acks
prefetch(3, true): 6 of 20 delivered to 2 consumers on one channel, no acks
2026-11-29 16:32:31.472801+00:00 [error] <0.1264.0> Deprecated features: `global_qos`: Feature `global_qos` is deprecated.
2026-11-29 16:32:31.472801+00:00 [error] <0.1264.0> By default, this feature is not permitted anymore.
2026-11-29 16:32:31.472801+00:00 [error] <0.1264.0> The feature will be removed from a future major RabbitMQ version, regardless of the configuration; actual version to be determined.
2026-11-29 16:32:31.472801+00:00 [error] <0.1264.0> To continue using this feature when it is not permitted by default, set the following parameter in your configuration:
2026-11-29 16:32:31.472801+00:00 [error] <0.1264.0> "deprecated_features.permit.global_qos = true"
Trong lần chạy của mình, cả hai lệnh đều cho 3 mỗi consumer, tổng 6. Lệnh true không báo lỗi gì ở client. Dấu hiệu duy nhất là thông báo deprecated, broker ghi một lần, ở lần dùng đầu tiên kể từ khi khởi động; với container đã chạy lâu, grep -m1 cho thấy dòng đầu tiên đó, có thể cũ hơn lần thử của bạn. Trong một container thử thứ hai của lần chạy đó, có deprecated_features.permit.global_qos = true, cùng lệnh prefetch(3, true) trên quorum queue này đóng cả connection với 540 NOT_IMPLEMENTED ... does not support global qos, không chỉ channel. Trên classic queue, nó chia chung giới hạn: tổng 3. Đừng dựa vào cách nào trong hai: hãy dùng prefetch theo consumer.
Chọn giá trị prefetch thế nào?
Docs đưa ra khoảng giá trị, không đưa công thức. Từ hướng dẫn acknowledgement:
| Prefetch | Docs nói gì | Hợp với Darkroom khi |
|---|---|---|
| 0 (không giới hạn) | "should be used with care" (nên dùng cẩn thận); consumer giữ nhiều message chưa ack sẽ dùng bộ nhớ ngày càng nhiều | không bao giờ, với worker resize |
| 1 | "the most conservative" (thận trọng nhất); "will significantly reduce throughput" (sẽ giảm throughput đáng kể) | job mất hàng trăm ms hoặc vài giây và to nhỏ khác nhau |
| 100 tới 300 | "usually offer optimal throughput" (thường cho throughput tối ưu) | một dòng job rất nhỏ và nhanh, đã đo trước |
Với worker resize của Darkroom, 1 là điểm bắt đầu đúng. Ở lượt 2 trong lần chạy của mình, khoảng nghỉ giữa hai job khoảng 0,1 s hoặc ít hơn, rất nhỏ so với một thumbnail 200 ms. Docs quorum queue nói thêm: "Quorum queues also benefit from consumers using higher prefetch values to ensure consumers aren't starved whilst acknowledgements are flowing through the system" (quorum queue cũng được lợi khi consumer dùng prefetch cao hơn, để consumer không bị đói việc trong lúc ack đang trên đường). Nếu job của worker rất nhỏ, hãy đo vài giá trị như bạn vừa làm ở đây, rồi giữ giá trị xong nhanh nhất.
Consumer không đặt prefetch có thể nhận một giá trị mặc định cho cả broker, default_consumer_prefetch trong file advanced config. Đặt nó trong code thì hành vi của worker hiện ngay ở chỗ bạn đọc code.
Tóm tắt
- Work queue là nhiều consumer trên một queue; mỗi message đến một consumer.
- Không có giới hạn prefetch, RabbitMQ chia message lần lượt ngay khi chúng tới, bất kể mỗi consumer bận cỡ nào. Một worker nhận cả bốn panorama, và lô job mất 8,0 s.
channel.prefetch(1)trướcconsumechỉ giao job mới cho worker sau khi nó ack job trước. Cùng lô đó mất 4,3 s.- Prefetch đếm các lần giao chưa ack, nên nó cần ack thủ công.
- Trong amqplib,
prefetch(count)là theo consumer.prefetch(count, true)xin QoS global theo channel, thứ đã deprecated, mặc định không được phép từ RabbitMQ 4.3 và quorum queue không hỗ trợ. - Bắt đầu với 1 cho job chậm, không đều; docs gợi ý 100–300 để tối ưu throughput với job nhỏ.
Giờ job đã được chia công bằng trong lúc worker giữ chúng. Bài tiếp theo hỏi chuyện gì xảy ra với các job còn đang chờ khi chính broker khởi động lại.
Nguồn
Kiểm ngày 2026-11-29 với RabbitMQ 4.4 (Docker image rabbitmq:4.4.1-management), amqplib 2.4.2 và Node.js 24.18.0. Mọi output trong bài lấy từ lần chạy thật của code ở trên.
- Tutorial RabbitMQ: Work Queues in JavaScript
- Docs RabbitMQ: Consumer prefetch, Consumer acknowledgements and publisher confirms, Quorum queues, Deprecated features, rabbitmqctl(8)
- amqplib: API reference,
prefetch, mã nguồn ở tag v2.4.2: lib/channel_model.js, lib/api_args.js
