Distributed Transactions: Saga Pattern and Outbox Pattern :👈 👉:REST-vs-SOAP

Building Event-Driven Microservices Using RabbitMQ and ASP.NET Core

Building Event-Driven Microservices Using RabbitMQ and ASP.NET Core

1. What Is Event-Driven Architecture?

Event-Driven Architecture (EDA) is an architectural pattern in which services communicate by publishing and consuming events.

An event represents something that has already happened in the system.

Examples:

  • OrderPlaced
  • PaymentCompleted
  • InventoryReserved
  • ShipmentCreated
  • UserRegistered

Instead of directly calling another microservice, a service publishes an event. Other services interested in that event receive and process it independently.

Traditional synchronous communication

Consider an e-commerce application:

Order Service HTTP Request Payment Service HTTP Request Inventory Service HTTP Request Notification Service Each service waits for the next HTTP response

In this approach, the Order Service directly depends on other services. If one downstream service is unavailable, the entire operation may be affected.

Event-driven communication

Order Service Publish: OrderPlaced RabbitMQ Message Broker Payment Service Inventory Service Notification Service Each service consumes the event independently

RabbitMQ receives the event and routes it to interested consumers. Each consumer processes the event independently.

2. What Is RabbitMQ?

RabbitMQ is an open-source message broker that enables applications and microservices to communicate through messages.

It acts as an intermediary between message producers and message consumers.

Important RabbitMQ components

  • Producer: Application or service that publishes messages.
  • Consumer: Application or service that receives and processes messages.
  • Queue: Stores messages until consumers receive them.
  • Exchange: Receives published messages and routes them to queues.
  • Binding: Connects an exchange to a queue and can define routing rules.
  • Routing Key: Helps an exchange determine where a message should go.
  • Virtual Host: Provides logical isolation for exchanges, queues, bindings, and permissions.
  • Channel: A lightweight communication session inside a connection.
  • Connection: A network connection between an application and RabbitMQ.
  • Consumer Acknowledgement: Confirms that a message has been successfully processed.

3. RabbitMQ Architecture

2. RabbitMQ Internal Architecture

Producer Order Service Exchange Routing Rules Queue A Payment Queue B Inventory Queue C Notification Consumer A Consumer B Consumer C Exchange routes messages to bound queues

The producer does not normally send a message directly to a queue. It publishes the message to an exchange, which routes it to one or more queues according to its type and bindings.

4. Types of RabbitMQ Exchanges

4.1 Direct Exchange

A Direct Exchange routes messages to queues whose binding key exactly matches the message routing key.

Direct Exchange

Producer Direct Exchange order.created Order Queue Binding: order.created

Use cases:

  • Routing order-related events.
  • Routing payment-related events.
  • Sending messages to a specific processing queue.

4.2 Fanout Exchange

A Fanout Exchange broadcasts messages to all queues bound to it. Routing keys are ignored.

Producer Fanout Exchange Payment Queue Inventory Queue Notification Queue

Use cases:

  • Broadcasting an event to multiple services.
  • Sending notifications to different systems.
  • Distributing application-wide events.

4.3 Topic Exchange

A Topic Exchange routes messages based on routing-key patterns.

Producer Topic Exchange Order Queue Binding: order.* Payment Queue Binding: payment.# Failure Queue Binding: #.failed

Special characters:

  • * matches exactly one word.
  • # matches zero or more words.

Example routing keys:

order.created
order.cancelled
payment.completed
payment.failed

Example bindings:

order.*       Matches order.created and order.cancelled
payment.#     Matches payment.completed and payment.failed
#.failed      Matches keys ending with failed

Use cases:

  • Domain event routing.
  • Microservice event subscriptions.
  • Routing events by business category.

4.4 Headers Exchange

A Headers Exchange routes messages using message headers rather than routing keys.

It is useful when routing depends on multiple message attributes.

5. Recommended Microservices Architecture

Consider an e-commerce application with four microservices:

  • Order Service: Creates customer orders.
  • Payment Service: Processes payments.
  • Inventory Service: Reserves product stock.
  • Notification Service: Sends order notifications.

Event-Driven Architecture – Overall Flow

Customer / Client ASP.NET Core API Order Service RabbitMQ Exchange and Message Routing Payment Service Inventory Service Notification Service

Each microservice owns its own database. Services communicate through events rather than directly accessing another service's database.

6. Create the ASP.NET Core Solution

