Exchange Types: Direct, Topic, Fanout, and Headers
Route messages to the right consumers by choosing the appropriate exchange and binding strategy.
Why Exchanges Exist
In RabbitMQ, producers never publish directly to a queue. They publish to an exchange, and the exchange decides which queue(s) receive the message based on bindings and a routing key.
This indirection is the core of event-driven routing. To get messages to the right consumers you must choose the correct exchange type:
direct— exact routing-key matchtopic— pattern match with wildcardsfanout— broadcast to all bound queuesheaders— match on message header attributes
Picking the wrong one means consumers miss messages or get flooded with irrelevant ones.
The Mental Model: Exchange + Binding + Routing Key
Three pieces work together:
- Routing key: a string the producer attaches to each message (e.g.
order.created). - Binding: a rule connecting an exchange to a queue, often with a binding key.
- Exchange type: the algorithm that compares the routing key against the bindings.
The exchange evaluates every binding. A message can land in zero, one, or many queues. If it matches no binding, it is dropped (unless an alternate exchange is configured).
We'll use the amqplib library throughout these examples.
// Establishing a channel with amqplib
const amqp = require('amqplib');
async function connect() {
const conn = await amqp.connect('amqp://localhost');
const channel = await conn.createChannel();
return { conn, channel };
}
module.exports = { connect };All lessons in this course
- Producers, Consumers, and the AMQP Model
- Exchange Types: Direct, Topic, Fanout, and Headers
- Acknowledgements, Dead-Letter Queues, and Retries
- Work Queues, Prefetch, and Competing Consumers