Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Queues and Exchanges

Exchanges Overview

Learn what RabbitMQ exchanges do, the four built-in types, the default and predeclared exchanges, the mandatory flag and alternate exchanges.

An exchange receives every message a producer publishes and decides where it goes. It stores nothing: it just applies routing rules to a message and its routing key, then passes copies to the queues (or other exchanges) that match. Choosing the right exchange type is the most important design decision in a RabbitMQ topology.

pika calls are read-only examples. Runnable blocks are Python stand-ins of the routing rules, not the real broker.

Declaring an exchange

Python
# real pika code, read-only
channel.exchange_declare(
    exchange="shop.events",
    exchange_type="topic",    # direct, fanout, topic, headers
    durable=True,             # keep the exchange after a broker restart
    auto_delete=False,        # delete when the last binding is removed
    internal=False,           # True: publishers cannot publish to it directly
)

As with queues, redeclaring an existing exchange with different settings is an error, and the exchange name "" and names beginning with amq. are reserved.

The four built-in types

Exchange types

Direct Routing key must equal the binding key exactly.
Fanout Copy to every bound queue, ignore the key.
Topic Match dotted keys with * and # wildcards.
Headers Match on message headers, not the key.

Each type gets its own lesson in the next chapter, Routing Patterns.

1 / 2

Plugins add more types, for example a consistent hash exchange that spreads messages across queues by hashing the routing key, and a delayed message exchange. Core RabbitMQ also has the special default exchange and a few predeclared ones.

The default exchange

Every vhost has a nameless direct exchange, written "". Every queue is automatically bound to it with a binding key equal to the queue name. That is why basic_publish(exchange="", routing_key="hello") reaches the queue hello, as in Hello World: Publish and Consume. You cannot bind to it, unbind from it or delete it.

Predeclared exchanges

Fresh vhosts contain these standard exchanges (their names start with amq.): amq.direct, amq.fanout, amq.topic, amq.headers and amq.match (a headers exchange). There is also amq.rabbitmq.trace, used by the tracing feature. Real applications normally declare their own exchanges with meaningful names such as orders or billing.events.

Choosing a type

Need Use
Send to one named queue default exchange or direct
Send each message to a specific category direct
Broadcast to every subscriber fanout
Route by pattern ("all errors from any service") topic
Route on several attributes without a key convention headers

When in doubt, start with topic: it can imitate direct (exact words) and fanout (#).

A router in one function

This stand-in implements the matching rules of all four types in one place. It is a good place to see the differences side by side. Topic matching handles * (exactly one word) and # (zero or more words).

Python Four exchange types side by side (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Unroutable messages: mandatory and alternate exchanges

If no queue matches, the message normally disappears. Two features make that visible or safe:

  • mandatory flag. The publisher sets mandatory=True on basic_publish. If the message cannot be routed to any queue, the broker sends it back with basic.return, and the client library gives the publisher a callback or exception.
  • Alternate exchange. When you declare an exchange with the argument alternate-exchange naming another exchange, any message that this exchange cannot route is automatically re-published to the alternate one. A common design is a fanout alternate exchange bound to an unrouted queue, so nothing is silently lost.
Python
# real pika code, read-only
channel.exchange_declare("unrouted", "fanout", durable=True)
channel.queue_declare("unrouted.messages", durable=True)
channel.queue_bind("unrouted.messages", "unrouted")

channel.exchange_declare(
    "orders", "direct", durable=True,
    arguments={"alternate-exchange": "unrouted"},
)
Python Mandatory flag and alternate exchange (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exchange-to-exchange bindings

RabbitMQ extends AMQP by letting an exchange be bound to another exchange. Messages that match the binding flow from the source into the destination exchange, which routes them again. This lets you build layered topologies, for example a topic exchange for a department that feeds a company-wide audit exchange.

An internal exchange cannot receive publishes from clients; it is only a destination for such bindings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Do exchanges store messages?

    Exchanges are routing tables. Messages are stored in queues.
  2. 2. What is the default exchange?

    The default exchange has the empty name and routes by queue name, which is why publishing with exchange "" and a queue name works.
  3. 3. Which feature returns an unroutable message to the publisher?

    With mandatory set, an unroutable message is sent back using basic.return.
  4. 4. What does an alternate exchange do?

    Unroutable messages are re-published to the alternate exchange, so they can be caught in an "unrouted" queue.

Summary

  • Exchanges route; they never store messages.
  • The built-in types are direct, fanout, topic and headers, plus the nameless default exchange and predeclared amq.* exchanges.
  • Use mandatory or an alternate exchange so unroutable messages are not lost silently.
  • Exchanges can be bound to exchanges; internal exchanges accept only such bindings.

Next: Bindings and Routing Keys