Create a solution containing separate projects for the services and shared event contracts.

EventDrivenMicroservices/
|
+-- EventDrivenMicroservices.sln
|
+-- Shared.Contracts/
|   +-- OrderPlacedEvent.cs
|   +-- PaymentCompletedEvent.cs
|
+-- OrderService/
|   +-- Controllers/
|   +-- Services/
|   +-- Program.cs
|
+-- PaymentService/
|   +-- Consumers/
|   +-- Program.cs
|
+-- InventoryService/
|   +-- Consumers/
|   +-- Program.cs
|
+-- NotificationService/
|   +-- Consumers/
|   +-- Program.cs

Create the solution and projects:

dotnet new sln -n EventDrivenMicroservices
dotnet new classlib -n Shared.Contracts
dotnet new webapi -n OrderService
dotnet new worker -n PaymentService
dotnet new worker -n InventoryService
dotnet new worker -n NotificationService
dotnet sln add Shared.Contracts
dotnet sln add OrderService
dotnet sln add PaymentService
dotnet sln add InventoryService
dotnet sln add NotificationService

7. Install RabbitMQ

You can run RabbitMQ locally using Docker.

docker run -d ^
 --name rabbitmq ^
 -p 5672:5672 ^
 -p 15672:15672 ^
 rabbitmq:4-management

Ports:

  • 5672: AMQP messaging port.
  • 15672: RabbitMQ Management UI.

Open the management interface:

http://localhost:15672

The default credentials for a standard local RabbitMQ container are:

Username: guest
Password: guest

The default guest account is restricted to localhost connections. Configure dedicated credentials for applications running in separate containers or on other machines.

8. Install RabbitMQ Client Library

Install the RabbitMQ .NET client in the projects that publish or consume messages.

dotnet add package RabbitMQ.Client

Use a compatible RabbitMQ.Client version and check its API documentation. The examples below use the asynchronous API style available in modern RabbitMQ .NET client releases.

9. Create Event Contracts

Events represent business facts that have already happened. Keep event contracts independent of internal database entities.

OrderPlacedEvent.cs

namespace Shared.Contracts;
public record OrderPlacedEvent(
    Guid EventId,
    Guid OrderId,
    Guid CustomerId,
    decimal TotalAmount,
    DateTime OccurredAt
);

Why use EventId?

  • Identifies a unique event.
  • Helps consumers detect duplicate messages.
  • Supports idempotent processing.
  • Helps with troubleshooting and event tracing.

10. Configure RabbitMQ Connection Settings

Store RabbitMQ configuration outside source code, using appsettings.json for local development and secure configuration providers for deployed environments.

appsettings.json

{
  "RabbitMQ": {
    "HostName": "localhost",
    "Port": 5672,
    "UserName": "appuser",
    "Password": "use-a-secret-store",
    "VirtualHost": "/"
  }
}

Do not use production passwords in source control.

11. Create a RabbitMQ Publisher

The Order Service publishes an OrderPlaced event after successfully creating an order.

RabbitMqPublisher.cs

using System.Text;
using System.Text.Json;
using RabbitMQ.Client;
public sealed class RabbitMqPublisher : IAsyncDisposable
{
    private readonly IConnection _connection;
    private readonly IChannel _channel;
    public RabbitMqPublisher(
        IConnection connection,
        IChannel channel)
    {
        _connection = connection;
        _channel = channel;
    }
    public async Task PublishAsync<T>(
        string exchange,
        string routingKey,
        T message,
        CancellationToken cancellationToken = default)
    {
        var body = Encoding.UTF8.GetBytes(
            JsonSerializer.Serialize(message));
        var properties = new BasicProperties
        {
            ContentType = "application/json",
            DeliveryMode = DeliveryModes.Persistent,
            MessageId = Guid.NewGuid().ToString(),
            Type = typeof(T).Name
        };
        await _channel.BasicPublishAsync(
            exchange,
            routingKey,
            mandatory: true,
            basicProperties: properties,
            body: body,
            cancellationToken: cancellationToken);
    }
    public async ValueTask DisposeAsync()
    {
        await _channel.DisposeAsync();
        await _connection.DisposeAsync();
    }
}

Important: This is a simplified publisher example. In a production application, use a managed connection/channel lifecycle, confirm publishing with publisher confirms, handle returned unroutable messages, and coordinate publishing with the database transaction through the Outbox Pattern.

12. Configure RabbitMQ Connection and Exchange

