Wildcard routing with topic exchanges
🎯 Introduction
The previous article used a direct exchange to match events exactly. As payment events multiply, an accounting system that wants every payment event would need a binding for each. Topic exchanges allow wildcards in bindings, so one rule can receive a group of routing keys. Through payment message experiments, we will see where rules belong, how * and # match, and which queues receive each message.
🧱 Specific routing keys on messages, receiving patterns on bindings
Recall the two concepts: a routing key is the label a sender attaches to a message for routing; a binding key is the receiving condition supplied when binding a queue to an exchange. Topic exchanges change how they are compared: binding keys can use wildcards to describe a set of matching routing keys.
For example, an accounting queue that wants all payment events uses this binding:
await channel.bindQueue('topic.accounting', 'payment.topic', 'payment.#');
The arguments are queue name, exchange name, and binding key. payment.# is the receiving condition on the binding. This step sends no message.
The sender publishes a specific payment success message:
channel.publish('payment.topic', 'payment.success', body);
The arguments are exchange name, routing key, and body. body represents the message bytes and is created in the complete example below.
| Value being compared | Where it is supplied | Value here |
|---|---|---|
| Queue binding pattern | Third argument to bindQueue() | payment.# |
| Specific message label | Second argument to publish() | payment.success |
The exchange asks: does the message's payment.success match the binding's payment.#? It forwards to that queue only if it does. Wildcards belong in binding patterns. Publish these events with specific routing keys rather than using payment.# to represent all payment events.
🔎 How asterisks and hashes match dot-separated segments
Topic exchanges use dots (.) to separate routing key segments. Each segment is a string, with no requirement to use built-in business names:
| Routing key | Segments | Segment count |
|---|---|---|
payment | payment | 1 |
payment.success | payment, success | 2 |
payment.refund.completed | payment, refund, completed | 3 |
Here, payment denotes the payment category by convention. RabbitMQ matches these strings without understanding payments or refunds, and does not parse the body to choose a destination.
An asterisk matches exactly one segment
The binding key payment.* consists of the literal payment and wildcard *. The first segment must be payment, followed by exactly one more segment.
Thus payment.success matches: payment matches the literal, and success matches the asterisk. payment.refund.completed does not: refund and completed are two segments after payment, which one asterisk cannot cover. payment also fails because the asterisk cannot omit its segment.
A hash matches zero or more segments
The binding key payment.# also requires payment first, but the hash allows no following segments, one segment, or multiple segments.
Thus payment, payment.success, and payment.refund.completed all match. Notice that payment does not need a trailing dot when the hash matches zero segments.
Compare the two patterns:
| Message routing key | Binding key payment.* | Binding key payment.# | Reason |
|---|---|---|---|
payment | No match | Matches | Zero segments after payment |
payment.success | Matches | Matches | One following segment |
payment.refund | Matches | Matches | One following segment |
payment.refund.completed | No match | Matches | Two following segments |
invoice.success | No match | No match | The literal first segment differs |
Count dot-separated segments, not characters. Wildcards need not appear at the end: *.success matches payment.success and invoice.success, but not payment.refund.success. See the official RabbitMQ topic tutorial for matching rules.
🛠 Create two patterns and publish test messages
Reuse the directory, amqplib, and config.mjs from installation and connection. Save files and run commands there. This experiment only observes routing; it does not update orders or write accounting entries.
To compare both patterns, the order observation queue uses payment.* and the accounting observation queue uses payment.#. Real services should select events according to business needs; this order program only prints results.
Create the exchange, queues, and bindings
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.assertExchange('payment.topic', 'topic', { durable: false });
await channel.assertQueue('topic.order', { durable: false });
await channel.bindQueue('topic.order', 'payment.topic', 'payment.*');
await channel.assertQueue('topic.accounting', { durable: false });
await channel.bindQueue('topic.accounting', 'payment.topic', 'payment.#');
console.log('Topic routing rules created');
await channel.close();
await connection.close();
The first argument to assertExchange(), payment.topic, is the exchange name; the second, topic, is its type. The topic prefix in queue names is only a naming convention and does not affect matching. The actual conditions are the third arguments to bindQueue().
durable: false keeps the basic examples' non-durable setting; we only observe routing here. Run:
node setup-topic.mjs
Wait for “Topic routing rules created” before sending. Queues and bindings must exist in advance. Later bindings do not recover previously published messages.
Publish five specific routing keys
Use the same body with five keys to cover the table's boundary cases. The single-segment payment intentionally tests the hash matching zero segments; real applications do not have to name events this way.
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
const routingKeys = [
'payment',
'payment.success',
'payment.refund',
'payment.refund.completed',
'invoice.success',
];
const body = Buffer.from(JSON.stringify({ paymentId: 'P1001' }));
for (const routingKey of routingKeys) {
channel.publish('payment.topic', routingKey, body);
console.log('Published', routingKey);
}
await channel.close();
await connection.close();
Each loop iteration takes one specific routingKey from the list as the second argument to publish(). The body is the payment ID object encoded as JSON text and then bytes. Its content does not affect this routing decision.
node publish-topic.mjs
Matching messages now wait in their queues. Start consumers next to read them.
📥 Check routing results in both queues
Order observation program:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.consume('topic.order', (message) => {
if (message === null) return;
console.log(message.fields.routingKey);
}, { noAck: true });
console.log('order Waiting for messages');
Accounting observation program:
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.consume('topic.accounting', (message) => {
if (message === null) return;
console.log(message.fields.routingKey);
}, { noAck: true });
console.log('accounting Waiting for messages');
consume() selects the queue, and the callback prints the message's actual message.fields.routingKey. The exchange already applied the rules while routing, so consumers need not match again. noAck: true simplifies this demonstration; later chapters cover acknowledging after business processing.
Start one program in each of two terminals:
node order-topic.mjs
node accounting-topic.mjs
Apart from the startup message, the order terminal should receive two messages matching payment.*:
payment.success
payment.refund
The accounting terminal should receive four matching payment.#:
payment
payment.success
payment.refund
payment.refund.completed
Five messages were published, but the two queues received six copies in total. The success and refund messages each match both queues, producing two copies each. The single-segment payment and three-segment payment.refund.completed go only to accounting. invoice.success matches neither queue and is discarded because returns are not configured here.
Topic exchanges forward to every matching queue, rather than selecting only the most specific rule. If multiple bindings on one queue match a publication, that queue still receives just one copy. This does not automatically deduplicate repeated publications or later redeliveries.
Keep consumers running and publish again to see two and four new lines respectively. If you have run this experiment before, finish old messages, stop extra consumers on the same queues, and remove extra bindings using the post-exercise steps before checking new output.
❓ Questions and answers
Q1: Does payment.ref match all events starting with ref?*
No. Each wildcard must occupy an entire segment; ref* is not a character prefix pattern. Use payment.* to receive any single segment after payment.
Q2: Must binding keys contain wildcards?
No. A binding of payment.success matches only that exact routing key.
Q3: Does payment.# match invoice.payment.success?
No. This binding requires payment at the start. The hash matches the remaining segments at its own position; it cannot skip the preceding invoice.
🧪 Exercise
Keep the order queue's payment.* binding. Before closing the setup channel, add another binding from payment.topic to topic.order with binding key payment.*.*.
Predict the result, then rerun setup and the publisher. Expect three new order messages: payment.success, payment.refund, and payment.refund.completed, still excluding the single-segment payment. Accounting should still receive four.
The refund and completed segments match the two asterisks in the added rule. The original payment.* binding remains, so the two previously matching messages still arrive.
Restore the basic bindings afterward
Remove the added binding code from setup, then run the reset script below. Removing code or redeclaring the original bindings does not remove extra bindings already on the server.
import amqp from 'amqplib';
import { rabbitmqUrl } from './config.mjs';
const connection = await amqp.connect(rabbitmqUrl);
const channel = await connection.createChannel();
await channel.unbindQueue('topic.order', 'payment.topic', 'payment.*.*');
console.log('Removed payment.*.* binding from order queue');
await channel.close();
await connection.close();
The arguments to unbindQueue() correspond to those used to create the binding: queue name, exchange name, and binding key to remove. After exercise messages finish, keep both consumers running and execute:
node reset-topic-binding.mjs
node publish-topic.mjs
Expect two new order messages again and four for accounting. Unbinding affects future publications without deleting already queued messages.
🎉 You can now compare messages and binding patterns segment by segment to predict topic routing!
Exact routing with direct exchanges
Understand how direct exchanges select queues by comparing binding conditions with message routing keys.
Message processing and consumer acknowledgements
Interrupt a consumer to observe redelivery of unacknowledged messages and understand why business operations still need deduplication.
