Work Queues and Fair Dispatch with Prefetch
Run three RabbitMQ workers on one queue, watch round-robin hand all the slow jobs to one of them, and fix it with per-consumer prefetch in amqplib.
In the previous lesson one worker acknowledged each job after finishing it. Now Darkroom gets busy, so you start three workers on the same queue. RabbitMQ shares the jobs between them, but when job sizes differ, the split can leave two workers idle. In this lesson you measure how long a mixed batch takes, see which worker got which job, and fix the split with one line: channel.prefetch(1).
The problem: one queue, three workers, uneven jobs
Darkroom's resize jobs are not all the same size. A thumbnail takes a fraction of a second. A large panorama takes seconds. You run three copies of the worker on darkroom.resize and expect the batch to finish about three times faster.
This pattern is called a work queue: several consumers on one queue, each message handled by exactly one of them. The official work queues tutorial shows it with the same client you use here. Out of the box, RabbitMQ deals the messages to the consumers in rotation, one each. With equal jobs that is fine. With mixed jobs, one worker can end up with all the heavy ones.
Run it and see
You need the broker from lesson 2 (container rabbitmq) and a project set up as in lesson 3, with amqplib@2.4.2.
The worker: photo-worker.js
The worker takes an optional prefetch value from the command line. Without it, the worker sets no limit. The "resize" is a busy loop, so each process does one job at a time, like a real CPU-bound resize in Node.js: 200 ms for a thumbnail, 2,000 ms for a panorama. AMQP_URL only lets you point it at another broker; the default is the local one.
// 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();
});
Each log line says when the job finished, counted from the moment the batch was sent. The last line across all three terminals is the time the whole batch took.
The batch: send-batch.js
Twelve jobs. Every third one, starting with the first, is a panorama.
// 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();
Round 1: no prefetch limit
Start the three workers first, each in its own terminal, so all three are subscribed before any job arrives:
node photo-worker.js w1
node photo-worker.js w2
node photo-worker.js w3
Check that RabbitMQ sees three consumers with manual acks and no limit. In the rabbitmqctl manual, the prefetch column is "an integer indicating the prefetch limit (with 0 meaning "none")":
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
Send the batch with node send-batch.js. The three terminals print:
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
The batch took 8.0 seconds. w2 got jobs 1, 4, 7 and 10: all four panoramas. Which worker gets them depends on the order the workers subscribed; in our run it was w2. w1 and w3 finished their thumbnails before 1 second and then sat idle for 7 seconds while three panoramas waited behind w2's first one.
Round 2: prefetch 1
Stop the workers with Ctrl+C and start them again with a prefetch of 1:
node photo-worker.js w1 1
node photo-worker.js w2 1
node photo-worker.js w3 1
list_consumers now shows prefetch_count 1 for each of the three consumers. Send the same batch:
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
The batch took 4.3 seconds. Each job went to whichever worker was free. Four panoramas on three workers means one worker must do two, so 4 seconds is the floor for this batch.
| No prefetch limit | prefetch(1) | |
|---|---|---|
w1 got | 4 thumbnails | 3 thumbnails, 1 panorama |
w2 got | 4 panoramas | 1 thumbnail, 2 panoramas |
w3 got | 4 thumbnails | 1 panorama, 4 thumbnails |
| Batch finished at | 8.0 s | 4.3 s |
| Idle while jobs waited | about 7 s (w1, w3) | none; w1 and w3 stopped at 2.7 s and 2.8 s, when the queue was empty |
Why round-robin went wrong
The tutorial explains it: "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." With no limit, all twelve jobs left the queue at once, dealt to the three workers in turn. Every third job went to the same worker, and in this batch every third job was a panorama. Those jobs were already delivered to w2 and unacknowledged, so no other worker could take them.
A prefetch limit changes the rule. basic.qos exists, the consumer prefetch page says, "to limit the number of unacknowledged messages". With a limit of 1, a worker gets its next job only after it acks the current one. The rest stay in the queue, ready for whoever acks first. That is why fair dispatch needs manual acks: with automatic acks, the docs say, "there is no such limit by definition".
Per-consumer and global prefetch
AMQP 0-9-1 sets prefetch with the basic.qos method, which carries a count and a global flag. The consumer prefetch page puts the spec's meaning as "shared across all consumers on the channel" and RabbitMQ's as "applied separately to each new consumer on the channel". RabbitMQ uses global set to true for a per-channel limit shared by those consumers.
The amqplib 2.4.2 source shows how channel.prefetch(count, global) maps to it. prefetch is another name for qos, which sends basic.qos (lib/channel_model.js). The arguments become prefetchCount: count || 0, prefetchSize: 0 and global: !!global, so leaving global out sends false (lib/api_args.js):
| amqplib call | basic.qos sent | Meaning on RabbitMQ 4.4 |
|---|---|---|
prefetch(1) | count 1, global false | at most 1 unacked message for each consumer started after the call |
prefetch(0) or no call | count 0, or nothing | no limit: 0 "is treated as infinite" |
prefetch(15, true) | count 15, global true | one limit shared by the channel's consumers; deprecated, not permitted by default since 4.3 |
Because the limit applies to each new consumer, call prefetch before consume, as the worker does.
The consumer prefetch page says: "Global (per-channel) QoS prefetch is deprecated and disabled by default starting with RabbitMQ 4.3." Quorum queues do not support it at all. The quorum queue docs say: "If an attempt is made to consume from a quorum queue from a channel with global QoS activated a channel error will be returned." Here is what a 4.4.1 broker with default settings did. global-qos.js publishes 20 jobs to a throwaway queue, sets the prefetch, and starts two consumers on one channel that never 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"
In our run, both calls gave 3 per consumer, 6 in total. The true call raised no error in the client. The only sign was the deprecation message, which the broker logs once, on the first use since it started; on a container that has run for a while, grep -m1 shows that first line, which can be older than your test. In a second test container from our run, with deprecated_features.permit.global_qos = true, the same prefetch(3, true) on this quorum queue closed the connection with 540 NOT_IMPLEMENTED ... does not support global qos, not only the channel. On a classic queue it shared the limit: 3 in total. Do not rely on either: use per-consumer prefetch.
How do I choose a prefetch value?
The docs give ranges, not a formula. From the acknowledgements guide:
| Prefetch | What the docs say | Fits Darkroom when |
|---|---|---|
| 0 (unlimited) | "should be used with care"; a consumer holding many unacked messages uses more and more memory | never for resize workers |
| 1 | "the most conservative"; "will significantly reduce throughput" | jobs take hundreds of ms or seconds and vary in size |
| 100 to 300 | "usually offer optimal throughput" | a stream of tiny, quick jobs, measured first |
For Darkroom's resize workers, 1 is the right start. In round 2 of our run, the gap between one job and the next was about 0.1 s or less, small next to a 200 ms thumbnail. The quorum queue docs add: "Quorum queues also benefit from consumers using higher prefetch values to ensure consumers aren't starved whilst acknowledgements are flowing through the system". If a worker's jobs are tiny, measure with a few values, as you did here, and keep the one that finishes fastest.
A consumer that sets no prefetch can get a broker-wide default, default_consumer_prefetch in the advanced config file. Setting it in code keeps the worker's behaviour visible where you read it.
Summary
- A work queue is several consumers on one queue; each message goes to one of them.
- Without a prefetch limit, RabbitMQ deals messages out in turn as they arrive, regardless of how busy each consumer is. One worker got all four panoramas, and the batch took 8.0 s.
channel.prefetch(1)beforeconsumegives a worker a new job only after it acks the last one. The same batch took 4.3 s.- Prefetch counts unacknowledged deliveries, so it needs manual acks.
- In amqplib,
prefetch(count)is per consumer.prefetch(count, true)asks for global, per-channel QoS, which is deprecated and not permitted by default since RabbitMQ 4.3 and not supported by quorum queues. - Start with 1 for slow, uneven jobs; the docs point to 100–300 for throughput with small ones.
The jobs are now shared fairly while workers hold them. The next lesson asks what happens to the jobs still waiting when the broker itself restarts.
Sources
Checked 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 in this lesson comes from a real run of the code above.
- RabbitMQ tutorial: Work Queues in JavaScript
- RabbitMQ docs: Consumer prefetch, Consumer acknowledgements and publisher confirms, Quorum queues, Deprecated features, rabbitmqctl(8)
- amqplib: API reference,
prefetch, source at tag v2.4.2: lib/channel_model.js, lib/api_args.js
