Skip to content
LATEST

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

Upgradix
Upgradix Code. Learn. Ship.

Transactional Outbox Pattern with EF Core & RabbitMQ

The Transactional Outbox Pattern saves your business data and outgoing event in the same SQL database transaction. A background worker then reads that outbox table and publishes the event to RabbitMQ, preventing lost messages if the broker or app crashes.

Transactional Outbox Pattern with EF Core & RabbitMQ

Quick Answer: The Transactional Outbox Pattern saves your business data and outgoing event in the same SQL database transaction. A background worker then reads that outbox table and publishes the event to RabbitMQ, preventing lost messages if the broker or app crashes.

Imagine Meena runs a UPI payment app in Hyderabad. At 11:00 AM, Karthik sends Rs. 2,500 to a local merchant under transaction TXN-9081.

Meena's Payment API saves Karthik's transfer in SQL Server, then publishes a PaymentCompleted event to RabbitMQ so the Receipt Service can notify Karthik.

What happens if RabbitMQ blinks offline for two seconds right after SQL Server commits?

1. Why Do We Need the Transactional Outbox Pattern?

The problem without an outbox (The Dual-Write Problem)

Dual-Write Problem = writing to two separate systems (a database and a message broker) without a shared transaction.

In a naive setup, the Payment API calls EF Core's SaveChangesAsync() and then calls RabbitMQ's BasicPublishAsync().

Example 1: Unsafe dual-write in ASP.NET Core

This code looks clean, but it silently loses events during network blips.

_db.Payments.Add(payment);
await _db.SaveChangesAsync();             // 1. Commits TXN-9081 in SQL Server

// What if the pod crashes or RabbitMQ drops right here?
await _rabbit.BasicPublishAsync(          // 2. Fails! Event is lost forever
    "payments.exchange", "payment.done", body);

What happens during a crash

[SQL Server] TXN-9081 saved. Rs. 2,500 deducted from Karthik.
[RabbitMQ]   BrokerUnreachableException: Connection refused!
[Result]     Karthik lost Rs. 2,500, but Receipt & Merchant services never heard about it.

This setup works on a quiet dev laptop. However, it breaks in production.

  1. SQL Server and RabbitMQ cannot share a single atomic transaction.
  2. If RabbitMQ is down, the database is updated but the event disappears forever.
  3. If you publish to RabbitMQ first and SQL fails, downstream services process a fake payment.

We need a way to make the database update and the RabbitMQ event succeed or fail together.

The solution: Transactional Outbox Pattern

Outbox Table = a regular SQL table in the same database that temporarily holds outgoing RabbitMQ messages.

Outbox Relay = a .NET BackgroundService that polls pending outbox rows, publishes them to RabbitMQ, and marks them as processed.

Because both Payments and OutboxMessages live in the same SQL Server database, EF Core commits them in one atomic transaction. Either both succeed, or both roll back.

Live Flow: Atomic SQL Outbox Commit & Background Relay

Watch Karthik's payment commit atomically with its outbox row, then get safely relayed to RabbitMQ.

Karthik (Hyderabad)
Sends Rs. 2,500 (TXN-9081)
Payment API (.NET)
EF Core DbContext
Single SaveChangesAsync()
Atomic SQL Transaction (All or Nothing)
Payments Table
INSERT TXN-9081 · Rs. 2,500
OutboxMessages Table
Event: PaymentCompleted Waiting...
Polls Pending Rows
Outbox Relay (BackgroundService)
Publishes & marks ProcessedUtc
BasicPublishAsync (Guaranteed)
RabbitMQ Broker
Delivers to Receipt & Merchant Services
User / Client Service / Broker SQL Atomic Transaction Active Step

If RabbitMQ goes down, the OutboxMessages row stays Pending. The relay retries automatically until RabbitMQ recovers.

2. Implementing the Outbox Pattern with EF Core & C#

First, save both the Payment entity and the OutboxMessage entity in a single EF Core SaveChangesAsync() call.

Example 2: Atomic save in Payment API with EF Core

EF Core wraps all pending changes in one database transaction automatically.

var payment = new Payment("TXN-9081", "Karthik", 2500);
var outbox = new OutboxMessage
{
    Id = Guid.NewGuid(),
    Type = "PaymentCompleted",
    Payload = JsonSerializer.Serialize(payment),
    CreatedUtc = DateTime.UtcNow
};

_db.Payments.Add(payment);
_db.OutboxMessages.Add(outbox);
await _db.SaveChangesAsync(); // Single atomic SQL transaction

Next, run a BackgroundService that polls unprocessed rows, publishes them to RabbitMQ, and stamps ProcessedUtc.

Example 3: Outbox Relay worker loop in .NET

Runs every second in the background and retries safely if RabbitMQ is unreachable.

var pending = await db.OutboxMessages
    .Where(m => m.ProcessedUtc == null)
    .OrderBy(m => m.CreatedUtc)
    .Take(20)
    .ToListAsync(ct);

foreach (var msg in pending)
{
    var body = Encoding.UTF8.GetBytes(msg.Payload);
    await channel.BasicPublishAsync("payments.exchange", "payment.done", body);
    msg.ProcessedUtc = DateTime.UtcNow;
}
await db.SaveChangesAsync(ct);

Expected output

[PaymentAPI]  Committed TXN-9081 + OutboxMessage in 14 ms
[OutboxRelay] Published PaymentCompleted for TXN-9081 -> Marked ProcessedUtc

3. Direct Dual-Write vs. Transactional Outbox

Direct dual-write vs. Transactional Outbox in Meena's UPI app
Without Outbox (Dual-Write) With Transactional Outbox
Events are lost if RabbitMQ is down. Events wait safely in SQL until RabbitMQ is back.
API response waits for RabbitMQ network I/O. API replies fast right after SQL commit.
Database and broker drift out of sync. Guaranteed at-least-once delivery to RabbitMQ.

Design tip: The Outbox Pattern gives you at-least-once delivery. If the relay crashes right after publishing to RabbitMQ but before saving ProcessedUtc, it will publish the message again. Always make your consumers idempotent using MessageId.

4. Common Mistakes to Avoid

1. Calling SaveChangesAsync() twice

If you save the Payment first and the OutboxMessage in a second SaveChangesAsync(), you recreated the dual-write bug.

Better approach: Add both entities to the same DbContext and call SaveChangesAsync() once.

2. Letting the OutboxMessages table grow forever

Keeping millions of processed rows slows down polling queries on your primary database.

Better approach: Add a filtered index on ProcessedUtc IS NULL and run a nightly job to delete rows older than 7 days.

5. Interview Questions & Practice

Question 1: Why can't we just use a distributed transaction (2PC) between SQL Server and RabbitMQ?

What the interviewer expects: Understanding of AMQP limitations and 2PC performance bottlenecks.

Strong answer: "RabbitMQ does not support XA/2PC distributed transactions, and even when systems do, 2PC holds locks across networks and kills throughput. In Meena's UPI app, the Transactional Outbox gives us atomic safety using only a fast local SQL transaction."

Practice: Railway ticket booking

A passenger books a Bengaluru-to-Chennai seat. Design the OutboxMessages table columns needed to guarantee the Seat Confirmation Email event is never lost.

Expected result: Columns for Id (GUID), Type, Payload (JSON), CreatedUtc, ProcessedUtc, and Error.

6. Next Steps

  • Previous Article: Hosting Background Consumers with BackgroundService in .NET
  • Next Article: Leveling Up with MassTransit 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.