Skip to content
Fullstack Launchpad

Your First Producer and Consumer in Node.js

Send a resize job to RabbitMQ with amqplib, read it in a worker, see connections and channels, and watch a message vanish when the process exits abruptly.

Lesson 3By Published 9 min readRabbitMQ: The Complete Guide
Two tin cans joined by a taut string, the classic toy telephone

In the previous lesson you started RabbitMQ in Docker and pushed a message through the UI by hand. Now you write two programs that do it. upload-api.js hands a resize job to RabbitMQ. resize-worker.js picks it up. You will also see what connections and channels are, and lose a message on purpose to learn why closing properly matters.

The problem: the job has to leave the API

Darkroom is our photo service. A user uploads a photo, and the API should answer at once. Making the 320 px and 1080 px versions is slow, so the API does not do it. It writes a small job, {photoId, sizes}, and gives it to RabbitMQ. A worker process does the resizing later.

That needs two pieces of code:

  • a producer (the API) that publishes the job to a queue named darkroom.resize;
  • a consumer (the worker) that subscribes to that queue and handles each job.

The two never talk directly; each talks only to the broker.

The big picture: connection, channel, queue

Each program opens one connection to RabbitMQ. That is a long-lived TCP connection that has logged in to a virtual host. Inside it, the program opens a channel. The RabbitMQ docs describe channels as "lightweight connections that share a single TCP connection". Almost everything you do (declare a queue, publish, consume) happens on a channel.

The upload-api process and the resize-worker process each open one TCP connection to RabbitMQ with one channel inside, and the job goes through the darkroom.resize queue

Set up the project

You need Node.js 18 or later (amqplib 2.x requires it) and the broker from the previous lesson on localhost:5672. Create a folder and install the client:

sh
mkdir darkroom && cd darkroom
npm init -y
npm pkg set type=module
npm install --save-exact amqplib@2.4.2

type=module lets you use import and top-level await. --save-exact pins the version this lesson uses.

Write the producer: upload-api.js

js
// upload-api.js: the Darkroom API hands one resize job to RabbitMQ.
// Usage: node upload-api.js [photoId] [--crash]
import amqp from 'amqplib';

const QUEUE = 'darkroom.resize';
const args = process.argv.slice(2);
const photoId = args.find((a) => !a.startsWith('--')) ?? 'p-1001';
const crash = args.includes('--crash');

const connection = await amqp.connect('amqp://127.0.0.1', {
  clientProperties: { connection_name: 'upload-api' },
});
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 job = { photoId, sizes: [320, 1080] };
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(job)), {
  contentType: 'application/json',
});
console.log('sent', job);

if (crash) {
  process.exit(1); // die right after the send, like a crash or a hasty exit
}

await channel.close();
await connection.close();
console.log('closed cleanly');

What each step does:

  • amqp.connect('amqp://127.0.0.1', ...) opens the connection. Missing parts of the URL default to amqp://guest:guest@localhost:5672 and the virtual host / (amqplib API reference). connection_name is a client-provided name that the broker shows in the UI and in its logs.
  • Keep the error listeners. The amqplib README says an error event with no listener becomes an uncaught exception and ends the process.
  • assertQueue creates the queue if it does not exist. Declaring a queue is idempotent, so both programs can call it, and whichever starts first creates it. The options match the official JavaScript tutorial: a quorum queue, a durable, replicated queue type. A later lesson explains it; for now, both programs must declare the queue with the same options.
  • sendToQueue sends the bytes straight to the named queue, "bypassing routing" in the words of the API docs. On the broker the default exchange still does the routing: sendToQueue is a shortcut for publishing to it with the queue name as the routing key. The next lesson shows what that means.
  • sendToQueue returns true or false, not a promise. false only means the client's write buffer is full. Neither value tells you the broker has the message.

Write the consumer: resize-worker.js

js
// resize-worker.js: takes resize jobs from RabbitMQ and prints them.
import amqp from 'amqplib';

const QUEUE = 'darkroom.resize';

const connection = await amqp.connect('amqp://127.0.0.1', {
  clientProperties: { connection_name: 'resize-worker' },
});
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' },
});

