Volume 4 · Chapter 6 — .NET Distributed Systems and Microservices Architecture

Messaging with RabbitMQ and Azure Service Bus

Goutham Mayaluri 7 min read .NETC#MicroservicesMessagingAzure

6.1 Introduction

Message-based communication is a core building block of distributed systems. Instead of services depending on each other at runtime, they exchange messages through a broker asynchronously - improving reliability, scalability, and loose coupling. The recurring engineering concerns are queues vs topics, reliable delivery with dead-letter queues, and idempotent consumers, because brokers deliver at-least-once.

6.2 The Broker Model: Queues vs Topics

A producer publishes messages to a broker without knowing the consumers. Aqueuedelivers each message to one consumer among competing consumers - point-to-point work distribution. Atopic(pub/sub) delivers a copy to every subscriber - event broadcasting. The choice depends on whether the message is work to be done once or an event many should react to.

sequenceDiagram
  autonumber
  participant Pay as Payment Service
  participant Broker as Broker (topic)
  participant Notif as Notification (subscriber)
  participant Audit as Audit (subscriber)
  participant DLQ as Dead-Letter Queue
  Pay-)Broker: publish PaymentCompleted
  Broker-)Notif: deliver
  Broker-)Audit: deliver
  Notif-->>Broker: complete (processed)
  Audit--xBroker: fails repeatedly (poison message)
  Broker-)DLQ: move after max delivery attempts

6.3 RabbitMQ and Azure Service Bus

RabbitMQ routes messages through exchanges to queues via bindings and routing keys - flexible and self-hosted. Azure Service Bus is a managed enterprise broker offering queues, topics/subscriptions, dead-letter queues, scheduled and deferred messages, sessions (for ordering), and duplicate detection. In .NET, MassTransit is a common abstraction over both, handling serialization, retries, and consumer wiring.


// A MassTransit consumer that reacts to a published event, idempotently.
public sealed class PaymentCompletedConsumer(IDedup dedup, ILedger ledger)
    : IConsumer<PaymentCompleted>
{
    public async Task Consume(ConsumeContext<PaymentCompleted> ctx)
    {
        if (await dedup.SeenAsync(ctx.Message.PaymentId)) return;   // at-least-once -> dedupe
        await ledger.PostAsync(ctx.Message.PaymentId, ctx.Message.Amount);
        await dedup.MarkAsync(ctx.Message.PaymentId);
    }
}

6.4 Reliability: Ordering, DLQs, and Idempotency

Where ordering matters, preserve it per key (partition keys / sessions), not globally. Messages that repeatedly fail (poison messages) are moved to a dead-letter queue for investigation rather than blocking the queue or retrying forever. And because delivery is at-least-once, consumers must be idempotent - deduping by message id or using naturally idempotent operations - so redelivery does no harm. Contracts (message schemas) must stay backward-compatible.

Senior Interview Question

Why use messaging instead of direct service calls, and what is the difference between a queue and a topic?

Messaging decouples services in time and contains failure, which is its main advantage over direct synchronous calls. With a direct call, the caller depends on the callee being up and fast right now, so a slow or failing callee propagates failure back and can cascade; with messaging, the producer hands the message to a durable broker and moves on, and the consumer processes when it can - so a downstream outage becomes a backlog the broker absorbs rather than a failure, spikes are leveled by the queue, producers and consumers scale independently, and new consumers can be added without changing producers. It also lets services evolve independently. The trade-off is asynchrony and eventual consistency, so I use messaging for state-change notifications and work that doesn’t need an immediate answer, keeping synchronous calls for queries that do. On queue vs topic: a queue is point-to-point - each message is delivered to exactly one consumer among competing consumers, which is the model for distributing work so each item is processed once (e.g. a payment to be processed). A topic is publish-subscribe - each message is delivered as a copy to every subscriber, which is the model for broadcasting an event that multiple independent services need to react to (e.g. a “payment completed” event consumed separately by notifications, audit, and fraud). So a queue answers “process this unit of work once, by one worker,” and a topic answers “tell all interested parties that this happened.” I choose a queue for command/work distribution where one consumer should handle each message, and a topic (pub/sub) for event distribution where many consumers react independently - and a system typically uses both: queues for work, topics for events. The key insight is that messaging buys temporal decoupling and resilience at the cost of eventual consistency, and queues and topics serve fundamentally different communication patterns (one-to-one work vs one-to-many events).