Register the connection and channel during application startup. A connection is generally long-lived and shared, while channels should be managed according to the client's concurrency requirements. Do not concurrently publish through one channel unless the client version and usage pattern explicitly support it.

RabbitMqSetup.cs

using RabbitMQ.Client;
public static class RabbitMqSetup
{
    public static async Task<(IConnection, IChannel)>
        CreateAsync(IConfiguration configuration)
    {
        var factory = new ConnectionFactory
        {
            HostName = configuration["RabbitMQ:HostName"]!,
            Port = int.Parse(
                configuration["RabbitMQ:Port"] ?? "5672"),
            UserName = configuration["RabbitMQ:UserName"]!,
            Password = configuration["RabbitMQ:Password"]!,
            VirtualHost =
                configuration["RabbitMQ:VirtualHost"] ?? "/"
        };
        var connection =
            await factory.CreateConnectionAsync();
        var channel =
            await connection.CreateChannelAsync();
        await channel.ExchangeDeclareAsync(
            exchange: "ecommerce.events",
            type: ExchangeType.Topic,
            durable: true,
            autoDelete: false);
        return (connection, channel);
    }
}

For a larger application, encapsulate connection and channel management in dedicated infrastructure services. Ensure channels are not shared unsafely across concurrent operations.

13. Publish an Event from Order Service

After an order is created, publish an OrderPlaced event.

OrderController.cs

using Microsoft.AspNetCore.Mvc;
using Shared.Contracts;
[ApiController]
[Route("api/orders")]
public class OrderController : ControllerBase
{
    private readonly RabbitMqPublisher _publisher;
    public OrderController(RabbitMqPublisher publisher)
    {
        _publisher = publisher;
    }
    [HttpPost]
    public async Task<IActionResult> CreateOrder(
        CancellationToken cancellationToken)
    {
        var orderId = Guid.NewGuid();
        var orderEvent = new OrderPlacedEvent(
            Guid.NewGuid(),
            orderId,
            Guid.NewGuid(),
            1500,
            DateTime.UtcNow
        );
        await _publisher.PublishAsync(
            "ecommerce.events",
            "order.placed",
            orderEvent,
            cancellationToken);
        return Accepted(new
        {
            OrderId = orderId,
            Message = "Order event published"
        });
    }
}

This example demonstrates event publishing. A real Order Service must first persist the order and should use the Outbox Pattern to prevent a database save succeeding while event publishing fails, or vice versa.

14. Configure Queues and Bindings

Each consumer needs its own queue. This allows multiple services to receive the same event independently.

RabbitMqTopology.cs

using RabbitMQ.Client;
public static class RabbitMqTopology
{
    public static async Task ConfigureAsync(
        IChannel channel)
    {
        await channel.ExchangeDeclareAsync(
            "ecommerce.events",
            ExchangeType.Topic,
            durable: true);
        await channel.QueueDeclareAsync(
            "payment.order-placed",
            durable: true,
            exclusive: false,
            autoDelete: false);
        await channel.QueueBindAsync(
            "payment.order-placed",
            "ecommerce.events",
            "order.placed");
        await channel.QueueDeclareAsync(
            "inventory.order-placed",
            durable: true,
            exclusive: false,
            autoDelete: false);
        await channel.QueueBindAsync(
            "inventory.order-placed",
            "ecommerce.events",
            "order.placed");
        await channel.QueueDeclareAsync(
            "notification.order-placed",
            durable: true,
            exclusive: false,
            autoDelete: false);
        await channel.QueueBindAsync(
            "notification.order-placed",
            "ecommerce.events",
            "order.placed");
    }
}

Now the same OrderPlaced event is routed to three independent queues.

15. Create a Payment Service Consumer

The Payment Service listens to the payment.order-placed queue.

Order Placed Event – Complete Message Flow

Order Service Creates Order RabbitMQ Exchange order.placed Payment Queue Payment Service Inventory Queue Inventory Service Notification Queue Notification Service 1. Publish event 2. Route event Each service processes independently

PaymentConsumer.cs

