Skip to content
Fullstack Launchpad

When Should You Use a Message Queue?

Measure an upload API that resizes in the request against one that queues the job, then weigh the costs of a queue and when not to use one.

Lesson 1By Published 10 min readRabbitMQ: The Complete Guide
A hand-drawn orange post box with a yellow letter dropping into its slot and the word later on the front

This course follows Darkroom, a small photo service that makes thumbnails of uploaded photos, tags them and indexes them for search. In this first lesson you build two versions of the upload endpoint, time both, and decide which work belongs in a queue and which does not.

The problem: an upload that waits for a resize

The first version of Darkroom does everything inside the HTTP request. The photo arrives, the API resizes it to 256 px and 1024 px, and only then does it answer. In our experiment the resize takes about 2 seconds, so every upload does too.

That hurts in three ways:

  • The user waits for work they do not need right now.
  • If the resize step breaks, the upload fails too, though the photo arrived fine.
  • A traffic spike lands straight on the resize code, with no place for extra work to wait.

The client waits while the upload API resizes the photo for 2 s; the reply is a 201 after 2008 ms

The big picture: drop the job in a mailbox

Think of a post box. You drop a letter in the slot and walk away. The post office delivers it at its own pace.

A message queue gives your code the same deal. The RabbitMQ docs define a queue as "an ordered collection of messages", enqueued at the tail and delivered to consumers from the head, first in, first out. Three roles appear in every lesson of this course:

  • A producer sends a message. Here it is the upload API, and the message is a resize job.
  • A queue holds messages until someone takes them. RabbitMQ is the broker that keeps the queue.
  • A consumer takes messages and does the work. Here it is a resize worker.

The official work queues tutorial builds on this: heavy work leaves the request and a background worker picks it up when it can. Celery uses the same split: calling add.delay(4, 4) sends a task message to the broker (RabbitMQ is its default), and a Celery worker runs it.

The upload API sends a job to the queue darkroom.why-mq.resize and answers 202 after 4 ms; later the resize-worker resizes the photo in 2 s

Run it and see: two upload endpoints

You need Node.js 18 or newer and a RabbitMQ broker on 127.0.0.1:5672. If you do not have one yet, the next lesson starts RabbitMQ 4.4 in Docker with one command. Lesson 3 explains each amqplib call line by line.

Set up the project

Create a folder with this package.json, then run npm install:

json
{
  "name": "darkroom-why-message-queues",
  "private": true,
  "type": "module",
  "dependencies": {
    "amqplib": "2.4.2"
  }
}

shared.js holds the queue name and the fake resize. A timer stands in for real image work, so both versions do exactly the same 2 seconds of "work":

js
// Shared settings for the Darkroom upload experiment.
export const AMQP_URL = process.env.AMQP_URL ?? 'amqp://127.0.0.1';
export const QUEUE = 'darkroom.why-mq.resize';

// Pretend to resize a photo: wait about 2 seconds.
export const resizePhoto = () => new Promise((resolve) => setTimeout(resolve, 2000));

The upload API with both endpoints

upload-api.js serves two routes. /upload-sync resizes before it answers. /upload-queue sends a job to the queue and answers at once with 202 Accepted:

js
// Two upload endpoints: one resizes inside the request, one queues a job.
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import amqp from 'amqplib';
import { AMQP_URL, QUEUE, resizePhoto } from './shared.js';

const conn = await amqp.connect(AMQP_URL);
conn.on('error', (err) => console.error('connection error:', err.message));
const ch = await conn.createChannel();
ch.on('error', (err) => console.error('channel error:', err.message));
await ch.assertQueue(QUEUE);

const server = http.createServer(async (req, res) => {
  const photoId = randomUUID().slice(0, 8);

  if (req.method === 'POST' && req.url === '/upload-sync') {
    await resizePhoto(); // the client waits for this
    res.writeHead(201, { 'content-type': 'application/json' });
    return res.end(JSON.stringify({ photoId, thumbnail: 'ready' }));
  }

  if (req.method === 'POST' && req.url === '/upload-queue') {
    const job = { photoId, sizes: [256, 1024], queuedAt: Date.now() };
    ch.sendToQueue(QUEUE, Buffer.from(JSON.stringify(job)));
    res.writeHead(202, { 'content-type': 'application/json' });
    return res.end(JSON.stringify({ photoId, thumbnail: 'pending' }));
  }

  res.writeHead(404).end();
});

server.listen(3000, () => console.log('upload-api listening on :3000'));

The resize worker