await channel.consume(QUEUE, (msg) => {
  if (msg === null) {
    console.log('the broker cancelled this consumer');
    return;
  }
  const job = JSON.parse(msg.content.toString());
  console.log(`resize ${job.photoId} to ${job.sizes.join(' and ')} px`);
  channel.ack(msg); // tell RabbitMQ this job is done
});
console.log(`waiting for jobs on ${QUEUE}, Ctrl+C to stop`);

process.once('SIGINT', async () => {
  await channel.close();
  await connection.close();
  console.log('worker closed cleanly');
});

consume registers a callback, and RabbitMQ pushes each message to it. If the broker cancels the consumer, amqplib calls the callback with null, so the code checks for that first.

channel.ack(msg) is the one acknowledgement detail you need today. By default amqplib consumes with noAck: false, which means RabbitMQ expects an acknowledgement for each message it delivers. The worker sends it after the work is done. Acknowledgements get their own lesson in chapter 2.

Run it and see

Open two terminals in the project folder. Start the worker first, then send one job:

sh
node resize-worker.js   # terminal 1
node upload-api.js p-1001   # terminal 2

Terminal 2 prints:

text
sent { photoId: 'p-1001', sizes: [ 320, 1080 ] }
closed cleanly

Terminal 1 prints:

text
waiting for jobs on darkroom.resize, Ctrl+C to stop
resize p-1001 to 320 and 1080 px

The producer has already exited and the worker is still running. Wait 5 to 10 seconds, then ask the management HTTP API what is connected. The server emits statistics every 5 seconds by default, and until the next emission channels can read 0:

sh
curl -s -u guest:guest http://localhost:15672/api/connections | jq -c '.[] | {name: .client_properties.connection_name, client: .client_properties.product, channels, state} | select(.client == "amqplib")'
json
{"name":"resize-worker","client":"amqplib","channels":1,"state":"running"}

The worker has one connection with one channel, under the name you set in code. The producer's connection is gone because it closed. The UI shows the same on the Connections and Channels tabs.

Press Ctrl+C in terminal 1:

text
worker closed cleanly

Connection vs channel

ConnectionChannel
What it isA TCP connection that has authenticated to a virtual hostA lightweight connection inside one TCP connection
amqplib callamqp.connect(url)connection.createChannel()
LifetimeLong-lived; not one per operationLong-lived; opening one is a network round trip
How manyOne per process in this lessonA single-digit number per connection for most apps
On errors such as 404 NOT_FOUND or 406 PRECONDITION_FAILEDStays openThat channel is closed
When it closesEvery channel on it closes tooThe channel becomes unusable; the connection stays
Where you see itUI Connections tab, GET /api/connectionsUI Channels tab, GET /api/channels

Open the connection and channel once when the process starts, reuse them, and close them when the process stops, in the order below.

Lifecycle of a client from top to bottom: connect, create channel, assert queue, publish or consume many times, close channel, close connection

What happens to a message sent just before a crash?

Stop the worker, then send one job with --crash, where the producer calls process.exit(1) right after sendToQueue. Then send one job the normal way:

sh
node upload-api.js p-1002 --crash
node upload-api.js p-1003
text
sent { photoId: 'p-1002', sizes: [ 320, 1080 ] }
sent { photoId: 'p-1003', sizes: [ 320, 1080 ] }
closed cleanly

After a few seconds, count the messages:

sh
curl -s -u guest:guest http://localhost:15672/api/queues/%2F/darkroom.resize | jq '{messages}'
json
{
  "messages": 1
}

Both runs printed sent, but the queue holds one message. The broker log shows how each connection ended. rabbitmq is the container name from the previous lesson, and --since 2m keeps only the last two minutes:

sh
docker logs --since 2m rabbitmq 2>&1 | grep -E 'closing AMQP|unexpectedly'
text
2026-11-29 16:24:49.507563+00:00 [info] <0.3082.0> closing AMQP connection (172.17.0.1:59414 -> 172.17.0.2:5672 - upload-api, vhost: '/', user: 'guest', duration: '127ms')
2026-11-29 16:25:00.547502+00:00 [info] <0.3061.0> closing AMQP connection (172.17.0.1:59412 -> 172.17.0.2:5672 - resize-worker, vhost: '/', user: 'guest', duration: '12s')
2026-11-29 16:25:00.675690+00:00 [warning] <0.3125.0> closing AMQP connection <0.3125.0> (172.17.0.1:57622 -> 172.17.0.2:5672 - upload-api, vhost: '/', user: 'guest', duration: '64ms'):
2026-11-29 16:25:00.675690+00:00 [warning] <0.3125.0> client unexpectedly closed TCP connection
2026-11-29 16:25:00.881892+00:00 [info] <0.3139.0> closing AMQP connection (172.17.0.1:57636 -> 172.17.0.2:5672 - upload-api, vhost: '/', user: 'guest', duration: '117ms')

The first two lines are from the first run (the p-1001 producer and the worker you stopped with Ctrl+C), if you did it within the last two minutes. The crashed producer is a warning: its TCP connection just disappeared. The last line is the clean producer, a normal info close. Start the worker again and only one job arrives:

text
resize p-1003 to 320 and 1080 px
waiting for jobs on darkroom.resize, Ctrl+C to stop
worker closed cleanly

Job p-1002 is gone, and nothing reported an error. (The job line comes first because the job was already waiting in the queue.)

Why the job vanished

sendToQueue does not write to the network. amqplib encodes the message and puts it in a buffer for that channel (lib/connection.js). A separate step moves buffered frames to the socket on a later turn of the event loop, scheduled with setImmediate (lib/mux.js). process.exit(1) ends the process right away, before that turn comes, so the bytes never leave your machine.

Two paths from top to bottom: with close, the buffered job reaches the socket and the queue; with process.exit, the process ends while the job is still in the client buffer

channel.close() fixes this: its promise resolves only when the closing handshake with the broker is complete. The close request goes out on the same channel after the job, and await keeps the process alive until the broker replies.

Close properly: the fix and its limits

Way the producer endsJob p-… in the queue?What the broker logs
await channel.close(); await connection.close();Yes (p-1003)[info] closing AMQP connection
process.exit(1) right after sendToQueueNo (p-1002)[warning] client unexpectedly closed TCP connection

So, in every producer:

  • Keep one connection and one channel for the life of the process. The docs say connection churn consistently above 100 per second likely means connections are managed badly.
  • On shutdown, await channel.close() and then await connection.close() before you exit.
  • Do not replace that with a timer before process.exit. A delay only guesses how long the buffer needs.

A clean close still does not prove the broker stored the job. The publishers guide says messages "previously serialised and written to the socket are not guaranteed to reach the target node" when a connection fails. Without confirmation, a publisher cannot assume the message reached the server. For that proof you need publisher confirms, which a later lesson covers. A clean close prevents the loss in this experiment; confirms tell you about failures outside your process, such as a broken connection.

What does noAck: true change in the consumer?

The official tutorial consumes with noAck: true. In amqplib that tells the broker not to expect acknowledgements, and the API reference says the broker will then "dequeue messages as soon as they've been sent down the wire". The RabbitMQ docs call this automatic acknowledgement mode "fire-and-forget". If the consumer's connection or channel closes before the delivery succeeds, the message is lost, and the docs say this mode "should be considered unsafe". It also has no prefetch limit, so a slow consumer can be overwhelmed. So the worker keeps the default and calls channel.ack(msg).

Should I open a new connection for every message?

No. A connection is meant to be long-lived. Each new one means a new TCP connection and a new login, and the broker logs every open and close. Open it once and publish many messages over the same channel. If several parts of your app publish or consume at the same time, give each one its own channel on that connection; the docs note that a channel per thread or process is common.

Summary

  • A producer publishes to a queue, a consumer subscribes to it, and neither talks to the other.
  • A connection is one long-lived TCP connection. A channel is a lightweight connection inside it, where queue declarations, publishing and consuming happen.
  • connection_name makes your processes easy to find in the UI, API and logs.
  • sendToQueue only buffers the message. An abrupt exit right after it can lose the message without any error.
  • Close the channel and then the connection with await before exiting. For proof that the broker has the message, use publisher confirms.
  • Keep the default noAck: false and acknowledge after the work. Automatic acknowledgement is unsafe according to the docs.

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.