using System.Text.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Shared.Contracts;
public sealed class PaymentConsumer
{
    private readonly IChannel _channel;
    public PaymentConsumer(IChannel channel)
    {
        _channel = channel;
    }
    public async Task StartAsync(
        CancellationToken cancellationToken)
    {
        await _channel.BasicQosAsync(
            0,
            10,
            false,
            cancellationToken);
        var consumer =
            new AsyncEventingBasicConsumer(_channel);
        consumer.ReceivedAsync += async (_, ea) =>
        {
            try
            {
                var orderEvent =
                    JsonSerializer.Deserialize<OrderPlacedEvent>(
                        ea.Body.ToArray());
                if (orderEvent is null)
                    throw new InvalidOperationException(
                        "Invalid event payload.");
                await ProcessPaymentAsync(
                    orderEvent,
                    cancellationToken);
                await _channel.BasicAckAsync(
                    ea.DeliveryTag,
                    multiple: false,
                    cancellationToken);
            }
            catch (Exception)
            {
                // Simplified example:
                // production code should classify errors
                // and route messages to retry/DLQ handling.
                await _channel.BasicNackAsync(
                    ea.DeliveryTag,
                    multiple: false,
                    requeue: false,
                    cancellationToken);
            }
        };
        await _channel.BasicConsumeAsync(
            queue: "payment.order-placed",
            autoAck: false,
            consumer: consumer,
            cancellationToken: cancellationToken);
    }
    private Task ProcessPaymentAsync(
        OrderPlacedEvent orderEvent,
        CancellationToken cancellationToken)
    {
        Console.WriteLine(
            $"Processing payment for {orderEvent.OrderId}");
        return Task.CompletedTask;
    }
}

Important: Do not acknowledge a message before its business processing has safely completed. Also, avoid blindly rejecting every failed message without requeueing: configure retry and dead-letter handling so transient failures can be retried without creating an infinite loop.

16. What Is Message Acknowledgement?

Message acknowledgement tells RabbitMQ whether a consumer has successfully processed a message.

Message Acknowledgement – ACK and NACK

RabbitMQ Queue Consumer Processing Successful? YES NO ACK NACK / Reject

Automatic acknowledgement

autoAck = true

RabbitMQ considers the message delivered without waiting for the application to finish processing it. If the consumer fails during processing, the message may be lost.

Manual acknowledgement

autoAck = false

The consumer explicitly acknowledges the message after successful processing.

  • BasicAck: Message processed successfully.
  • BasicNack: Message negatively acknowledged; can reject one or multiple deliveries.
  • BasicReject: Rejects one delivery.

For business-critical events, manual acknowledgements are generally preferred.

17. What Happens When a Consumer Fails?

Consider the Payment Service receiving an OrderPlaced event.

RabbitMQ Payment Consumer Process Payment Payment successful? SUCCESS ACK FAILURE NACK Retry or Dead Letter Queue

With manual acknowledgement, if the consumer connection or channel closes before acknowledgement, RabbitMQ can requeue the unacknowledged delivery.

However, message delivery is not exactly once. A consumer may successfully perform a business operation and then fail before acknowledging the message. RabbitMQ may deliver it again.

18. Idempotency: Prevent Duplicate Processing

RabbitMQ consumers should be designed to handle duplicate messages safely.

Example:

  • Payment Service receives OrderPlaced.
  • It processes the payment.
  • The consumer crashes before acknowledging the message.
  • RabbitMQ redelivers the same message.

Without idempotency, the payment could be processed twice.

Store processed EventIds in a database table with a unique constraint.

ProcessedEvents table

CREATE TABLE ProcessedEvents
(
    EventId UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
    ProcessedAt DATETIME2 NOT NULL
);

Processing logic should follow this pattern:

BEGIN DATABASE TRANSACTION
1. Check whether EventId already exists.
2. If it exists, skip business processing.
3. Otherwise, perform the business operation.
4. Insert EventId into ProcessedEvents.
COMMIT DATABASE TRANSACTION
5. Acknowledge RabbitMQ message.

The business update and EventId insertion must be committed in the same local database transaction. For external payment providers, also use provider-supported idempotency keys because a local database transaction cannot make a remote payment operation atomic.

19. Dead Letter Queue (DLQ)

A Dead Letter Queue stores messages that cannot be processed normally.

Messages can be dead-lettered when:

  • A consumer rejects or negatively acknowledges a message without requeueing.
  • A message expires due to a queue or message TTL.
  • A queue exceeds its configured length limit, depending on the queue configuration and overflow behavior.

Dead Letter Queue – DLQ Architecture

Main Exchange Main Queue Consumer Rejected / Expired Dead Letter Exchange Dead Letter Queue

DLQs help developers inspect failed messages and investigate processing problems.

