Send and receive a message

Learn about producers, queues, and consumers by sending a message between two programs.

🎯 Introduction

Learn about producers, queues, and consumers by sending a message between two programs.


🧱 The three roles

A program that sends messages is a producer. A program that receives and processes them is a consumer. A queue holds messages awaiting processing. The queue lives on the RabbitMQ server, rather than in the sender's memory.

We will start with a text message indicating a successful payment and observe the full flow, before introducing multiple business systems.

courseComponents.mermaid.loading

This diagram is simplified. The client's sendToQueue() actually routes through RabbitMQ's built-in default exchange to the queue with the same name. An exchange is the entry point for routing messages; we will configure one in the next stage.


📤 Write the sender

Reuse the configuration from environment setup. After connecting, call createChannel() to create a channel, a logical session on the connection for messaging operations. Channels let us declare queues and send or receive messages.

send.mjs
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';

const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();

await channel.assertQueue('payment', { durable: false });
channel.sendToQueue('payment', Buffer.from('payment succeeded'));
console.log('Message submitted');
await channel.close();
await connection.close();

payment is the payment notification queue. Applications agree on its name; RabbitMQ does not infer routing from names. assertQueue() ensures the queue exists and can be called repeatedly with the same name and configuration. durable: false means this example does not require the queue to survive a server restart.

sendToQueue() takes a queue name and a body. The body must contain bytes, so Buffer.from() converts the text. Close the channel and connection after sending so the program exits normally. Printing “Message submitted” does not mean the receiver has processed it successfully.


📥 Write the receiver

receive.mjs
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';

const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();

await channel.assertQueue('payment', { durable: false });
await channel.consume('payment', (message) => {
    if (message === null) return;
    console.log('Received:', message.content.toString());
}, { noAck: true });
console.log('Waiting for messages; press Ctrl+C to stop');

consume() subscribes to the queue and invokes the callback when a message arrives. message.content contains the received bytes, and toString() converts them back to text. A null value means the server cancelled the subscription; it is not a regular message.

noAck: true means RabbitMQ does not wait for an explicit consumer acknowledgement. This basic example only prints text. If the program crashes after receiving a message, RabbitMQ will not redeliver it for that reason. The reliability chapter will change this to acknowledge after processing.


🧪 Observe the result in two terminals

Send from terminal one first:

node send.mjs

Then start the receiver in terminal two:

node receive.mjs

You should see Received: payment succeeded. The sender has already exited, yet the message can still be received, showing that the server queue stored it. Run the sender again to see another line in the receiving terminal. The receiver keeps waiting; press Ctrl+C to stop it.


❓ Questions and answers

Q1: Does declaring the same queue clear it each time?

No. Matching configurations reuse the existing queue. A different configuration may cause an error. Do not rely on implicit behavior to overwrite an existing configuration; use a different name when needed.

Q2: Do two receivers subscribed to one queue each get a copy?

No. They share the messages. Separate systems need separate queues to each receive a copy, as the next stage demonstrates.

Q3: Can I send before the queue exists?

This example declares the queue first. Without it, there is nowhere for that message to go. Creating the queue later does not recover earlier messages.


🧪 Exercise

Stop the receiver, send twice, and restart it. Expect two new output lines. Stop it afterward to avoid confusion in later examples.


🎉 You have sent a message all the way from producer to consumer!