Transactional Outbox
Write the business change and the event that announces it in one database transaction, then publish the event from the outbox table.
On this page
Problem
A service often needs to change its database and tell the rest of the system about it: save the order and publish OrderPlaced. The database and the message broker are separate systems with no shared transaction, so this is a dual write. If the service commits and then crashes before publishing, the event is lost and downstream services never learn about the order. If it publishes first and the commit fails, consumers react to an order that does not exist.
Distributed transactions (two-phase commit) across the database and broker are rarely available in modern brokers and, where they exist, are slow and couple both systems' availability. Retrying the publish in application code does not help if the process dies between the two steps.
Context
Use this pattern when:
- A service owns a relational or document database that supports local transactions.
- State changes must be announced to other services through a broker such as Kafka, RabbitMQ or a cloud queue.
- Losing an event, or announcing a change that was rolled back, causes real inconsistency.
- Consumers can tolerate a short delay and duplicate deliveries.
Solution
Add an outbox table to the service's own database. In the same local transaction that changes business data, insert a row describing the event (id, type, payload, timestamp). Either both commit or neither does, so the database alone decides whether the event exists.
A separate relay reads unpublished outbox rows in order, publishes them to the broker, and marks them as published (or deletes them). The relay can poll the table, or a change data capture tool such as Debezium can tail the database log and publish inserts as they commit.
The relay can crash after publishing but before marking a row, so it will publish that event again. The outbox therefore guarantees at-least-once delivery, and consumers must be idempotent, typically by recording processed event ids (the inbox pattern).
How it works, step by step
- 1Begin a database transaction.
- 2Apply the business change (insert the order).
- 3Insert an outbox row with a unique event id, type and serialised payload.
- 4Commit. The event now exists if and only if the change does.
- 5The relay fetches unpublished rows, publishes each to the broker, then marks it published.
- 6Consumers deduplicate by event id.
Implementation
The C# example uses EF Core: the outbox row is added to the same DbContext, so SaveChangesAsync writes both in one transaction. The TypeScript example shows a polling relay on PostgreSQL that is safe to run on several instances.
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public sealed class Order
{
public Guid Id { get; init; }
public string CustomerId { get; init; } = "";
public decimal Total { get; init; }
}
public sealed class OutboxMessage
{
public Guid Id { get; init; } = Guid.NewGuid();
public string Type { get; init; } = "";
public string Payload { get; init; } = "";
public DateTime OccurredAtUtc { get; init; } = DateTime.UtcNow;
public DateTime? PublishedAtUtc { get; set; }
}
public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<OutboxMessage> Outbox => Set<OutboxMessage>();
}
public sealed class PlaceOrderHandler(ShopDbContext db)
{
public async Task<Guid> HandleAsync(string customerId, decimal total, CancellationToken ct)
{
var order = new Order { Id = Guid.NewGuid(), CustomerId = customerId, Total = total };
db.Orders.Add(order);
db.Outbox.Add(new OutboxMessage
{
Type = "OrderPlaced",
Payload = JsonSerializer.Serialize(new { order.Id, order.CustomerId, order.Total }),
});
// One SaveChanges = one transaction: both rows commit or neither does.
await db.SaveChangesAsync(ct);
return order.Id;
}
}A hosted background service then reads rows where PublishedAtUtc is null, ordered by OccurredAtUtc, publishes them, and sets the timestamp. Libraries such as MassTransit and NServiceBus include a ready-made EF Core outbox.
import pg from 'pg';
type OutboxRow = { id: string; type: string; payload: unknown };
type Publisher = { publish(topic: string, key: string, message: unknown): Promise<void> };
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
/** Publishes one batch; returns how many rows were handled. */
export async function relayBatch(publisher: Publisher, batchSize = 100): Promise<number> {
const client = await pool.connect();
try {
await client.query('BEGIN');
// SKIP LOCKED lets several relay instances share the table without double-claiming rows.
const { rows } = await client.query<OutboxRow>(
'SELECT id, type, payload FROM outbox WHERE published_at IS NULL ' +
'ORDER BY occurred_at LIMIT $1 FOR UPDATE SKIP LOCKED',
[batchSize],
);
for (const row of rows) {
// The event id travels with the message so consumers can deduplicate.
await publisher.publish(row.type, row.id, row.payload);
await client.query('UPDATE outbox SET published_at = now() WHERE id = $1', [row.id]);
}
await client.query('COMMIT');
return rows.length;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
export async function runRelay(publisher: Publisher, signal: AbortSignal) {
while (!signal.aborted) {
const handled = await relayBatch(publisher).catch(() => 0);
if (handled === 0) await new Promise((resolve) => setTimeout(resolve, 500));
}
}If the process dies after publishing but before COMMIT, the rows are unlocked and published again: duplicates are expected, loss is not.
In production
- Give every event a unique id generated when the outbox row is written, and carry it in the message so consumers can deduplicate.
- Preserve order where it matters by publishing per aggregate in insertion order and using the aggregate id as the partition key.
- Clean up published rows on a schedule (or delete on publish) so the table does not grow without bound.
- Monitor outbox lag: the age of the oldest unpublished row is the delay consumers experience.
- Change data capture removes polling load and latency but adds infrastructure (Kafka Connect, Debezium) to operate.
Trade-offs
Benefits
- Eliminates the dual-write problem: an event is published if and only if its change committed.
- Uses only the local database transaction; no distributed transaction or broker support needed.
- The broker can be down without blocking writes; events queue in the outbox and drain later.
- Provides an audit trail of emitted events.
Costs
- At-least-once delivery: consumers must handle duplicates.
- Adds latency between commit and publication (polling interval or CDC lag).
- Extra writes and a table to maintain, index and clean up.
- Another moving part (the relay) to deploy, scale and monitor.
Alternatives
- Change data capture on business tables
- Stream row changes directly from the database log without an outbox table; simpler writes, but events mirror table structure instead of intentional domain events.
- Event sourcing
- Store events as the source of truth and derive state from them, so the event store is the only write and publication follows from it.
- Listen to yourself
- Publish the event first and update the database when the service consumes its own event; consistent, but the change is not visible immediately after the request returns.
Anti-patterns
- Publish inside the transaction
- Calling the broker before commit announces changes that may still roll back and holds the transaction open during a network call.
- Publish after commit with best-effort retries
- A crash between commit and publish loses the event permanently, and nothing will ever retry it.
- Non-idempotent consumers
- The outbox delivers at least once; consumers that cannot handle duplicates will double-charge or double-ship.
Related lessons
Interview questions
What is the dual-write problem?
A service must update two systems, such as its database and a message broker, that do not share a transaction. Any crash or failure between the two writes leaves them inconsistent: either a committed change with no event, or an event for a change that never committed.
Why does the outbox give at-least-once rather than exactly-once delivery?
The relay publishes a message and then marks it as sent. If it crashes between those two steps, the row still looks unpublished and is sent again after restart. Effectively-once processing requires idempotent consumers on top.
Polling relay or change data capture: how do you choose?
Polling is simple and needs only SQL, but adds query load and latency proportional to the interval. CDC tails the transaction log with low latency and no polling queries, at the cost of running and operating tools such as Debezium and Kafka Connect.
How do you keep events for the same order in sequence?
Read outbox rows in insertion order and publish them with the order id as the message key, so a partitioned broker like Kafka places them on the same partition. Avoid parallel publishing of rows for the same key.