Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.

Topic Exchanges – Wildcard Pattern Routing (* and #)

A Topic Exchange routes messages by matching dot-delimited routing keys against wildcard patterns. Use * to match exactly one word and # to match zero or more words, so each .NET service receives only the events it needs.

Topic Exchanges – Wildcard Pattern Routing (* and #)

Quick Answer: A Topic Exchange routes messages by matching dot-delimited routing keys against wildcard patterns. Use * to match exactly one word and # to match zero or more words, so each .NET service receives only the events it needs.

Imagine Karthik runs an online shopping app across Chennai, Bengaluru, and Mumbai. Lakshmi in Chennai places an order, creating the event order.chennai.created.

Seconds later, a UPI payment fails in Chennai, creating payment.chennai.failed. Meanwhile, a customer in Bengaluru cancels an order, creating order.bengaluru.cancelled.

How does each .NET microservice subscribe only to the exact city, domain, or error events it cares about?

1. Why Do We Need a Topic Exchange?

The problem without a topic exchange

If Karthik uses a Fanout Exchange, every microservice receives every event and wastes CPU throwing away messages it does not need. If he uses a Direct Exchange, he must manually bind every exact key.

Example 1: Fragile exact-match bindings with a Direct Exchange

This setup works for two cities, but explodes when Karthik expands across India.

// Every new city or action forces new bindings and redeployments
await channel.QueueBindAsync("q.all.orders", "shop.direct", "order.chennai.created");
await channel.QueueBindAsync("q.all.orders", "shop.direct", "order.chennai.cancelled");
await channel.QueueBindAsync("q.all.orders", "shop.direct", "order.bengaluru.created");
await channel.QueueBindAsync("q.all.orders", "shop.direct", "order.bengaluru.cancelled");

This works when you have 3 events. However, it becomes a maintenance nightmare at scale.

  1. Adding Hyderabad requires updating bindings across multiple services.
  2. You cannot easily subscribe to "all failed events across every domain."
  3. Services end up either over-fetching (Fanout) or missing new event types (Direct).

The solution: Topic Exchange with * and #

Topic Exchange = a RabbitMQ router that matches dot-separated routing keys against wildcard binding patterns.

Star (*) = a wildcard that matches exactly one word between dots.

Hash (#) = a wildcard that matches zero or more words.

Watch how Karthik's shop.events.topic exchange evaluates three live events and lights up only the matching queues.

Live Wildcard Matcher: Topic Exchange in Karthik's Shopping App

Each incoming routing key is tested against three wildcard patterns. Only matching queues receive the message.

Incoming Event: order.chennai.created
shop.events.topic
Topic Exchange · Evaluates * and # patterns
q.chennai.ops
*.chennai.* Matched
q.all.orders
order.# Matched
q.alerts.failed
#.failed Skipped
Topic Exchange Pattern Matched Skipped (No Match)

Notice how order.chennai.created routes to both *.chennai.* and order.#, while order.bengaluru.cancelled only matches order.#.

2. How Topic Exchanges Work in C# (.NET)

Routing keys in a topic exchange are lowercase words separated by dots, like <domain>.<city>.<action>. Keep them under 255 bytes.

Example 2: Publishing domain events to a Topic Exchange in C#

Karthik's Order API publishes Lakshmi's event with a 3-part routing key.

await channel.ExchangeDeclareAsync(
    exchange: "shop.events.topic",
    type: ExchangeType.Topic,
    durable: true);

var body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-991\",\"user\":\"Lakshmi\"}");

await channel.BasicPublishAsync(
    exchange: "shop.events.topic",
    routingKey: "order.chennai.created",
    body: body);

Now each .NET microservice binds its queue using the exact wildcard pattern it needs.

Example 3: Binding queues with * and # wildcards in C#

Three services subscribe to different slices of the same event stream.

// 1. Chennai Ops wants any 3-word event happening in Chennai
await channel.QueueBindAsync("q.chennai.ops", "shop.events.topic", "*.chennai.*");

// 2. Order Analytics wants every order event, regardless of city or depth
await channel.QueueBindAsync("q.all.orders", "shop.events.topic", "order.#");

// 3. Alert Service wants any failed event from any domain
await channel.QueueBindAsync("q.alerts.failed", "shop.events.topic", "#.failed");

Expected output when order.chennai.created is published

[ChennaiOps]     Received order.chennai.created (Lakshmi)
[OrderAnalytics] Received order.chennai.created (Lakshmi)
[AlertService]   (idle - pattern #.failed did not match)

3. Direct vs. Fanout vs. Topic Exchange

Choosing the right RabbitMQ exchange type
Exchange Type Routing Rule Best Use Case
Direct Exact string match on routing key. Targeted tasks like payment.process.
Fanout Ignores routing key; sends to all queues. Broadcasting one event to every service.
Topic Wildcard match using * and #. Flexible, multi-criteria event subscriptions.

The important terms to remember

  • Star (*) = matches exactly one word in a dot-delimited routing key.
  • Hash (#) = matches zero, one, or many words.
  • Binding Pattern = the wildcard rule attached between a queue and a topic exchange.

Design tip: Agree on a consistent naming convention across your .NET teams, such as <domain>.<region>.<action>. Predictable keys make wildcard subscriptions easy to read and debug.

4. Common Mistakes to Avoid

1. Confusing * with #

Developers often bind a queue with order.* expecting it to catch order.chennai.created. It will not match because * only matches one word, not two.

Better approach: Use order.# to match any number of words after order, or order.*.* for exactly three words.

2. Binding every queue with #

Binding a queue with just # turns a Topic Exchange into a Fanout Exchange, but with extra pattern-matching overhead.

Better approach: If every consumer truly needs every message, use a Fanout Exchange instead.

5. Interview Questions & Practice

Question 1: What is the difference between * and # in a RabbitMQ Topic Exchange?

What the interviewer expects: Exact word count rules and a concrete routing key example.

Strong answer: "In a Topic Exchange, routing keys are words separated by dots, like order.chennai.created. A star (*) matches exactly one word, so *.chennai.* matches 3-word keys for Chennai. A hash (#) matches zero or more words, so order.# matches both order.created and order.chennai.created."

Practice: Railway ticket alert system

A railway portal publishes events like ticket.chennai.confirmed and ticket.delhi.cancelled. Write the binding pattern for a queue that only wants cancellations from any city.

Expected result: ticket.*.cancelled (or #.cancelled if other domains also emit cancellation events).

6. Next Steps

  • Previous Article: Fanout Exchanges – Pub/Sub Broadcasting Across Services
  • Next Article: Headers Exchanges & Message Metadata Routing

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.