Exchanges and publish/subscribe

Understand exchanges, bindings, and queues, and deliver the same payment message to three systems.

🎯 Introduction

Understand exchanges, bindings, and queues, and deliver the same payment message to three systems.


🧱 Why use multiple queues?

The order, notification, and accounting systems all need the payment result. If they share a queue, each delivery goes to only one consumer, leaving the other two without a copy.

Give each system its own queue and use an exchange to route messages. An exchange receives messages from producers and applies rules to decide which queues receive them. It does not replace queues as storage for messages awaiting processing.

A binding defines a routing relationship between an exchange and a queue. fanout is an exchange type that sends a copy to every bound queue. The sender publishes, and receivers subscribe through their own queues: this is publish/subscribe.

courseComponents.mermaid.loading


🛠 Create the exchange and bindings

setup-fanout.mjs
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';

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

await channel.assertExchange('payment', 'fanout', { durable: false });
for (const queue of ['order', 'notice', 'accounting']) {
    await channel.assertQueue(queue, { durable: false });
    await channel.bindQueue(queue, 'payment', '');
}
console.log('Three queues bound');
await channel.close();
await connection.close();

assertExchange() takes a name, type, and options. bindQueue() takes a queue, exchange, and binding key. The binding key is part of the receiving rule, but fanout does not filter by it, so use an empty string here.

Run the setup script:

node setup-fanout.mjs

Wait for “Three queues bound” before sending. The queues and bindings must exist to receive messages published afterward.


📤 Publish once from the payment system

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

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

const event = { paymentId: 'P1001', orderId: 'O1001', amountFen: 9900 };
channel.publish('payment', '', Buffer.from(JSON.stringify(event)));
console.log('Payment success message published');
await channel.close();
await connection.close();

publish() takes the exchange name, routing key, and body. The routing key is a label the producer provides for routing. Fanout does not filter by it, so it is also empty here. Unlike the earlier sendToQueue() example, this explicitly sends to the exchange we created.


📥 Receive independently in three systems

Each file is a separate program subscribed only to its own queue. The logs represent the work each system would perform; they do not actually update orders or send text messages.

Order consumer:

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

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

await channel.consume('order', (message) => {
    if (message === null) return;
    const event = JSON.parse(message.content.toString());
    console.log('[order]', event.paymentId, 'Update order status');
}, { noAck: true });
console.log('[order] Waiting for payment messages');

Notification consumer:

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

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

await channel.consume('notice', (message) => {
    if (message === null) return;
    const event = JSON.parse(message.content.toString());
    console.log('[notice]', event.paymentId, 'Send payment notification');
}, { noAck: true });
console.log('[notice] Waiting for payment messages');

Accounting consumer:

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

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

await channel.consume('accounting', (message) => {
    if (message === null) return;
    const event = JSON.parse(message.content.toString());
    console.log('[accounting]', event.paymentId, 'Record payment transaction');
}, { noAck: true });
console.log('[accounting] Waiting for payment messages');

Start them in three terminals:

node order.mjs
node notice.mjs
node accounting.mjs

Send from a fourth terminal:

node publish.mjs

Each receiving terminal prints P1001 once, indicating an order status update, a notification, or an accounting entry. The payment program published once, and each independent queue received a copy.


⏸ Receivers can pause independently

Stop the notification program and publish again. The order and accounting programs continue printing, while the notification queue retains its copy. Restart the notification program to receive messages from the pause.

To add another system, create a new queue and binding; the producer does not need the new system's address. The new queue will not receive messages published before it existed. See the official publish/subscribe tutorial for exchange routing.


❓ Questions and answers

Q1: Does the exchange store messages?

Queues store messages awaiting consumption. An exchange without a matching queue cannot automatically retain messages for future consumers.

Q2: Will two notification instances each receive a copy?

If they share the notification queue, they share its messages. Giving each system a copy and distributing work among instances of one system are different relationships.

Q3: Does stopping the notification system affect the order queue?

Not in this example. Each queue stores an independent copy, so the notification queue's progress does not determine the order queue's progress.


🧪 Exercise

Stop only the accounting program, publish twice, then restart it. Verify that order and notification output appears promptly and accounting prints two additional lines after restarting.


🎉 You can now give multiple systems a copy each through independent queues!