RabbitMQ Exchange Types
What You'll Learn
You'll learn the four types of exchanges in RabbitMQ and how each routes messages differently to queues.
Core Concept
An exchange in RabbitMQ is the routing engine that decides which queue(s) should receive a message. Producers send messages to exchanges (not directly to queues), and the exchange type determines the routing logic.
Think of exchanges like postal sorting facilities: different facilities use different rules to decide where mail goes.
The Four Exchange Types
Direct Exchange
Routes messages to queues based on an exact routing key match.
Analogy: Like addressing a letter to a specific apartment number—only that exact recipient gets it.
When to use: When you need precise, one-to-one routing (e.g., sending a task to a specific worker type: email.sender, sms.sender).
Fanout Exchange
Broadcasts messages to all bound queues, ignoring routing keys entirely.
Analogy: Like a fire alarm—everyone hears it, no filtering.
When to use: When multiple independent systems need the same event (e.g., broadcasting a "user_registered" event to analytics, email service, and notification service).
Topic Exchange
Routes based on pattern matching against routing keys using wildcards (* matches one word, # matches zero or more words).
Analogy: Like subscribing to magazine categories—you might want "sports.*" (all sports) or "news.#.breaking" (breaking news at any level).
When to use: When you need flexible, hierarchical routing (e.g., log.error.api, log.warn.database—subscribers can listen to log.error.* or log.#).
Headers Exchange
Routes based on message header attributes instead of routing keys, using header matching rules.
When to use: When routing logic is too complex for topic patterns and requires multiple criteria (rarely used compared to topic exchanges).
Key Takeaway: Direct for exact matching, fanout for broadcasting, topic for pattern-based routing, and headers for complex attribute-based routing—choose based on how consumers need to filter messages.