Skip to content
LATEST

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

Upgradix
Upgradix Code. Learn. Ship.

Fanout Exchanges – Pub/Sub Broadcasting Across Services

A Fanout Exchange copies every incoming message to all queues bound to it. It ignores routing keys completely. Use it when one event must trigger multiple independent .NET microservices at the exact same time.

Fanout Exchanges – Pub/Sub Broadcasting Across Services

Quick Answer: A Fanout Exchange copies every incoming message and broadcasts it to all bound queues at the exact same time. It completely ignores routing keys, making it the cleanest way to run Pub/Sub across independent .NET microservices.

Imagine Priya runs a busy food delivery app in Bengaluru. At 8:00 PM on a Friday, Ravi places dinner order ORD-5042.

The moment Ravi's order is confirmed, three separate .NET services must act at once. One sends Ravi an SMS, one writes an audit log, and one clears stale Redis cache.

How does the Order API notify all three services at the same time without slowing down Ravi's checkout?

1. Why Do We Need a Fanout Exchange?

The problem without a fanout exchange

In a naive setup, the Order API calls each downstream service directly over HTTP, one after another.

Example 1: Tightly coupled Order API calling three services

This simple setup works for 10 orders a minute, but fails under Friday night traffic.

public async Task ConfirmOrderAsync(string orderId)
{
    await _smsClient.SendAsync(orderId);       // 1. Send SMS to Ravi
    await _auditClient.LogAsync(orderId);      // 2. Save audit record
    await _cacheClient.ClearAsync(orderId);    // 3. Clear Redis cache
}

What happens under load

Order ORD-5042 -> SMS Service OK (140 ms)
Order ORD-5042 -> Audit Service TIMEOUT (5000 ms)
Order ORD-5042 -> Cache Clear NEVER RAN! Checkout failed for Ravi.

This setup works on a quiet afternoon. However, it breaks when real traffic arrives.

  1. If the Audit Service slows down, Ravi's checkout screen hangs.
  2. If the SMS Service crashes, the Cache Service never gets called.
  3. Every time Priya adds a new service (like Loyalty Points), she must edit and redeploy the Order API.

Now think about a cricket match night with 5,000 orders per minute. We need a way to broadcast one event to many services at once, while keeping the Order API fast and independent.

The solution: Fanout Exchange (Pub/Sub)

Fanout Exchange = a RabbitMQ router that copies one message and sends it to every queue bound to it.

Pub/Sub (Publish/Subscribe) = a messaging pattern where a publisher broadcasts events without knowing who is listening.

With a fanout exchange, Priya's Order API publishes ONE OrderConfirmed event and moves on. RabbitMQ instantly clones and broadcasts a separate copy to each microservice's own queue.

Live Broadcast: 1-to-3 Fanout Split in Priya's Food App

Watch one OrderConfirmed event pulse at the exchange and split into 3 simultaneous copies.

Ravi → Order API (.NET)
Confirms ORD-5042 · Publishes 1 event
1 Message · routingKey: "" (ignored)
order.events.fanout
Fanout Exchange · Clones 1 → 3 instantly
Simultaneous 3-Way Broadcast
q.notifications
Notification Service
Sends SMS to Ravi
Copy #1 Received
q.audit.log
Audit Log Service
Writes SQL audit row
Copy #2 Received
q.cache.clear
Cache Service
Clears Redis key
Copy #3 Received
Producer (Order API) Fanout Exchange Bound Queue & .NET Worker Simultaneous Broadcast

All three queues receive their own copy at the exact same moment. If the Audit Service goes offline, q.audit.log holds Copy #2 safely while Ravi still gets his SMS immediately.

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

Binding = a rule that links a queue to an exchange so messages flow into that queue.

With a fanout exchange, the producer does not know any queue names. It only declares the exchange with ExchangeType.Fanout and publishes with an empty routing key.