20. Retry Mechanism

Transient failures may happen because of network issues, temporary database unavailability, or an external API outage.

A retry mechanism allows messages to be processed again after a delay.

Recommended retry approach:

7. Retry Mechanism with Dead Letter Queue

Main Queue Consumer Success? YES ACK NO Retries left? YES Retry After Delay Dead Letter Queue

Use bounded retries and increasing delays. Avoid immediate requeue loops because they can overload consumers and RabbitMQ.

RabbitMQ supports retry designs using dead-letter exchanges and TTL queues. RabbitMQ quorum queues also provide a native delayed-retry mechanism through delivery limits and dead-letter configuration in supported versions. Choose a retry strategy based on the RabbitMQ version and operational requirements.

21. What Is the Outbox Pattern?

The Outbox Pattern solves the dual-write problem.

Consider this sequence:

1. Order Service saves order in SQL Server.
2. Order Service publishes OrderPlaced to RabbitMQ.

What happens if the database save succeeds but RabbitMQ is unavailable?

The order exists, but the event is not published. Other services never learn that the order was created.

The Outbox Pattern addresses this by saving the business data and event record in the same database transaction.

Outbox architecture

Outbox Pattern – Reliable Event Publishing

Order Service Single Database Transaction Save Order + Save Outbox Event Database Orders Table + Outbox Table Outbox Background Worker RabbitMQ

Example table:

CREATE TABLE OutboxMessages
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    EventType NVARCHAR(200) NOT NULL,
    Payload NVARCHAR(MAX) NOT NULL,
    CreatedAt DATETIME2 NOT NULL,
    ProcessedAt DATETIME2 NULL
);

Processing sequence:

  1. Begin database transaction.
  2. Insert the order.
  3. Insert the OrderPlaced event into OutboxMessages.
  4. Commit the transaction.
  5. Background worker reads pending events.
  6. Worker publishes events to RabbitMQ.
  7. Worker marks successfully published records as processed.

The Outbox Pattern guarantees that the business change and event record are saved atomically in the same database. It does not guarantee exactly-once delivery to RabbitMQ. The worker and consumers must handle duplicate publication and processing safely.

22. Eventual Consistency

In event-driven microservices, different services may update their databases at different times.

Example:

Order Service:
Order Status = Pending
Payment Service:
Payment Status = Processing
Inventory Service:
Reservation Status = Pending

After the events are processed:

Order Service:
Order Status = Confirmed
Payment Service:
Payment Status = Completed
Inventory Service:
Reservation Status = Reserved

This is called eventual consistency. The system may temporarily have different states, but they converge as events are processed successfully.

23. Saga Pattern with RabbitMQ

The Saga Pattern coordinates a business transaction across multiple microservices using a sequence of local transactions.

Example order workflow:

Saga Pattern – Choreography

Order Service RabbitMQ Inventory Service Payment Service OrderPlaced InventoryReserved PaymentCompleted Release Inventory Cancel Order Compensation if payment fails

If payment fails after inventory is reserved, the workflow may need to release the inventory.

This is called a compensating transaction.

Possible compensation:

Payment Failed
      |
      v
Release Inventory
      |
      v
Cancel Order

Saga can be implemented through choreography, where services react to events, or orchestration, where a coordinator directs the workflow.

24. Choreography vs Orchestration

Choreography Orchestration
Services react to events. A coordinator manages the workflow.
No central workflow controller. Central workflow controller.
Suitable for simpler workflows. Suitable for complex workflows.
Can become difficult to trace as workflows grow. Workflow status is easier to centralize.

25. Configure a Worker Service

Consumers should normally run as independent background services rather than being tied to an HTTP request.

A Worker Service can continuously listen for RabbitMQ messages.

Program.cs

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<PaymentWorker>();
var host = builder.Build();
await host.RunAsync();

PaymentWorker.cs

public sealed class PaymentWorker : BackgroundService
{
    private readonly ILogger<PaymentWorker> _logger;
    public PaymentWorker(
        ILogger<PaymentWorker> logger)
    {
        _logger = logger;
    }
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            "Payment worker started.");
        while (!stoppingToken.IsCancellationRequested)
        {
            // In production, establish and maintain
            // a RabbitMQ connection and consumer here.
            await Task.Delay(
                TimeSpan.FromSeconds(5),
                stoppingToken);
        }
    }
}

