Creating an order often requires several actions at once: persist the order, notify a payment or shipping service, and trigger secondary work such as email delivery. The first two actions already expose a serious reliability problem. If the database write succeeds but publishing fails, downstream services never learn about the order. If the message is published and the application crashes before the database transaction commits, consumers may process an event for data that does not exist.
This is the dual-write problem. The Transactional Outbox pattern solves it by storing the business change and the event to be published in the same local database transaction. A separate, replayable worker then delivers the stored event to the message broker.
Why two independent writes are unsafe
A typical implementation looks simple:
- Insert the order into the database.
- Publish an
OrderCreatedmessage.
These operations normally do not share one transaction boundary. The process can terminate after the first step, the network can fail, or the broker can be temporarily unavailable. The result is an inconsistent view of the system: the source database contains the order, while other services do not know it exists.
Reversing the order does not solve the issue. If the message is published first and the database write later fails, consumers process a phantom event. Distributed transactions may be available in some environments, but they introduce operational complexity, tighter coupling, and additional latency. For many services, a local transaction plus a durable outbox is a simpler boundary.
How the Transactional Outbox works
The application writes the business record and its outgoing event together:
- Begin the business transaction.
- Insert the order into
Orders. - Insert an event into
OutboxMessages. - Commit the transaction.
- Let a background worker find unpublished outbox rows.
- Publish each event and mark it as published.
If the transaction commits, both the order and the event are durable. If the worker or broker is unavailable, the event remains in the outbox until the delivery attempt succeeds. Microsoft architecture guidance describes the same principle: persist the state change and event atomically, then use a separate process to publish the event.
SQL Server table design
The following table is a practical starting point for a small or medium-sized .NET service:
CREATE TABLE dbo.OutboxMessages
(
Id UNIQUEIDENTIFIER NOT NULL
CONSTRAINT PK_OutboxMessages PRIMARY KEY,
AggregateId UNIQUEIDENTIFIER NOT NULL,
MessageType NVARCHAR(200) NOT NULL,
Payload NVARCHAR(MAX) NOT NULL,
OccurredAtUtc DATETIME2(3) NOT NULL,
PublishedAtUtc DATETIME2(3) NULL,
AttemptCount INT NOT NULL CONSTRAINT DF_Outbox_Attempts DEFAULT 0,
NextAttemptAtUtc DATETIME2(3) NOT NULL,
LockedUntilUtc DATETIME2(3) NULL,
LockToken UNIQUEIDENTIFIER NULL,
LastError NVARCHAR(2000) NULL
);
CREATE INDEX IX_Outbox_Ready
ON dbo.OutboxMessages (PublishedAtUtc, NextAttemptAtUtc, LockedUntilUtc)
INCLUDE (AggregateId, MessageType, OccurredAtUtc);Storing the event payload as JSON preserves the data as it existed when the business operation occurred. Rebuilding the event later by querying the current order row can produce a different result after subsequent updates.
LockToken and LockedUntilUtc implement a time-limited lease. If a worker crashes after claiming a row, another worker can safely retry it after the lease expires. This is preferable to a permanent processing flag that can leave messages stuck forever.
Writing the state and event in one transaction
When the provider supports transactions, EF Core applies the changes in a single SaveChanges call transactionally. Adding the order and the outbox entry through the same context is therefore sufficient for many applications:
var order = new Order
{
Id = orderId,
CustomerId = command.CustomerId,
Total = command.Total,
Status = "Created"
};
var message = new OutboxMessage
{
Id = Guid.NewGuid(),
AggregateId = order.Id,
MessageType = "OrderCreated.v1",
Payload = JsonSerializer.Serialize(new
{
OrderId = order.Id,
order.CustomerId,
order.Total
}),
OccurredAtUtc = DateTime.UtcNow,
NextAttemptAtUtc = DateTime.UtcNow
};
db.Orders.Add(order);
db.OutboxMessages.Add(message);
await db.SaveChangesAsync(cancellationToken);If saving fails, both the order and the event are rolled back. When explicit transaction control is needed, use BeginTransactionAsync, but do not keep the transaction open while making network calls. Publishing to the broker must happen after the database transaction has committed.
Claiming rows safely with multiple workers
Multiple worker instances must not process the same row simultaneously. SQL Server’s UPDLOCK and READPAST hints can be used to claim ready rows in a short transaction. READPAST skips rows locked by another worker instead of waiting for them, which is useful for queue-like workloads.
DECLARE @now DATETIME2(3) = SYSUTCDATETIME();
DECLARE @token UNIQUEIDENTIFIER = NEWID();
;WITH next_messages AS
(
SELECT TOP (50) *
FROM dbo.OutboxMessages WITH (UPDLOCK, READPAST, ROWLOCK)
WHERE PublishedAtUtc IS NULL
AND NextAttemptAtUtc <= @now
AND (LockedUntilUtc IS NULL OR LockedUntilUtc < @now)
ORDER BY OccurredAtUtc, Id
)
UPDATE next_messages
SET LockedUntilUtc = DATEADD(SECOND, 60, @now),
LockToken = @token,
AttemptCount = AttemptCount + 1
OUTPUT inserted.*;Commit this claim transaction immediately. The worker should then publish the messages outside the database transaction. This prevents a slow or unavailable broker from holding SQL Server locks for an extended period.
Publishing, leases, and retry policy
The worker should handle three outcomes:
- Successful publish: Set
PublishedAtUtc, but only when the storedLockTokenstill matches. - Transient failure: Move
NextAttemptAtUtcforward and store the error. - Worker crash: Allow the lease to expire so another worker can claim the row.
A retry schedule such as 5, 15, 45, and 120 seconds is easy to reason about. Add jitter so multiple workers do not retry at exactly the same moment. Avoid unbounded retries: permanent serialization, authorization, or schema errors need an operational path rather than an endless hot loop.
The publisher can still send the same event twice. For example, it may publish successfully and crash before updating PublishedAtUtc. The next worker will send the event again. This means the design provides at-least-once delivery, not exactly-once processing. Consumers must be idempotent.
Making consumers duplicate-safe
Every event should have a stable identifier. A consumer can record processed message IDs in its own database:
CREATE TABLE dbo.ProcessedMessages
(
ConsumerName NVARCHAR(100) NOT NULL,
MessageId UNIQUEIDENTIFIER NOT NULL,
ProcessedAtUtc DATETIME2(3) NOT NULL,
CONSTRAINT PK_ProcessedMessages
PRIMARY KEY (ConsumerName, MessageId)
);If the consumer inserts into this table in the same transaction as its business update, a duplicate delivery can be rejected safely. For external side effects such as sending email or charging a payment method, use the provider’s idempotency mechanism or maintain an equivalent request record before performing the side effect.
Ordering and event contract evolution
The outbox does not automatically guarantee global event ordering. If order-related events must be ordered, include an aggregate identifier and sequence number. For example, each order can have a monotonically increasing version. A consumer that receives version 5 before version 4 can delay processing, detect a gap, or request a resynchronization.
Event contracts should evolve compatibly. Versioned names such as OrderCreated.v1 and OrderCreated.v2 let old consumers continue working while new consumers adopt additional fields. Adding optional fields is usually safer than removing or changing the meaning of existing fields.
Operational metrics that matter
A reliable outbox is more than a background loop. Monitor at least:
- Number of ready and unpublished rows
- Age of the oldest unpublished event
- Failed delivery attempts
- Publishing latency:
PublishedAtUtc - OccurredAtUtc - Rows reclaimed after lease expiration
- Broker publish failure rate
Do not silently delete a message after a fixed number of attempts. Move malformed payloads, incompatible schemas, and permanent authorization failures into a reviewable dead-letter state. Keep the original payload and error so the event can be repaired or replayed.
When the pattern is not appropriate
Adding an outbox to every table can create needless complexity. A local operation with no external notification requirement does not need a relay worker or additional indexes. At very high event volumes, database growth, cleanup, partitioning, and retention must be compared with the capabilities of a dedicated messaging platform.
When a committed business change must reliably reach another system, however, the Transactional Outbox is a strong default. It provides atomic local persistence, durable retries, an auditable event record, and a clear failure boundary without requiring a distributed transaction.
Sources
- https://learn.microsoft.com/en-us/azure/architecture/patterns/transactional-outbox
- https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html
- https://learn.microsoft.com/en-us/ef/core/saving/transactions
- https://learn.microsoft.com/en-gb/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://www.tugrulbostan.com/
0 Comments