Transactional Outbox Pattern
What Problem Does It Solve?
The Transactional Outbox pattern makes a state change and its resulting integration event reliable without using a distributed transaction across a database and a message broker.
Consider an Ordering service. It creates an order in its database and then publishes OrderCreated to Azure Service Bus so that inventory, invoicing, and notifications can react. The seemingly natural sequence is a dual write:
save order to database
publish OrderCreated to message broker
That sequence has an unavoidable failure window. If the database commit succeeds but the process crashes, the network fails, or Service Bus is unavailable before the send completes, the order exists but its event is lost. Reversing the order creates the opposite fault: consumers see an event for an order that never committed.
Neither try/catch nor a retry around the send closes this gap. The database and the broker are independent resource managers. A distributed transaction can sometimes coordinate them, but it introduces coupling and availability constraints that are usually a poor fit for cloud-native, independently deployed services.
The Transactional Outbox pattern replaces the dual write with:
- One local transaction that saves business state and an outbox record.
- A separate relay that reads committed outbox records, publishes them, and retries safely.
- Idempotent consumers, because a relay can publish a message more than once.
Microsoft's Azure Architecture Center guidance describes the same core approach: persist the business object and its event atomically, then relay the event asynchronously to the broker.
The Core Idea
An outbox is durable, service-owned storage for messages that must leave a service. In a relational system it is normally an OutboxMessages table in the same database as the aggregate being changed. In Azure Cosmos DB it can be an event document in the same container and logical partition as the business document.
The request commits only after both the business state and its outbox message are written. Therefore:
- If the transaction rolls back, neither the state change nor the event exists.
- If it commits, both exist durably.
- If the broker is unavailable, the relay can resume later from the durable outbox.
This provides at-least-once publication and eventual consistency, not exactly-once processing. A relay can successfully send a message but crash before it records that the message was sent. On restart, it sends again. That is why an outbox always needs idempotent consumers.
flowchart LR
Client[Client] --> API[Ordering API]
API --> TX{Local transaction}
TX --> Order[(Orders)]
TX --> Outbox[(OutboxMessages)]
TX --> Commit[Commit]
Commit --> Relay[Outbox relay]
Relay --> SB[Azure Service Bus topic]
SB --> Inventory[Inventory consumer]
SB --> Billing[Billing consumer]
SB --> Notifications[Notification consumer]
Failure Mode: Naive Dual Write
sequenceDiagram
participant C as Client
participant O as Ordering service
participant D as Orders database
participant B as Azure Service Bus
C->>O: POST /orders
O->>D: Commit new order
D-->>O: Success
Note over O,B: Process crashes or broker is unavailable
O-xB: Publish OrderCreated
O-->>C: 201 Created
Note over D,B: Order exists, downstream services never learn about it
The application can report success because the order was committed, yet inventory never reserves stock and the customer never receives a notification. A later reconciliation job may detect the discrepancy, but correctness now depends on a secondary repair process rather than the normal path.
Reliable Flow with an Outbox
sequenceDiagram
participant C as Client
participant O as Ordering service
participant D as Orders + Outbox database
participant R as Outbox relay
participant B as Azure Service Bus
participant I as Inventory consumer
C->>O: POST /orders
O->>D: Begin transaction
O->>D: Insert Order
O->>D: Insert OrderCreated outbox record
O->>D: Commit
D-->>O: Success
O-->>C: 201 Created
R->>D: Read unprocessed outbox record
R->>B: Publish message (MessageId = event ID)
B->>I: Deliver OrderCreated
R->>D: Mark published or checkpoint progress
If the relay fails at any point, the committed record remains available. A publishing retry may create duplicates, so the receiving service records or otherwise recognizes the event ID before executing an externally visible side effect.
Outbox Record Design
The outbox record is an integration contract, not a serialized database row. It should include enough information for a relay and consumers to handle the event without querying the source service synchronously.
| Field | Purpose |
|---|---|
Id |
Globally unique event identifier; map this to Service Bus MessageId. |
OccurredUtc |
When the business fact occurred; useful for audit and lag measurement. |
Type |
Stable event name, such as orders.created.v1. |
AggregateId |
Business identifier used for correlation and per-aggregate ordering. |
Payload |
Versioned event data, generally JSON. Avoid secrets and unnecessary personal data. |
CorrelationId / TraceParent |
Connects logs and traces across the distributed operation. |
Sequence |
Optional monotonically increasing sequence within an aggregate when ordering matters. |
PublishedUtc / status |
Relay bookkeeping for polling implementations. |
AttemptCount / error metadata |
Operational visibility and poison-message handling. |
Example schema for Azure SQL or SQL Server:
CREATE TABLE dbo.OutboxMessages
(
Id uniqueidentifier NOT NULL PRIMARY KEY,
OccurredUtc datetime2 NOT NULL,
Type nvarchar(200) NOT NULL,
AggregateId nvarchar(128) NOT NULL,
Payload nvarchar(max) NOT NULL,
CorrelationId nvarchar(128) NULL,
PublishedUtc datetime2 NULL,
AttemptCount int NOT NULL DEFAULT 0,
LastError nvarchar(2000) NULL
);
CREATE INDEX IX_OutboxMessages_Unpublished
ON dbo.OutboxMessages (PublishedUtc, OccurredUtc)
WHERE PublishedUtc IS NULL;
The index supports the relay's hot query. Keep the primary transactional database authoritative; the outbox is an append-only delivery log that can be archived or deleted only after an agreed retention window.
.NET and EF Core Implementation
In an ASP.NET Core application backed by a relational database, create the domain event and the outbox entity during the same DbContext unit of work. EF Core wraps a single SaveChangesAsync in a transaction when the provider supports transactions, but make transaction boundaries explicit if the application uses multiple saves or other database work.
public sealed class OrderService(OrderingDbContext dbContext)
{
public async Task<Guid> PlaceOrderAsync(
PlaceOrder command,
CancellationToken cancellationToken)
{
var order = Order.Create(command.CustomerId, command.Lines);
var integrationEvent = new OutboxMessage(
id: Guid.NewGuid(),
occurredUtc: DateTimeOffset.UtcNow,
type: "orders.created.v1",
aggregateId: order.Id.ToString(),
payload: JsonSerializer.Serialize(new OrderCreatedV1(order.Id, order.CustomerId)));
await using var transaction = await dbContext.Database
.BeginTransactionAsync(cancellationToken);
dbContext.Orders.Add(order);
dbContext.OutboxMessages.Add(integrationEvent);
await dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return order.Id;
}
}
public sealed class OutboxMessage
{
public OutboxMessage(Guid id, DateTimeOffset occurredUtc, string type,
string aggregateId, string payload)
{
Id = id;
OccurredUtc = occurredUtc;
Type = type;
AggregateId = aggregateId;
Payload = payload;
}
public Guid Id { get; }
public DateTimeOffset OccurredUtc { get; }
public string Type { get; } = null!;
public string AggregateId { get; } = null!;
public string Payload { get; } = null!;
public DateTimeOffset? PublishedUtc { get; set; }
}
The important property is not the class shape; it is that the Order and OutboxMessage inserts participate in the same database transaction. Do not publish directly from a domain-event handler that runs before the transaction commits: consumers could observe an event for a transaction that later rolls back.
Relay options
| Relay approach | Best fit | Trade-off |
|---|---|---|
BackgroundService polling the outbox |
Simple relational application; predictable low-to-medium volume. | Requires lock/lease design, polling interval, and cleanup. |
| Azure Function timer trigger | Cloud-hosted polling relay with a simple deployment model. | Still polling; prevent concurrent relays from processing the same row. |
| Change Data Capture (CDC) / transaction-log tailing | High-volume relational systems where polling is undesirable. | More operational infrastructure and provider-specific expertise. |
| Azure Cosmos DB change feed | Cosmos DB source-of-truth data; event documents share the transactional partition. | Transactions are constrained to one logical partition/container. |
| A messaging framework such as MassTransit or NServiceBus | Established messaging convention and operational requirements. | Adds a framework and its conventions; evaluate its storage and transport support. |
For a polling relay, claim a short batch atomically so multiple instances cannot publish the same row concurrently. A lease/lock expiration is safer than a permanent Processing status because a host can die after claiming work. Duplicate delivery is still possible after the broker accepts a message, so locks improve efficiency—not the correctness model.
Azure Service Bus Integration
Azure Service Bus is a strong fit when downstream processing needs durable queues or publish-subscribe topics, dead-lettering, sessions, and controlled delivery. The relay should use the outbox event ID as ServiceBusMessage.MessageId and include event type, correlation ID, and aggregate ID as application properties.
var message = new ServiceBusMessage(BinaryData.FromString(outboxMessage.Payload))
{
MessageId = outboxMessage.Id.ToString(),
Subject = outboxMessage.Type,
ContentType = "application/json",
CorrelationId = correlationId,
SessionId = outboxMessage.AggregateId
};
await sender.SendMessageAsync(message, cancellationToken);
Use SessionId only when per-aggregate ordered processing is a real requirement and the destination entity has sessions enabled. It provides ordering within a session, not global ordering. Configure Service Bus duplicate detection as a helpful broker-side optimization where its time window and throughput implications fit, but retain consumer idempotency as the definitive protection. Azure Service Bus reliability guidance
The relay should authenticate with a managed identity and receive only the required data-plane role, such as Azure Service Bus Data Sender. Consumers should use a different identity with receiver permissions. Do not store shared access keys in source code or event payloads.
Azure Cosmos DB Variant
With Azure Cosmos DB, write the business document and an event document in a TransactionalBatch. Both documents must be in the same container and logical partition. That scope is fundamental: Cosmos DB does not provide a cross-container or cross-partition transactional outbox batch.
var batch = container.CreateTransactionalBatch(new PartitionKey(order.Id.ToString()))
.CreateItem(order)
.CreateItem(new OutboxEvent
{
Id = Guid.NewGuid().ToString(),
PartitionKey = order.Id.ToString(),
DocumentType = "outbox-event",
EventType = "orders.created.v1",
Payload = new OrderCreatedV1(order.Id, order.CustomerId)
});
var response = await batch.ExecuteAsync(cancellationToken);
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException("Order and outbox event were not committed.");
}
Use the change feed as the relay input. It is durable and preserves change order within a logical partition. An Azure Function with a Cosmos DB trigger or a change-feed processor filters event documents and sends them to Service Bus. A lease container checkpoints progress, so a separate Published flag is often unnecessary. Apply a time-to-live (TTL) policy to event documents only after verifying that the retention period exceeds the longest credible outage and replay window. Cosmos DB outbox implementation guidance
flowchart LR
API[Order API] --> Batch[Cosmos DB TransactionalBatch]
Batch --> Order[Order document]
Batch --> Event[Outbox event document]
Event --> Feed[Cosmos DB change feed]
Feed --> Relay[Azure Function or change-feed processor]
Relay --> Topic[Azure Service Bus topic]
Topic --> Consumers[Idempotent consumers]
Idempotent Consumers Are Mandatory
An outbox makes it safe to retry publishing, but it cannot know whether a send succeeded when the sender fails immediately after the broker accepted the message. Consumers must therefore tolerate duplicates.
Typical approaches:
- Store each successfully handled
EventIdin aProcessedMessagestable in the same transaction as the consumer's business update. A duplicate insert becomes a no-op. - Use a unique business constraint that makes the desired side effect naturally idempotent, such as one reservation per
(OrderId, SKU). - Make calls to external providers idempotent by passing the event ID as the provider's idempotency key when supported.
- Include a per-aggregate sequence number when consumers must detect out-of-order messages; define whether to buffer, retry, or compensate when a gap occurs.
sequenceDiagram
participant B as Service Bus
participant C as Consumer
participant D as Consumer database
B->>C: OrderCreated (event ID E123)
C->>D: Begin transaction
C->>D: Insert ProcessedMessage(E123)
C->>D: Reserve inventory
C->>D: Commit
Note over B,C: Duplicate delivery later
B->>C: OrderCreated (event ID E123)
C->>D: Insert ProcessedMessage(E123) conflicts
C-->>B: Complete without repeating side effect
Do not promise exactly-once end-to-end delivery unless the whole boundary—including the final external side effect—can prove it. In most real systems, “at least once plus idempotency” is the stronger and more honest design.
Ordering, Versioning, and Operations
Ordering
The outbox preserves commit order only to the extent that the storage and relay design does. If OrderCreated and OrderAddressChanged must arrive in order for an individual order, assign an aggregate sequence number, partition/route by aggregate ID, and use Service Bus sessions where appropriate. Do not attempt global ordering across independent aggregates; it destroys parallelism and usually has no business meaning.
Event contracts
Events are public contracts for other services. Use names such as orders.created.v1, publish immutable facts rather than commands disguised as events, and evolve payloads compatibly. Prefer adding optional fields over breaking changes. Consumers should ignore unknown fields and handle older supported versions during rollout.
Monitoring and recovery
Monitor these signals with Azure Monitor and Application Insights:
- Age of the oldest unpublished outbox record and the count of pending records.
- Relay publish failures, retry attempts, and throughput.
- Service Bus active, scheduled, and dead-letter message counts.
- End-to-end trace latency from state commit to consumer completion.
- Consumer deduplication rate; a sudden rise can reveal relay instability.
Provide an operator-safe replay procedure. Replaying should send the same event ID where consumers are idempotent, should be scoped by time or aggregate, and should leave an audit trail. Never delete outbox data merely because it is old without first confirming that downstream consumers and incident-response retention no longer need it.
Advantages and Disadvantages
Advantages
- Eliminates the lost-event gap caused by a database-plus-broker dual write.
- Uses a local database transaction instead of distributed transactions across services.
- Creates a durable audit trail and controlled replay point for integration events.
- Lets the user-facing request succeed independently of temporary broker or consumer outages.
- Works with Azure Service Bus, Event Grid-facing relays where appropriate, and Azure Cosmos DB change feed.
Disadvantages and trade-offs
- Downstream systems are eventually consistent; consumers do not react before the transaction commits and relay runs.
- Duplicate messages are expected, so consumer idempotency is non-negotiable.
- Ordering, cleanup, schema evolution, locking, and replay add operational design work.
- Outbox tables or event documents grow and require retention, indexing, and capacity planning.
- It does not make a multi-service business workflow atomic; use compensating actions or a durable orchestration when later steps fail.
Transactional Outbox Compared with Alternatives
| Approach | What it solves | Why it is different |
|---|---|---|
| Transactional Outbox | Reliable local state change plus eventual event publication. | Uses one local transaction and a retryable relay. |
| Direct publish after commit | Fast to implement. | Still loses events in the post-commit failure window. |
| Distributed transaction / two-phase commit | Atomic coordination across resource managers. | Often reduces availability and portability; uncommon across modern cloud services. |
| Transactional inbox / idempotent consumer | Safe duplicate consumption. | Complements an outbox; it protects the receiving side rather than publishing. |
| Saga / compensating transaction | Coordinates a multi-step distributed business workflow. | An outbox reliably emits saga commands/events; it does not replace compensation. |
| Change Data Capture alone | Streams database changes. | Can act as a relay mechanism, but event intent, contract, and consumer semantics still require design. |
Interview-Ready Summary
The Transactional Outbox pattern solves the dual-write problem. When a service updates its database and must notify other services, it writes both the business change and an event record in the same local transaction. A separate relay publishes committed records to a broker such as Azure Service Bus.
The guarantee is not exactly-once delivery. It is durable, at-least-once publication with eventual consistency. The relay may send a message twice, so consumers must be idempotent, normally using the event ID inside their own transaction. In Azure, a relational implementation commonly uses an EF Core outbox table plus a worker; a Cosmos DB implementation uses a same-partition TransactionalBatch and the change feed.