This is only a Worker Service lifecycle example. The actual consumer should establish its RabbitMQ connection, declare or verify topology, register an asynchronous consumer, and handle reconnection and shutdown.

26. Scaling RabbitMQ Consumers

You can run multiple instances of the same consumer to process messages concurrently.

             RabbitMQ Queue
                   |
          +--------+--------+
          |        |        |
          v        v        v
       Worker 1 Worker 2 Worker 3

RabbitMQ distributes queue deliveries among active consumers. This is useful for scaling workloads.

Important considerations:

  • Use prefetch limits to control outstanding unacknowledged deliveries.
  • Make consumers idempotent.
  • Monitor queue depth and message processing latency.
  • Ensure database connection pools can handle the workload.
  • Use multiple consumers only when the business processing can safely run concurrently.

27. Message Ordering

RabbitMQ queues generally preserve enqueue order, but end-to-end processing order is not automatically guaranteed when multiple consumers, retries, redeliveries, or concurrent processing are involved.

If strict ordering is required:

  • Use a single active consumer for the relevant queue or an appropriate single-active-consumer configuration.
  • Process messages sequentially.
  • Include aggregate or entity identifiers and sequence numbers in events.
  • Detect and handle out-of-order events.
  • Consider partitioning messages by business entity when scaling is required.

28. RabbitMQ Durability

Durability helps protect messages and topology across broker restarts.

Important settings:

  • Durable Exchange: Exchange definition survives broker restart.
  • Durable Queue: Queue definition survives broker restart.
  • Persistent Message: Message is marked for persistence.
  • Publisher Confirms: Broker confirms that it has accepted responsibility for a publication.
  • Consumer Acknowledgement: Consumer confirms successful processing.

Durable queues and persistent messages are not, by themselves, a complete end-to-end delivery guarantee. Use publisher confirms, appropriate queue types, replication where required, and consumer idempotency.

29. RabbitMQ Queue Types

Queue Type Description Typical Use
Classic Queue Traditional queue type. General messaging workloads.
Quorum Queue Replicated queue based on a consensus algorithm. Important messages requiring replicated queue data.
Stream Append-only persistent log with replay capabilities. Large-scale event streaming and replay scenarios.

Choose the queue type according to delivery, replication, throughput, retention, and replay requirements.

30. Security Best Practices

  • Use dedicated RabbitMQ application accounts.
  • Apply least-privilege permissions to virtual hosts and resources.
  • Use TLS for network communication.
  • Keep credentials in a secure secret store.
  • Restrict access to the management interface.
  • Do not expose the AMQP port publicly without a clear security requirement.
  • Validate message payloads before processing.
  • Set message size limits appropriate to the application.
  • Use separate virtual hosts or clusters where stronger isolation is required.

31. Monitoring and Observability

Monitor RabbitMQ and each microservice independently.

Important RabbitMQ metrics:

  • Queue message count.
  • Unacknowledged message count.
  • Message publish rate.
  • Message delivery rate.
  • Consumer count.
  • Connection and channel count.
  • Dead-letter queue size.
  • Memory and disk usage.

Use structured logs, distributed tracing, and correlation identifiers to follow a business operation across services.

Useful tools include:

  • RabbitMQ Management UI.
  • OpenTelemetry.
  • Prometheus.
  • Grafana.
  • ASP.NET Core logging.

32. Common Mistakes to Avoid

  • Publishing events without handling database and broker failures.
  • Assuming RabbitMQ guarantees exactly-once processing.
  • Not implementing idempotent consumers.
  • Using unlimited retries.
  • Ignoring dead-letter queues.
  • Using auto acknowledgement for critical processing without understanding message-loss implications.
  • Sharing a RabbitMQ channel unsafely across concurrent operations.
  • Putting large files or large payloads directly into messages.
  • Creating tight dependencies between services through shared database access.
  • Ignoring schema evolution and event versioning.
  • Using events as if they were synchronous request-response calls.

33. Best Practices

  1. Use clear domain event names such as OrderPlaced and PaymentCompleted.
  2. Keep event contracts small and stable.
  3. Include EventId, OccurredAt, and relevant business identifiers.
  4. Use separate queues for independent consumers.
  5. Use durable topology and persistent messages where required.
  6. Use publisher confirms and handle unroutable messages.
  7. Use manual acknowledgements for reliable processing.
  8. Implement idempotency and bounded retry policies.
  9. Use dead-letter exchanges and queues.
  10. Use the Outbox Pattern for reliable event publication.
  11. Use the Inbox or processed-event pattern for duplicate detection.
  12. Monitor queue depth, processing failures, and consumer lag.
  13. Version event contracts carefully.
  14. Use Saga for multi-service business workflows that require compensation.

