Exact routing with direct exchanges
🎯 Introduction
The payment system emits two events: payment succeeded and refund completed. The order program needs only the first, and the refund program only the second. The previous fanout exchange forwards to every bound queue and cannot filter this way. Here, a direct exchange sends messages only to queues with matching receiving conditions.
🧱 The two values an exchange compares
Filtering requires telling the exchange two things: which messages a queue wants and which message is being sent.
Queues specify receiving conditions with binding keys
A binding connects a queue to an exchange. The condition supplied when creating it is the binding key. For example:
await channel.bindQueue('direct.order', 'payment.direct', 'success');
The arguments are the queue name, exchange name, and binding key. This binds direct.order to payment.direct with the receiving condition success. It only configures a rule; no message has been sent.
Messages carry routing keys
A routing key is the routing label the sender supplies when publishing a message. For example:
channel.publish('payment.direct', 'success', body);
The arguments are the exchange name, routing key, and message body. Here, body represents the bytes of the body; the complete example creates it below. This publishes to payment.direct with the routing key success.
Direct exchanges require an exact match
The two occurrences of success have the same value but different roles: one is a receiving condition on a binding; the other is a routing label on a message.
| Value being compared | Where it is supplied | Value here |
|---|---|---|
| Queue binding key | Third argument to bindQueue() | success |
| Message routing key | Second argument to publish() | success |
When the direct exchange receives the message, it checks its bindings. The message routing key and the order queue's binding key are both success. They match exactly, so the message enters the order queue.
These are the two values it compares—not the queue name or the body. success and refund are event labels chosen for this example, not business states built into RabbitMQ.
🧭 Trace routing through two bindings
This example creates these relationships:
| Queue | Binding key on payment.direct |
|---|---|
direct.order | success |
direct.refund | refund |
Now publish two messages:
| Message routing key | Compared with order binding key success | Compared with refund binding key refund | Destination queue |
|---|---|---|---|
success | Matches | Does not match | direct.order |
refund | Does not match | Matches | direct.refund |
A direct exchange sends to every matching queue. Add a success binding for the refund queue and both queues receive payment success messages. Exact matching does not limit a message to one queue. A queue can also receive multiple event types through multiple bindings.
First, we will run the two basic bindings shown above. The exercise then verifies matching multiple queues.
🛠 Create resources and publish messages
Reuse the directory, amqplib, and config.mjs from installation and connection. Save the following files and run commands there. The example only prints messages; it does not update orders or issue refunds.
Create the exchange and queues
The exchange is named payment.direct and has type direct: distinguish its name from its type. The queues use the dedicated names direct.order and direct.refund to avoid mixing chapters. The dots and the word direct in these names are naming conventions and do not participate in matching.
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.assertExchange('payment.direct', 'direct', { durable: false });
await channel.assertQueue('direct.order', { durable: false });
await channel.assertQueue('direct.refund', { durable: false });
await channel.bindQueue('direct.order', 'payment.direct', 'success');
await channel.bindQueue('direct.refund', 'payment.direct', 'refund');
console.log('Direct routing rules created');
await channel.close();
await connection.close();
assertExchange() declares an exchange, taking its name first and type second. assertQueue() declares a queue. These methods create missing resources or check existing configurations; they cannot change an existing fanout exchange into a direct exchange with the same name.
durable: false keeps the non-durable setting from the basic examples. This article does not test survival across a server restart. Run setup first:
node setup-direct.mjs
After “Direct routing rules created”, both queues and their bindings are ready. Bindings affect later publications; they do not recover earlier messages.
Publish two event types
Create this sender. Both messages use the same body and differ only in routing key, making the routing decision easier to observe:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
const body = Buffer.from(JSON.stringify({ paymentId: 'P1001' }));
channel.publish('payment.direct', 'success', body);
channel.publish('payment.direct', 'refund', body);
console.log('Published success and refund');
await channel.close();
await connection.close();
JSON.stringify() converts the payment ID object to text, and Buffer.from() converts that text to bytes. Neither success nor refund is in the body; each is the second argument to its publish() call.
node publish-route.mjs
No consumers are running yet, so the messages wait in their matching queues. Consumers can start later, provided the queues and bindings existed before publishing.
📥 Read each queue and check the results
Order consumer
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.consume('direct.order', (message) => {
if (message === null) return;
const event = JSON.parse(message.content.toString());
console.log('direct.order', message.fields.routingKey, JSON.stringify(event));
}, { noAck: true });
console.log('direct.order Waiting for messages');
Refund consumer
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.consume('direct.refund', (message) => {
if (message === null) return;
const event = JSON.parse(message.content.toString());
console.log('direct.refund', message.fields.routingKey, JSON.stringify(event));
}, { noAck: true });
console.log('direct.refund Waiting for messages');
The first argument to consume() selects the queue. The callback runs when a message arrives. message.fields.routingKey is the routing key supplied at publication, and message.content is the body. Neither consumer needs to filter events again: the exchange already matched them before enqueueing.
noAck: true means the server does not wait for a report that processing is complete. It simplifies this demonstration; the consumer acknowledgement article later shows how to acknowledge after business processing succeeds.
Open two terminals and run one command in each:
node order-success.mjs
node refund.mjs
Apart from the startup message, the order terminal should receive:
direct.order success {"paymentId":"P1001"}
The refund terminal should receive:
direct.refund refund {"paymentId":"P1001"}
Looking back at the bindings, the order queue's success matched the first message, and the refund queue's refund matched the second. Keep both consumers running and run node publish-route.mjs again in a third terminal. Each receiving terminal should print one more corresponding line.
If you have run this example before, queues may hold older messages and the exercise may have changed bindings. Finish processing older messages, stop extra consumers of the same queues, and restore the basic bindings below before checking the new output.
❓ Questions and answers
Q1: Is success a binding key or a routing key?
It depends on where it is supplied. In the third argument to bindQueue(), it is a binding key value. In the second argument to publish(), it is a routing key value. A direct exchange compares those two values.
Q2: Where does a message go if its body says refund but its routing key is success?
With the basic bindings, it enters the order queue. Direct exchanges do not parse the body to choose a destination, so the sender must supply the correct routing key.
Q3: What happens with the routing key Success?
It differs from success, so it does not match that binding. With no other matching binding and no message return mechanism configured here, the message is discarded rather than saved for future bindings.
🧪 Exercise
Let the refund queue receive both success and refund events. Before closing the channel in setup-direct.mjs, add a bindQueue() call with queue direct.refund, exchange payment.direct, and the additional binding key success.
Run setup again, then run the publisher. Expect one new success in the order terminal and one success plus one refund in the refund terminal. Explain why the same success message enters two queues.
Restore the basic bindings afterward
First remove the added binding statement from setup so it is not added again next time. Removing code does not remove an existing binding, and rerunning the original setup does not automatically clean up extra bindings.
Create a reset script using unbindQueue() to remove the specified binding. Its arguments correspond to those used to create it: queue, exchange, and binding key.
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.unbindQueue('direct.refund', 'payment.direct', 'success');
console.log('Removed success binding from refund queue');
await channel.close();
await connection.close();
node reset-direct-binding.mjs
node publish-route.mjs
Keep both consumers running, wait for the exercise messages to finish, then run these commands. Expect only a new success for orders and a new refund for refunds. Removing a binding affects future publications and does not delete messages already queued.
🎉 You can now compare message routing keys with queue binding keys to predict direct exchange routing!
