Skip to content
LATEST

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

Upgradix
Upgradix Code. Learn. Ship.

Headers Exchanges & Message Metadata Routing

A Headers Exchange ignores the routing key and routes messages using custom key-value AMQP headers. Queues choose x-match: all (every header must match) or x-match: any (at least one header must match).

Headers Exchanges & Message Metadata Routing

Quick Answer: A Headers Exchange ignores the routing key and routes messages using custom key-value AMQP headers. Queues choose x-match: all (every header must match) or x-match: any (at least one header must match).

Imagine Meena manages a hospital lab report system in Chennai. Every time a lab test finishes, the system publishes a report event.

Each report carries several attributes: file format (pdf or csv), urgency (urgent or normal), and department (cardiology or billing).

How do we route reports using any combination of these attributes without creating fragile, unreadable routing keys?

1. Why Do We Need a Headers Exchange?

The problem without a headers exchange

With a Topic Exchange, you must pack every attribute into a single dot-separated string in a strict order.

Example 1: Fragile multi-attribute routing key in a Topic Exchange

This works for two fields, but breaks down quickly when metadata grows.

// Fixed order: department.priority.format.branch
var routingKey = "cardiology.urgent.pdf.chennai";

// Consumer only wants urgent PDFs from any department or branch
var pattern = "*.urgent.pdf.*";

What happens when requirements change

New field added (insuranceType) -> "cardiology.urgent.pdf.chennai.cashless"
Old binding pattern "*.urgent.pdf.*" -> STOPPED MATCHING!

This works when fields never change. However, real business payloads evolve often.

  1. Every consumer breaks if you change the order of words in the routing key.
  2. Routing keys only hold plain strings, never numbers or structured metadata pairs.
  3. Writing wildcard rules for 5 or 6 optional attributes becomes almost impossible to read.

We need a way to route messages by named key-value pairs where order does not matter.

The solution: Headers Exchange

Headers Exchange = a RabbitMQ router that checks key-value pairs in the message's AMQP headers instead of the routing key.

x-match: all = an AND rule where every header in the queue binding must match the message.

x-match: any = an OR rule where matching just one header in the queue binding is enough.

Meena's Lab API attaches a dictionary of headers to each report and publishes it to lab.reports.headers. RabbitMQ inspects the headers and delivers the report only to queues whose rules pass.

Live Flow: Metadata Inspection (x-match: all vs. x-match: any)

Watch RabbitMQ inspect Dr. Meena's report headers, match two queues, and skip the billing queue.

Meena's Lab API (.NET)
Publishes Heart Scan Report (routingKey: "")
format: pdf priority: urgent dept: cardio
AMQP Headers Attached
lab.reports.headers
Headers Exchange · Evaluates x-match Rules
q.urgent.pdf
x-match: all
format=pdf & priority=urgent
MATCHED (2/2)
q.doctor.alerts
x-match: any
dept=cardio OR dept=neuro
MATCHED (1/2)
q.billing.csv
x-match: all
format=csv & dept=billing
SKIPPED (0/2)
Inspecting Headers Rule Passed (Delivered) Rule Failed (Skipped)

RabbitMQ delivers the report to q.urgent.pdf (both headers match) and q.doctor.alerts (at least one header matches), while q.billing.csv is untouched.

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

BasicProperties.Headers = a dictionary on each AMQP message where you store custom metadata key-value pairs.

First, Meena's Lab API declares the exchange with ExchangeType.Headers and attaches the metadata dictionary to BasicProperties.

Example 2: Publishing a message with custom AMQP headers in C#

Notice that routingKey is empty because Headers Exchanges ignore it.

await channel.ExchangeDeclareAsync("lab.reports.headers", ExchangeType.Headers, durable: true);

var props = new BasicProperties
{
    Headers = new Dictionary<string, object?>
    {
        ["format"] = "pdf",
        ["priority"] = "urgent",
        ["dept"] = "cardio"
    }
};