34. RabbitMQ vs Azure Service Bus vs Kafka

Feature RabbitMQ Azure Service Bus Kafka
Primary Model Message broker Managed message broker Distributed event streaming platform
Routing Exchanges and bindings Queues and topics/subscriptions Topics and partitions
Message Replay Not its primary model Not its primary model Core capability through retention and offsets
Typical Use Application messaging and task distribution Cloud application messaging High-volume event streaming

35. End-to-End Event Flow

Complete Event-Driven Microservices Architecture

Customer / Client ASP.NET Core API Order Service Order API + Outbox Order Database Outbox Publisher RabbitMQ Exchange Payment Service Payment Queue Inventory Service Inventory Queue Notification Service Notification Queue Each service owns its database and processes messages independently

36. Interview Questions and Answers

Q1. What is Event-Driven Architecture?

It is an architecture where services communicate by publishing and consuming events representing business occurrences.

Q2. What is RabbitMQ?

RabbitMQ is a message broker that receives messages from producers and routes them to queues for consumers.

Q3. What is an exchange?

An exchange receives messages and routes them to queues according to its exchange type and binding rules.

Q4. What is the difference between an exchange and a queue?

An exchange routes messages, whereas a queue stores messages until consumers receive them.

Q5. What is a routing key?

A routing key is a message attribute used by exchanges such as Direct and Topic exchanges to determine message routing.

Q6. What is a Fanout Exchange?

A Fanout Exchange broadcasts a message to all queues bound to it, ignoring routing keys.

Q7. What is a Topic Exchange?

A Topic Exchange routes messages using routing-key patterns containing wildcards such as * and #.

Q8. What is message acknowledgement?

It is the consumer's confirmation that a delivered message has been processed successfully.

Q9. What is a Dead Letter Queue?

A DLQ stores messages that have been rejected, expired, or otherwise dead-lettered according to queue configuration.

Q10. What is the Outbox Pattern?

It stores business data and an event record in the same database transaction. A background publisher later sends the event to the broker.

Q11. Does RabbitMQ guarantee exactly-once delivery?

No. Duplicate delivery can occur. Consumers should implement idempotency and deduplication.

Q12. What is idempotency?

Idempotency means processing the same event more than once does not produce duplicate business effects.

Q13. What is eventual consistency?

It means different services may temporarily have different data states but eventually converge as events are processed.

Q14. What is the Saga Pattern?

Saga coordinates a distributed business workflow through local transactions and compensating actions.

Q15. What is the difference between choreography and orchestration?

In choreography, services react to events. In orchestration, a central coordinator manages the workflow.

Q16. What is a quorum queue?

A quorum queue is a replicated RabbitMQ queue designed to provide stronger data safety through a consensus-based approach.

Q17. How do you scale RabbitMQ consumers?

Run multiple consumer instances, configure prefetch appropriately, and ensure processing is safe under concurrency.

Q18. How do you prevent duplicate payment processing?

Use a unique event identifier, a durable idempotency record, and the payment provider's idempotency mechanism where supported.

Q19. What is publisher confirmation?

Publisher confirms allow the broker to inform a producer that it has accepted responsibility for a published message.

Q20. When should you use RabbitMQ?

Use RabbitMQ when applications need reliable message routing, asynchronous task processing, workload distribution, and event-based communication.

37. Final Architecture Summary

A production-oriented event-driven microservices system commonly includes:

  • ASP.NET Core Web APIs for synchronous client requests.
  • RabbitMQ for asynchronous message routing.
  • Worker Services for background message consumption.
  • Independent databases owned by individual microservices.
  • Outbox Pattern for reliable event publication.
  • Idempotent consumers for duplicate protection.
  • Retry and Dead Letter Queue strategies for failures.
  • Saga for multi-service business workflows.
  • OpenTelemetry and monitoring for observability.

Key principle: Microservices should own their business data and communicate through well-defined contracts. RabbitMQ provides asynchronous message delivery and routing, while patterns such as Outbox, Inbox, idempotency, and Saga help build reliable distributed workflows.

🔙
Distributed Transactions: Saga Pattern and Outbox Pattern :👈 👉:REST-vs-SOAP