Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Routing Patterns

The Direct Exchange

Learn the RabbitMQ direct exchange: exact-match routing, multiple bindings, log severity routing with pika, and where direct exchanges fit best.

The direct exchange is the simplest routing rule: a message goes to every queue whose binding key is exactly equal to the message's routing key. No wildcards, no guessing. It is ideal when you can name the category of a message up front, such as a log severity, a customer tier or a job type.

pika code is read-only for a real broker. Runnable blocks are Python stand-ins of the routing logic.

The rule

flowchart LR
    P["Publisher"] -->|"key = error"| X(["logs (direct)"])
    X -->|"binding: error"| QE["errors queue"]
    X -->|"binding: error"| QA["audit queue"]
    X -->|"binding: warning"| QW["warnings queue"]
    X -.->|"key = info: no binding"| N["dropped"]

A message with key error reaches every queue bound with error: two queues here.

Three consequences follow:

  • One binding key may point at several queues; each gets a copy.
  • One queue may be bound with several keys to listen to several categories.
  • A key nobody bound to produces no delivery (the message is dropped unless you use mandatory or an alternate exchange, see Exchanges Overview).

A log router with pika

This is the classic example: publish log lines with the severity as routing key, and let each consumer choose which severities to receive.

Python
# emit_log.py  (real pika code, read-only)
import sys
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.exchange_declare(exchange="logs", exchange_type="direct")

severity = sys.argv[1] if len(sys.argv) > 1 else "info"
message = " ".join(sys.argv[2:]) or "hello"

channel.basic_publish(exchange="logs", routing_key=severity, body=message.encode())
print(f"[{severity}] sent {message}")
connection.close()
Python
# receive_logs.py  (real pika code, read-only)
import sys
import pika

severities = sys.argv[1:] or ["info"]

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.exchange_declare(exchange="logs", exchange_type="direct")

queue = channel.queue_declare(queue="", exclusive=True).method.queue   # private queue

for severity in severities:
    channel.queue_bind(exchange="logs", queue=queue, routing_key=severity)

def callback(ch, method, properties, body):
    print(f"[{method.routing_key}] {body.decode()}")

channel.basic_consume(queue=queue, on_message_callback=callback, auto_ack=True)
channel.start_consuming()

Run python receive_logs.py error warning > errors.log in one terminal and python receive_logs.py info warning error in another, then publish with python emit_log.py error "disk full". Both consumers print it; a message with severity info reaches only the second.

Each receiver creates its own exclusive, server-named queue and binds it once per severity. When the receiver disconnects, its queue is deleted.

Try it: a direct exchange stand-in

Python Direct routing with multiple bindings (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.

Observe that error fans out to three queues even though the exchange is "direct". Direct does not mean one destination: it means exact matching.

Direct exchange and work routing

A very common use of direct exchanges is routing jobs by type to specialized workers:

  • key thumbnail goes to the queue read by image workers,
  • key transcode goes to the video workers,
  • key email goes to the mail workers.

Producers just pick the key; adding a new worker type means one new queue and binding, with no producer code change.

Python Routing jobs to specialized workers (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.

The typo at the end shows the weakness of exact matching: a misspelled key silently loses the job. Defend against it with mandatory=True, an alternate exchange, or constants shared between producer and consumer.

The default exchange is a direct exchange

You have already used one without knowing: the nameless default exchange is a direct exchange where every queue is bound with its own name (Bindings and Routing Keys). A hand-built direct exchange adds control: you choose the key names and can bind several queues to one key.

When to use something else

  • Need broadcast to all? Use fanout.
  • Need patterns such as "all errors from any service"? Use topic.
  • Keys with exactly one level and a small, fixed set of values are where direct shines.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a direct exchange deliver a message to a queue?

    Direct exchanges use exact string equality between the routing key and the binding key.
  2. 2. Two queues are bound to a direct exchange with the same key. A message with that key is published. What happens?

    Every queue with a matching binding gets its own copy.
  3. 3. Why does the receiver in the log example declare an exclusive, server-named queue?

    An empty name with exclusive=True yields a private throw-away queue for that subscriber.
  4. 4. What is the main risk of exact-match routing?

    A key with no matching binding means no delivery, so typos go unnoticed unless you use mandatory or an alternate exchange.

Summary

  • A direct exchange routes on exact equality of routing key and binding key.
  • One key can feed many queues and one queue can use many keys.
  • Typical uses: log severities and job-type routing.
  • The default exchange is a direct exchange bound by queue name.
  • Guard against typos with mandatory flags or alternate exchanges.

Next: Fanout and Publish/Subscribe