Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Routing Patterns

The Topic Exchange

Master the RabbitMQ topic exchange: dotted routing keys, the * and # wildcards, worked matching examples, naming conventions and common pitfalls.

The topic exchange is the workhorse of flexible routing. Routing keys are lists of words separated by dots, such as order.created.eu, and bindings can use two wildcards to describe patterns. A consumer can say "give me everything about orders", or "only errors from the payment service", without the publisher knowing who is listening.

pika code is read-only for a real broker. The runnable matcher is a Python stand-in that follows the topic rules, so you can test your patterns.

The rules

A topic routing key is a string of words delimited by dots, up to 255 bytes in total. A binding key has the same shape but may contain:

  • * (star): matches exactly one word.
  • # (hash): matches zero or more words.

Wildcard cheat sheet

  • = one word
order.* matches order.created but not order.created.eu.

= zero or more

order.# matches order, order.created and order.created.eu.
No wildcard Behaves like a direct exchange.
Just # Matches everything, like a fanout.

Wildcards must be whole words. "ord*" is not a pattern; it is a literal word.

1 / 2

Examples against the routing key stock.nyse.acme:

Binding key Matches? Why
stock.nyse.acme yes exact
stock.*.acme yes * stands for nyse
stock.* no * is one word, but two remain
stock.# yes # swallows nyse.acme
#.acme yes # swallows stock.nyse
*.*.* yes three words
# yes everything
stock.nasdaq.* no second word differs

Real code: a logging example

Use facility.severity as the key, for example kern.critical or auth.info.

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

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.exchange_declare(exchange="topic_logs", exchange_type="topic")

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

channel.basic_publish(exchange="topic_logs", routing_key=routing_key, body=message.encode())
connection.close()
Python
# receive_logs_topic.py  (real pika code, read-only)
import sys
import pika

binding_keys = sys.argv[1:]          # e.g. "kern.*" or "*.critical" or "#"

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
channel.exchange_declare(exchange="topic_logs", exchange_type="topic")

queue = channel.queue_declare(queue="", exclusive=True).method.queue
for key in binding_keys:
    channel.queue_bind(exchange="topic_logs", queue=queue, routing_key=key)

channel.basic_consume(
    queue=queue,
    on_message_callback=lambda ch, m, p, body: print(f"[{m.routing_key}] {body.decode()}"),
    auto_ack=True,
)
channel.start_consuming()

Start receivers with "#" (everything), "kern.*" (all kernel messages) and "*.critical" (critical from anywhere); then publish kern.critical "A critical kernel error" and watch which receivers print it.

A matcher you can experiment with

This stand-in implements the same word-by-word rules. The recursive function handles # by trying to consume zero, one, two... words.

Python Topic pattern tester (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 last pattern, stock.nyse.acme.#, matches even though the key has no fifth word, because # means zero or more. That surprises many beginners.

Routing a whole system

Here a topic exchange feeds four queues with different interests. Try publishing other keys.

Python Subscribers with patterns (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.

Look at order.paid.eu: both warehouse (order.paid.#) and eu-report (order.*.eu) match it, and audit receives everything.

Designing a good key hierarchy

  • Order words from general to specific: domain.entity.action.region. Prefixes then match whole families (order.#).
  • Keep the number of words fixed where possible so * stays predictable.
  • Put filterable things in the key, not in the body: the broker can only route on the key (or headers).
  • Do not put unbounded values (user ids, timestamps) in keys unless consumers truly filter on them; each new binding pattern costs memory.
  • Use lowercase, no spaces, and avoid dots inside a word.

Common pitfalls

  • Expecting * to match zero words. It never does; use # for that.
  • Using * or # in the routing key. Wildcards have meaning only in binding keys; in a routing key they are ordinary characters.
  • Overlapping patterns. One queue bound with a.* and *.b receives a.b once, not twice (Bindings and Routing Keys).
  • Forgetting the key length limit: a routing key may be at most 255 bytes.

Topic versus direct and fanout

Topic can imitate both: a binding without wildcards is a direct binding, and # is a fanout binding. It is slightly more expensive than direct to evaluate, but the cost is rarely a problem; RabbitMQ uses an efficient trie to match large numbers of bindings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which binding key matches the routing key "order.created.eu"?

    matches one or more remaining words. order.* needs exactly two words, *.eu needs two words, and order.created is exact on only two words.

  2. 2. Does "stock.#" match the routing key "stock"?

    The hash wildcard can match zero words, so the key "stock" matches "stock.#".
  3. 3. What does the binding key "#" do on a topic exchange?

    A lone # matches any sequence of words, so the queue receives all messages like a fanout.
  4. 4. Where do wildcards work?

    Publishers send literal routing keys. Wildcards are meaningful only in the binding keys of queues.

Summary

  • Topic routing keys are dot-separated words; binding keys may use * (exactly one word) and # (zero or more).
  • With no wildcards a topic binding acts like direct; # alone acts like fanout.
  • Order words from general to specific and keep the structure stable.
  • Wildcards belong only in binding keys.
  • One queue receives one copy even if several of its bindings match.

Next: Headers and the Default Exchange