var body = Encoding.UTF8.GetBytes("{\"reportId\":\"LAB-882\",\"city\":\"Chennai\"}");

await channel.BasicPublishAsync(
    exchange: "lab.reports.headers",
    routingKey: string.Empty,
    mandatory: false,
    basicProperties: props,
    body: body);

Next, each consumer binds its queue by passing a binding arguments dictionary containing x-match.

Example 3: Binding queues with x-match: all and x-match: any in C#

q.urgent.pdf requires both headers; q.doctor.alerts requires just one.

// Rule 1: x-match = all (AND logic)
var urgentPdfArgs = new Dictionary<string, object?>
{
    ["x-match"] = "all",
    ["format"] = "pdf",
    ["priority"] = "urgent"
};
await channel.QueueBindAsync("q.urgent.pdf", "lab.reports.headers", string.Empty, urgentPdfArgs);

// Rule 2: x-match = any (OR logic)
var doctorAlertArgs = new Dictionary<string, object?>
{
    ["x-match"] = "any",
    ["dept"] = "cardio",
    ["priority"] = "critical"
};
await channel.QueueBindAsync("q.doctor.alerts", "lab.reports.headers", string.Empty, doctorAlertArgs);

Expected output

[UrgentPdfWorker]   Received LAB-882 (matched format=pdf AND priority=urgent)
[DoctorAlertWorker] Received LAB-882 (matched dept=cardio)
[BillingCsvWorker]  (no message received)

Both matching workers receive the report immediately, even though the message also had extra headers they did not ask for.

3. Topic Exchange vs. Headers Exchange

Topic Exchange vs. Headers Exchange in RabbitMQ
Topic Exchange Headers Exchange
Routes using a dot-separated string key. Routes using a key-value header dictionary.
Field order in the routing key matters. Header order does not matter at all.
Faster lookup for high-throughput streams. Slightly slower due to map comparison.

The important terms to remember

  • Headers Exchange = an exchange that matches messages on custom AMQP header pairs.
  • x-match: all = requires every header in the binding to match the message.
  • x-match: any = requires at least one header in the binding to match.

Design tip: Prefer Direct or Topic exchanges for simple routing because they are slightly faster. Reach for a Headers Exchange when you have 3+ independent metadata attributes or non-string values.

4. Common Mistakes to Avoid

1. Forgetting to set the x-match argument

If you omit x-match when binding a queue, the rule becomes unclear to your team and defaults to matching all headers.

Better approach: Always set ["x-match"] = "all" or ["x-match"] = "any" explicitly in every binding.

2. Mismatching header value types

If the producer sends ["version"] = 2 (an integer) and the queue binds with ["version"] = "2" (a string), RabbitMQ treats them as a mismatch and drops the route.

Better approach: Share a common constants class or standardize all routing headers as lowercase strings across services.

5. Interview Questions & Practice

Question 1: When would you choose a Headers Exchange over a Topic Exchange?

What the interviewer expects: Understanding of multi-attribute metadata routing and trade-offs.

Strong answer: "I use a Topic Exchange when my routing keys follow a clean hierarchy like order.created.india. I switch to a Headers Exchange when a message has many independent attributes—like Meena's hospital reports with format, urgency, and department—where consumers need flexible AND/OR matching without caring about field order."

Practice: E-commerce invoice routing

Design a Headers Exchange for an online store that routes invoices by region (south, north), format (pdf, xml), and tier (vip, standard). Define two bindings: one for VIP PDF invoices, and one for any XML or South-region invoice.

Expected result: Queue 1 uses x-match: all with tier=vip and format=pdf; Queue 2 uses x-match: any with format=xml and region=south.

6. Next Steps

  • Previous Article: Topic Exchanges – Wildcard Pattern Routing (* and #)
  • Next Article: Request-Reply (RPC) Pattern with Correlation IDs in C#

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.