resize-worker.js is the consumer. It takes one job at a time, resizes, acknowledges the message, and prints how long the thumbnail took from the moment of upload:

js
// Takes resize jobs from the queue, one at a time.
import amqp from 'amqplib';
import { AMQP_URL, QUEUE, resizePhoto } from './shared.js';

const conn = await amqp.connect(AMQP_URL);
conn.on('error', (err) => console.error('connection error:', err.message));
const ch = await conn.createChannel();
ch.on('error', (err) => console.error('channel error:', err.message));
await ch.assertQueue(QUEUE);
await ch.prefetch(1); // one unacknowledged job at a time

await ch.consume(QUEUE, async (msg) => {
  if (msg === null) return; // consumer cancelled by the broker
  const job = JSON.parse(msg.content.toString());
  await resizePhoto();
  ch.ack(msg);
  const waited = ((Date.now() - job.queuedAt) / 1000).toFixed(1);
  console.log(`thumbnail ${job.photoId} ready ${waited} s after upload`);
});
console.log(`resize-worker waiting on ${QUEUE}`);

Measure both endpoints

bench.js fires N uploads at the same time and prints the fastest, median and slowest response:

js
// Sends N uploads at the same time to one endpoint and prints response times.
const path = process.argv[2] ?? '/upload-sync';
const n = Number(process.argv[3] ?? 10);

const timeOne = async () => {
  const start = performance.now();
  const res = await fetch(`http://localhost:3000${path}`, { method: 'POST' });
  await res.json();
  return performance.now() - start;
};

await fetch('http://localhost:3000/'); // warm-up, not measured

const times = (await Promise.all(Array.from({ length: n }, timeOne))).sort((a, b) => a - b);
const ms = (t) => `${Math.round(t)} ms`;
console.log(`${path}  requests=${n}  fastest=${ms(times[0])}  median=${ms(times[Math.floor(n / 2)])}  slowest=${ms(times[n - 1])}`);

Start node upload-api.js in one terminal and node resize-worker.js in a second. In a third terminal, run the bench. Send the single queued upload first and wait for the worker's first thumbnail line before you send the batch of 10; otherwise the batch queues behind that job and the times shift by 2 s. This is our real output (Node 24.18, amqplib 2.4.2, RabbitMQ 4.4.1, one laptop):

text
$ node bench.js /upload-sync 1
/upload-sync  requests=1  fastest=2008 ms  median=2008 ms  slowest=2008 ms
$ node bench.js /upload-sync 10
/upload-sync  requests=10  fastest=2012 ms  median=2013 ms  slowest=2013 ms
$ node bench.js /upload-queue 1
/upload-queue  requests=1  fastest=4 ms  median=4 ms  slowest=4 ms
$ node bench.js /upload-queue 10
/upload-queue  requests=10  fastest=6 ms  median=7 ms  slowest=7 ms

The queued upload answered in 4-7 ms instead of about 2 seconds. Now look at the worker terminal:

text
resize-worker waiting on darkroom.why-mq.resize
thumbnail 104073b2 ready 2.0 s after upload
thumbnail 22183a84 ready 2.0 s after upload
thumbnail 99ea01d8 ready 4.0 s after upload
thumbnail acc24d1b ready 6.0 s after upload
thumbnail 5e2338a4 ready 8.0 s after upload
thumbnail ef9c2e5d ready 10.0 s after upload
thumbnail edfda16f ready 12.1 s after upload
thumbnail a835945a ready 14.1 s after upload
thumbnail cacb2cc7 ready 16.1 s after upload
thumbnail 33b7269b ready 18.1 s after upload
thumbnail 31bbea16 ready 20.1 s after upload

The first line is the single queued upload. The other ten are the batch. Every upload got its answer in 7 ms or less, but the last thumbnail of the batch was ready 20.1 seconds after upload. Each resize took as long as before; the waiting moved from the upload to the thumbnail.

Ten answered uploads wait as ten jobs in the queue; one worker at 2 s per job finishes the first after 2.0 s and the last after 20.1 s

Stop the worker and upload anyway

Stop the worker with Ctrl+C, keep the API running, and send three uploads. Then ask the broker how many messages wait in the queue:

text
$ node bench.js /upload-queue 3
/upload-queue  requests=3  fastest=9 ms  median=9 ms  slowest=9 ms
$ docker exec rabbitmq rabbitmqctl list_queues name messages consumers | grep darkroom.why-mq
darkroom.why-mq.resize	3	0

Three jobs wait and no consumer is attached. Start the worker again and it drains them:

