ASP.NET Core Interview Question #242

What is the transactional outbox pattern and when would you use it?

Senior ASP.NET Core Real-World Scenarios Senior Advanced

Quick Interview Answer

The transactional outbox pattern addresses the problem of updating a database and publishing a message as one logical business operation when there is no distributed transaction across both systems.

Detailed Explanation

The transactional outbox pattern addresses the problem of updating a database and publishing a message as one logical business operation when there is no distributed transaction across both systems.

The application writes the business change and an outbox record in the same database transaction. A background publisher later reads committed outbox records and sends them to the message broker, then records successful publication.

Consumers should still tolerate duplicate messages because failures can occur after publication but before the outbox row is marked as processed.

Code Example

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

order.MarkPaid();
db.OutboxMessages.Add(new OutboxMessage
{
    Type = "OrderPaid",
    Payload = Serialize(order.Id)
});

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