Example 2: Publishing an OrderConfirmed event in C# (RabbitMQ.Client v7)

The Order API broadcasts one JSON message to order.events.fanout.

await channel.ExchangeDeclareAsync(
    exchange: "order.events.fanout",
    type: ExchangeType.Fanout,
    durable: true);

var payload = "{\"orderId\":\"ORD-5042\",\"customer\":\"Ravi\"}";
var body = Encoding.UTF8.GetBytes(payload);

// Fanout exchanges ignore the routingKey, so pass an empty string
await channel.BasicPublishAsync(
    exchange: "order.events.fanout",
    routingKey: string.Empty,
    body: body);

Next, each .NET microservice declares its own queue and binds it to the same fanout exchange.

Example 3: Binding the Notification Service queue in C#

Repeat this pattern with a unique queue name for Audit Log and Cache Invalidation.

await channel.ExchangeDeclareAsync("order.events.fanout", ExchangeType.Fanout, durable: true);
await channel.QueueDeclareAsync("q.notifications", durable: true, exclusive: false, autoDelete: false);
await channel.QueueBindAsync(
    queue: "q.notifications",
    exchange: "order.events.fanout",
    routingKey: string.Empty);

Expected output across all three .NET services

[NotificationService] Sent SMS to Ravi for ORD-5042
[AuditLogService]     Saved audit event for ORD-5042
[CacheService]        Deleted Redis key order:ORD-5042

All three services receive the exact same event at the same time. If Priya adds a fourth Loyalty Service tomorrow, she just binds q.loyalty to order.events.fanout without touching the Order API.

3. Direct Calls vs. Fanout Exchange

Direct service calls vs. RabbitMQ Fanout Exchange
Without fanout exchange With fanout exchange
Order API waits for every service to finish. Order API publishes once and replies in milliseconds.
One slow or down service breaks checkout. Each service runs independently with its own queue.
Adding a new service requires editing Order API. New services subscribe by binding a new queue.

The important terms to remember

  • Fanout Exchange = an exchange that broadcasts every message to all bound queues.
  • Pub/Sub = a pattern where publishers emit events without knowing who consumes them.
  • Routing Key = a label on a message that a fanout exchange completely ignores.

Design tip: For distributed cache invalidation across multiple API instances, let each pod create its own temporary exclusive queue bound to the fanout exchange. That way, every running server clears its local memory cache.

4. Common Mistakes to Avoid

1. Sharing one queue across different microservices

If Notification Service and Audit Service read from the same queue, RabbitMQ splits messages between them instead of broadcasting. Half the orders will miss their SMS.

Better approach: Give every distinct microservice its own named queue bound to the fanout exchange.

2. Expecting a fanout exchange to filter messages

Developers sometimes pass a routing key like order.cancelled to a fanout exchange and expect filtering. RabbitMQ ignores it and sends the message everywhere.

Better approach: Use a Direct or Topic exchange when consumers only want a subset of events.

5. Interview Questions & Practice

Question 1: When would you choose a Fanout Exchange over a Direct Exchange?

What the interviewer expects: Clear distinction between broadcasting to everyone vs. routing to a specific target.

Strong answer: "I use a Direct Exchange when one specific service should handle a task, like sending a payment to a billing worker. I use a Fanout Exchange when one event, like Ravi's confirmed food order, must be broadcast to many independent services like notifications, audit logs, and cache clearing at the same time."

Practice: Hospital appointment cancellation

Design a fanout topology for a hospital app when a doctor cancels a 4:00 PM slot. List the exchange name and three bound queues for patient alerts, billing refunds, and slot availability updates.

Expected result: One appointment.cancelled.fanout exchange bound to q.patient.alerts, q.billing.refunds, and q.slot.sync.

6. Next Steps

  • Previous Article: Direct Exchanges – Exact-Match Task Routing
  • Next Article: Topic Exchanges – Wildcard Pattern Routing (* and #)

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.