text
resize-worker waiting on darkroom.why-mq.resize
thumbnail e54f07e0 ready 2.8 s after upload
thumbnail d70eed2f ready 4.8 s after upload
thumbnail b6305576 ready 6.8 s after upload

Every upload succeeded while the resize side was down, and all three jobs were processed. When you are done, stop both processes and delete the queue with this cleanup.js:

js
// Deletes the queue this lesson created.
import amqp from 'amqplib';
import { AMQP_URL, QUEUE } from './shared.js';

const conn = await amqp.connect(AMQP_URL);
const ch = await conn.createChannel();
console.log(await ch.deleteQueue(QUEUE));
await conn.close();
text
$ node cleanup.js
{ messageCount: 0 }

What the queue changed

The queued version changed two things.

First, the API's job got smaller. It only hands a message to RabbitMQ, which took a few milliseconds here, and answers 202 Accepted.

Second, the queue became a buffer. When producers outpace consumers, messages pile up in the queue, not as open HTTP requests. When no consumer runs at all, the queue still accepts work. Workers catch up at their own pace, and you can add more of them: the work queues tutorial notes that RabbitMQ sends each message to the next consumer in sequence, so more workers share the backlog. A later lesson measures that.

The price you pay

Weigh these costs before you add a queue.

The result arrives later. With one worker and ten jobs, the last user waited 20.1 seconds for a thumbnail, ten times longer than with the synchronous version. Your UI needs a "processing" state, and the client needs a way to learn the work is done: polling, a webhook or a push channel.

Messages can arrive twice. The reliability guide says acknowledgements give at least once delivery. If a worker crashes after resizing but before its ack reaches the broker, RabbitMQ delivers the message again, and the guide recommends that consumers be idempotent. Resizing twice is harmless. Posting the same photo twice to a shared album would not be. A later lesson covers idempotent consumers.

Things can still be lost. Our sendToQueue call does not wait for any reply from the broker. The reliability guide warns that without acknowledgements and confirms, message loss is possible during publish and consume. Later lessons in chapter 2 close those gaps.

You run one more system. The broker needs upgrades, monitoring and a plan for when it is down. The reliability guide calls data safety "a joint responsibility of RabbitMQ nodes, publishers and consumers". Debugging also gets harder, because one user action now spans two processes and a broker.

Resize in the requestQueue the job
Upload response (10 at once, our run)2012-2013 ms6-7 ms
When the thumbnail is readywith the response2.0 to 20.1 s later, one worker
Resize side downuploads failuploads succeed, jobs wait
Traffic spikehits the resize code directlywaits in the queue
Duplicatesrare (client retries)possible, consumer must cope
Moving partsAPIAPI, broker, worker
Error reportingin the HTTP responseneeds its own channel

When not to use a queue

Call the other code directly when any of these is true:

  • The caller needs the result to continue. A login check, a permission check, a search query. A queue only adds delay here.
  • The work is fast and reliable. Saving a short row takes milliseconds. A worker would add a hop and save nothing.
  • You cannot handle "done later" or "done twice". Build a pending state and, if the action is unsafe to repeat, an idempotency plan first.
  • Your team cannot run a broker yet. A queue nobody monitors fails quietly. A simple synchronous call is often the better first version.

Good candidates look like Darkroom's resize: slow or heavy work, a result the user does not need this second, traffic that comes in bursts, or a step that calls an unreliable outside service.

Does a message queue make the work faster?

No. Each resize still took 2 seconds. A queue makes the response faster by moving work off the request path, and lets you add workers for a backlog. The time to the result can even grow, as the 20.1-second thumbnail showed.

Why does the queued endpoint return 202 instead of 201?

Because the thumbnail does not exist yet when the API answers. 201 Created claims the resource is done. RFC 9110 says 202 means "the request has been accepted for processing, but the processing has not been completed", which is exactly what happened. It also notes that HTTP has no way to re-send a status code later, so the client needs another way to learn when the job is done.

Summary

  • A producer hands off work and moves on; a consumer does it later. Our upload response fell from about 2 s to 4-7 ms.
  • The work is not faster: with one worker, ten jobs took 20.1 s. The queue absorbs bursts and accepts work while consumers are down.
  • You pay with delayed results, possible duplicates, possible loss until you add acks and confirms, and one more system to run.
  • Queue slow, bursty or failure-prone work whose result can wait. Call directly when the caller needs the answer now.

Next: run RabbitMQ in Docker and tour the management UI.

Sources

Looked up on 2026-11-29. RabbitMQ 4.4 (image rabbitmq:4.4.1-management), amqplib 2.4.2, Node.js 24.18.