Principal Engineer Question

How do you design reliable enterprise messaging - handling duplicates, failures, and ordering?

Reliable messaging is about guaranteeing that messages are delivered and processed correctly despite the realities of distributed systems: at-least-once delivery, transient failures, poison messages, and occasionally-required ordering. I design for each. Duplicates: because brokers deliver at-least-once (a message can be redelivered after a consumer crash, a retry, or a timeout), every consumer must be idempotent - I make handlers dedupe by a unique message/business id recorded in a store, or use naturally idempotent operations (upserts keyed by business id, absolute-value sets), so processing the same message twice produces the same result and no double effect. This is non-negotiable and pairs with the reliable-publishing side. Reliable publishing: to avoid the dual-write problem (state saved but event lost, or vice versa) I use the transactional outbox - the message is written to an outbox table in the same transaction as the state change, and a relay publishes committed outbox rows to the broker, so state and event are atomic and delivery is at-least-once. Failures: transient failures are retried with bounded attempts and exponential backoff, but messages that repeatedly fail (poison messages) are moved to a dead-letter queue after a max-delivery count, so one bad message doesn’t block the queue or retry forever - the DLQ isolates them for investigation and possible reprocessing. Ordering: I avoid strict global ordering (expensive and unscalable) and preserve ordering only per key where the business needs it - all messages for one account/entity go to the same partition or session (Kafka partition keys, Service Bus sessions) processed in sequence, giving per-entity order while allowing parallelism across entities; where consumers are idempotent and operations commute, I relax ordering entirely for better scale. Contracts: message schemas are explicit, versioned, and backward- compatible (additive changes, tolerant readers) so producers and consumers deploy independently without breaking each other. Durability and delivery guarantees: I use durable messages and appropriate acknowledgement so messages aren’t lost on broker or consumer failure, and choose broker features (duplicate detection, sessions, DLQs) that fit. And I make it all observable - correlation ids and tracing through the message flow, plus monitoring of queue depth, DLQ counts, and processing lag - so stuck or failing messages are visible. Clear ownership of each message contract and queue rounds it out. So reliable enterprise messaging = idempotent consumers (for at-least-once), transactional outbox (for reliable publishing), retries plus dead-letter queues (for failures and poison messages), per-key ordering via partitions/sessions (only where needed), versioned backward-compatible contracts, durable delivery, and end-to-end observability - which together turn “publish and hope” into a dependable messaging backbone that behaves correctly under the duplicates, failures, and reordering that distributed messaging inevitably brings.

6.5 Banking Enterprise Scenario

A banking payment platform publishes aPaymentCompletedevent after processing, and notification, audit, fraud-analysis, and reporting services each consume it independently via a topic - so payment processing isn’t coupled to every downstream consumer, and a new consumer can be added without touching it. Producers publish through the transactional outbox, consumers dedupe by transaction id (at-least-once), ordering is preserved per account via sessions, and poison messages go to a dead-letter queue for review.

Chapter Revision Notes

  • Messaging decouples services in time and absorbs downstream outages as backlog.
  • Queue = one consumer per message (work distribution); topic = many subscribers (event broadcast).
  • RabbitMQ (exchanges/bindings) and Azure Service Bus (topics, DLQs, sessions); MassTransit abstracts both.
  • Consumers must be idempotent (at-least-once); poison messages go to dead-letter queues.
  • Preserve ordering per key via partitions/sessions; keep message contracts backward-compatible.