Entity Framework Core Interview Question #123

What is the outbox pattern and how does it relate to EF Core transactions?

Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate

Quick Interview Answer

The outbox pattern stores a business data change and a message-to-be-published in the same database transaction. After commit, a background process reads the outbox and publishes the message to the external broker or service.

Detailed Explanation

The outbox pattern stores a business data change and a message-to-be-published in the same database transaction. After commit, a background process reads the outbox and publishes the message to the external broker or service.

This avoids the dangerous gap where the database commit succeeds but publishing the corresponding message fails before it is recorded anywhere durable.

Consumers and publishers still need idempotency because messages can be delivered or processed more than once.

Code Example

await using var tx =
    await db.Database.BeginTransactionAsync();

db.Orders.Add(order);
db.OutboxMessages.Add(new OutboxMessage
{
    Type = "OrderCreated",
    Payload = json,
    CreatedAtUtc = DateTime.UtcNow
});

await db.SaveChangesAsync();
await tx.CommitAsync();