Event-Driven Architecture: Outbox, Idempotency and Retries
Derar SattoufUpdated Backend & databases

Event-driven architecture promises decoupling: services publish facts ("OrderPlaced"), and others react without the publisher knowing who they are. In practice, teams discover a harsh reality. Messages get lost, duplicated, reordered, and poisoned, and systems quietly drift out of sync. The decoupling that looked free comes with a bill for reliability engineering.
The good news is that a small set of patterns handles most of it. The examples use Postgres and a generic broker (Kafka, RabbitMQ, SQS, NATS), since the patterns are broker-independent.
Updating a database and publishing a message are two operations, and one can succeed while the other fails, so never do both naively. Instead, write the event to an outbox table in the same transaction as the state change and let a separate relay publish it. Brokers give you at-least-once delivery in practice, so make consumers idempotent with a dedupe key or natural idempotency.
Preserve ordering where it matters through partition keys (all events for one aggregate go to one partition), and design consumers so they tolerate reordering where it doesn't. Use bounded retries with backoff, then a dead-letter queue with alerting and a replay tool. Treat events as a public API: version schemas and evolve them compatibly.
One trap is worth knowing before you start. Sequence ids are assigned at insert time, not commit time, so a poller that tracks "last id seen" can skip rows. Use SKIP LOCKED with a published flag, or CDC.
The dual-write problem
// BROKEN: two systems, no shared transaction
await db.orders.insert(order); // 1. succeeds
await broker.publish("OrderPlaced", order); // 2. crashes or times out
// => order exists, no event. Downstream never learns about it.Reversing the order is not better: publishing first and then failing the insert emits an event for an order that does not exist. Wrapping both in a try/catch does not help when the process dies between them.
"Exactly-once" across a database and a broker is not something you can bolt on; you need a pattern that makes the database the source of truth for what must be published.
The transactional outbox
Write the event into a table in the same local transaction as the business change. Either both commit or neither does.
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL UNIQUE DEFAULT gen_random_uuid(),
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;export async function placeOrder(input: PlaceOrderInput) {
return db.transaction(async (tx) => {
const order = await tx.orders.insert({ ...input, status: "placed" });
await tx.outbox.insert({
aggregate_type: "order",
aggregate_id: order.id,
event_type: "OrderPlaced",
payload: { orderId: order.id, customerId: order.customerId, total: order.total },
});
return order;
});
}Relaying the outbox
Two common approaches:
A. Polling publisher: a worker selects unpublished rows, publishes, and marks them. Use FOR UPDATE SKIP LOCKED so multiple workers can run without conflicts.
export async function relayBatch() {
await db.transaction(async (tx) => {
const rows = await tx.query(
`SELECT id, event_id, aggregate_id, event_type, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED`
);
if (rows.length === 0) return;
for (const r of rows) {
await broker.publish(r.event_type, r.payload, {
key: r.aggregate_id, // partition key => per-aggregate ordering
headers: { "event-id": r.event_id }, // consumers dedupe on this
});
}
await tx.query(`UPDATE outbox SET published_at = now() WHERE id = ANY($1)`, [rows.map(r => r.id)]);
});
}If the worker crashes after publishing but before the UPDATE, the rows get published again: duplicates are possible, which is why consumers must be idempotent.
B. Change Data Capture (CDC): a tool such as Debezium tails the database's write-ahead log and publishes outbox rows to Kafka with lower latency and no polling load. More infrastructure, better scale. Debezium even ships an outbox event router for this pattern.
Housekeeping: delete or archive published rows on a schedule (or partition the table by day and drop old partitions) so it doesn't grow without bound.
Idempotent consumers
Because delivery is at-least-once, the same event can arrive twice (relay retry, consumer crash before ack, broker redelivery, rebalance). A consumer must produce the same end state whether it handles an event once or five times.
Strategy 1: natural idempotency
Design operations so repeating them is harmless.
-- Idempotent: setting state, not incrementing
UPDATE shipments SET status = 'dispatched' WHERE order_id = $1;
-- NOT idempotent: replays double-count
UPDATE accounts SET balance = balance + 50 WHERE id = $1;Strategy 2: dedupe table in the same transaction
Record processed event IDs atomically with the side effect:
CREATE TABLE processed_events (
consumer TEXT NOT NULL,
event_id UUID NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);export async function handleOrderPlaced(evt: OrderPlaced, eventId: string) {
await db.transaction(async (tx) => {
const inserted = await tx.query(
`INSERT INTO processed_events (consumer, event_id)
VALUES ('billing', $1) ON CONFLICT DO NOTHING RETURNING 1`,
[eventId]
);
if (inserted.length === 0) return; // duplicate: already handled
await tx.invoices.insert({ orderId: evt.orderId, amount: evt.total });
});
// ack the message only after the transaction commits
}Because the dedupe insert and the business write share a transaction, a crash cannot leave them inconsistent. Prune processed_events after a retention window longer than your maximum redelivery horizon.
Strategy 3: idempotency keys for outbound side effects
When a consumer calls an external API (payment provider, email service), pass an idempotency key derived from the event ID so retries do not charge or email twice.
await stripe.paymentIntents.create(
{ amount: evt.total, currency: "usd", customer: evt.customerId },
{ idempotencyKey: `order-${evt.orderId}-charge` }
);Acknowledge after processing succeeds. Acking first risks losing the message if the consumer crashes; acking after risks duplicates, which you've already designed for.
Ordering
Brokers generally guarantee ordering only within a partition (Kafka) or queue/message group (SQS FIFO, RabbitMQ with single consumer). Global ordering does not scale.
- Use the aggregate ID as the partition key, so all events for
order-123are ordered relative to each other. - Don't assume ordering across aggregates or topics.
- With retries and parallel consumers, order can still be violated: a failed message retried later arrives after its successor. Defend with version numbers:
// Ignore stale events using a per-aggregate version
await tx.query(
`UPDATE order_projection
SET status = $2, version = $3
WHERE order_id = $1 AND version < $3`,
[evt.orderId, evt.status, evt.version]
);If an event arrives with a lower version than stored, it is a no-op. This makes projections tolerant of both duplicates and reordering.
- For stricter needs, pause the partition on failure rather than skipping ahead (head-of-line blocking is the price of strict order), and alert quickly.
Retries, backoff, and dead-letter queues
Failures come in two flavors:
- Transient: network blip, downstream 503, deadlock. Retry helps.
- Permanent: malformed payload, bug, missing referenced data. Retry never helps and just burns capacity ("poison message").
async function consume(msg: Message) {
try {
await handle(msg);
await msg.ack();
} catch (err) {
if (isPermanent(err) || msg.attempts >= MAX_ATTEMPTS) {
await dlq.publish(msg, { error: String(err), attempts: msg.attempts });
await msg.ack(); // remove from main flow
} else {
const delay = Math.min(60_000, 500 * 2 ** msg.attempts) * (0.5 + Math.random());
await retryQueue.publish(msg, { delayMs: delay, attempts: msg.attempts + 1 });
await msg.ack();
}
}
}Guidelines:
- Exponential backoff with jitter, to avoid retry storms.
- Bounded attempts, then DLQ. An unbounded retry loop on a poison message blocks a partition forever.
- Never silently drop a dead-lettered message. Alert on DLQ depth, include error and context, and build a replay tool to re-publish after fixing the bug.
- Separate retry topics or delay queues (for example 1 min, 10 min, 1 hour tiers) keep the main consumer unblocked.
- Add circuit breakers around downstream dependencies: if the payment service is down, pause consumption instead of cycling every message into the DLQ.
Schema design and evolution
Events outlive the code that wrote them. Consumers you don't control will depend on their shape.
Event design tips
- Name events as past-tense facts:
OrderPlaced,PaymentCaptured. Avoid commands disguised as events (DoShipOrder). - Include
eventId,eventType,occurredAt,aggregateId,version/schemaVersion, and a correlation/trace ID. - Thin vs fat events: a thin event carries IDs only (consumers call back for details, coupling them to your API and creating load); a fat event carries enough state for consumers to act independently (larger payloads, but decoupled). Prefer reasonably fat events with the data most consumers need, never entire internal entities.
{
"eventId": "6f2c7b0e-4b7a-4d9b-8d33-0a1f1b5e9a11",
"eventType": "OrderPlaced",
"schemaVersion": 2,
"occurredAt": "2026-11-07T10:15:30Z",
"aggregateId": "ord_123",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"data": {
"customerId": "cus_88",
"total": { "amount": 4999, "currency": "USD" },
"items": [{ "sku": "SKU-1", "qty": 2 }]
}
}Compatibility rules
- Add optional fields; never remove or repurpose existing ones.
- Never change a field's type or meaning in place; add a new field or publish a new event version.
- Use a schema registry (Avro, Protobuf, or JSON Schema) with compatibility checks in CI so a breaking change fails the build.
- Consumers should be tolerant readers: ignore unknown fields, and don't fail on additions.
- To retire an old version, publish both for a deprecation window and track which consumers still read the old one.
Consistency without distributed transactions: sagas
When a business process spans services (order, payment, inventory), you can't use one transaction. A saga is a sequence of local transactions coordinated by events, with compensating actions for failure.
OrderPlaced -> [Payment] reserve funds -> PaymentCaptured
-> [Inventory] reserve stock -> StockReserved
-> [Shipping] create shipment -> OrderFulfilled
Failure at Inventory: StockReservationFailed -> [Payment] refund -> OrderCancelledTwo styles:
- Choreography: services react to each other's events. Simple for small flows, hard to see the whole process as it grows.
- Orchestration: a coordinator (a workflow engine or an orchestrator service) tells each participant what to do and tracks state. More explicit and easier to reason about for long processes. See durable execution workflows with Temporal.
Make every step idempotent and every compensation safe to repeat.
Observability
Distributed event flows are hard to debug without instrumentation.
- Propagate trace context (W3C
traceparent) in message headers so one trace spans producer, broker, and consumers. - Emit metrics: consumer lag, processing time, retry counts, DLQ depth, outbox backlog (unpublished rows and age of the oldest), and throughput.
- Alert on the age of the oldest unpublished outbox row and on consumer lag growth, since they are leading indicators of trouble.
- Log
eventIdandaggregateIdon every handler invocation so one entity's history is searchable.
-- Outbox health: how far behind is the relay?
SELECT count(*) AS pending, now() - min(created_at) AS oldest
FROM outbox WHERE published_at IS NULL;Testing
- Idempotency tests: deliver each event twice and assert the same end state.
- Reordering tests: deliver v2 before v1.
- Crash tests: kill the consumer between side effect and ack; kill the relay between publish and mark.
- Contract tests (Pact, schema registry checks) between producers and consumers.
- Replay tests: rebuild a projection from the full event history and compare with live state.
Checklist
- State change and event recorded in one transaction (outbox) or via CDC.
- Relay is safe to run multiple times; duplicates are expected.
- Every consumer is idempotent (natural, dedupe table, or idempotency key).
- Partition key is the aggregate ID; handlers tolerate stale or reordered events via versions.
- Retries use backoff and jitter, are bounded, and end in a monitored DLQ with a replay path.
- Events are versioned, backward compatible, and checked in CI.
- Trace IDs flow through messages; lag, DLQ, and outbox age are alerted.
- You've tested duplicate delivery, reordering, and crashes at the worst moments.
The outbox ordering trap (and how to avoid it)
A polling relay that remembers "the highest id I published" can silently skip events. Sequence values are allocated when a row is inserted, but rows become visible when the transaction commits. Two concurrent transactions can get ids 10 and 11, and 11 can commit first. A poller that reads up to 11 and records it as its cursor will never see 10 once it commits.
tx A: insert outbox id=10 ........................ commit (late)
tx B: insert outbox id=11 ... commit (early)
poller: sees 11, cursor=11 -> id 10 is skipped foreverSafe options:
- Publish-flag polling (the approach shown earlier): select
WHERE published_at IS NULLand mark rows after publishing. Visibility, not id order, decides what is picked up. WithFOR UPDATE SKIP LOCKEDmultiple relays are safe. - CDC from the write-ahead log: the log is in commit order, so nothing is skipped.
- A safety margin: if you must use a cursor, only publish rows older than a few seconds, and still keep an eventual reconciliation job. This is a heuristic, not a guarantee.
Also note that per-aggregate ordering of published events requires that the relay publishes events for the same aggregate in order. With multiple relay workers and SKIP LOCKED, two workers may publish different rows for one aggregate concurrently. If strict per-aggregate ordering matters, shard relay workers by aggregate id hash, or rely on consumer-side version checks as shown in the ordering section.
The inbox pattern on the consumer side
The dedupe table from Strategy 2 above is the inbox pattern. A fuller version stores the message before processing, which also lets you handle messages from brokers without good redelivery controls and gives you an audit trail.
CREATE TABLE inbox (
consumer TEXT NOT NULL,
message_id UUID NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ,
PRIMARY KEY (consumer, message_id)
);Flow: insert into the inbox with ON CONFLICT DO NOTHING. If nothing was inserted and processed_at is set, it is a duplicate; ack and skip. If inserted (or present but unprocessed), do the work and set processed_at in the same transaction as the side effects.
Broker notes
Behavior differs by broker. Verify details in your broker's documentation.
| Broker | Ordering unit | Delivery semantics | Notes |
|---|---|---|---|
| Kafka | Partition | At-least-once by default; idempotent producer and transactions give exactly-once within Kafka | Key by aggregate id; consumer commits offsets after processing |
| RabbitMQ | Queue (single consumer preserves order) | At-least-once with acks and publisher confirms | Use dead-letter exchanges and TTL queues for retries |
| Amazon SQS | FIFO queues with message group id | Standard queues: at-least-once, unordered; FIFO: ordered per group, deduplication window | Dead-letter queue via redrive policy; visibility timeout must exceed processing time |
| NATS JetStream | Stream and subject | At-least-once with acks, dedupe by message id within a window | Good fit for lightweight services |
| Cloud pub/sub services | Ordering keys (optional) | At-least-once | Enable ordering explicitly and understand its throughput cost |
Even when a broker advertises exactly-once, that guarantee stops at the broker boundary. Your database write and any external API call are still outside it, so idempotent consumers remain necessary.
A Kafka consumer sketch (Node, kafkajs style)
import { Kafka } from "kafkajs";
const kafka = new Kafka({ clientId: "billing", brokers: [process.env.BROKER!] });
const consumer = kafka.consumer({ groupId: "billing" });
await consumer.connect();
await consumer.subscribe({ topic: "orders", fromBeginning: false });
await consumer.run({
autoCommit: false, // commit offsets only after the DB transaction succeeds
eachMessage: async ({ topic, partition, message }) => {
const eventId = message.headers?.["event-id"]?.toString();
if (!eventId) throw new Error("missing event-id"); // route to DLQ in real code
await handleOrderPlaced(JSON.parse(message.value!.toString()), eventId);
await consumer.commitOffsets([
{ topic, partition, offset: (Number(message.offset) + 1).toString() },
]);
},
});
declare function handleOrderPlaced(e: unknown, id: string): Promise<void>;The library API is illustrative, so check the client you use. The principle is what matters: process, commit the database transaction, then commit the offset.
CDC with Debezium (outline)
Debezium reads the Postgres write-ahead log and has an outbox event router transformation. The configuration below is an outline; property names are version dependent, so follow the Debezium outbox event router docs.
{
"name": "outbox-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "db",
"database.dbname": "app",
"table.include.list": "public.outbox",
"plugin.name": "pgoutput",
"transforms": "outbox",
"transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
"transforms.outbox.route.by.field": "aggregate_type"
}
}Operational cautions: logical replication slots retain WAL until consumed, so a stopped connector can fill the database disk. Monitor replication slot lag and set alerts. CDC also requires database-level configuration (wal_level=logical) that managed services may restrict.
Replay and rebuild
A major advantage of events is the ability to rebuild read models. Plan for it:
- Keep events long enough (or archive them to object storage).
- Make projection handlers idempotent and version-aware so a replay into a fresh table works.
- Throttle replays, and run them against a shadow table, then swap.
- Store
schemaVersionso old events can be upcast during replay.
// Upcasting: convert old event versions to the current shape on read
function upcast(evt: { schemaVersion: number; data: any }) {
if (evt.schemaVersion === 1) {
return { ...evt, schemaVersion: 2, data: { ...evt.data, total: { amount: evt.data.total, currency: "USD" } } };
}
return evt;
}Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Downstream missing some events | Outbox poller cursor skipped uncommitted ids | Use publish-flag polling or CDC |
| Duplicate side effects (double emails) | Non-idempotent consumer, or ack before commit | Dedupe table, idempotency key, ack after commit |
| Consumer lag keeps growing | Poison message blocking a partition, or slow downstream | Bounded retries and DLQ; circuit breaker; scale partitions and consumers |
| Outbox table is huge, queries slow | No cleanup | Delete published rows or partition by time; keep the partial index |
| State is stale after a retry | Reordering | Version checks on projections |
| Database disk filling up with CDC | Replication slot not consumed | Monitor slot lag; drop abandoned slots |
| Messages rejected after a deploy | Breaking schema change | Compatibility checks in CI; tolerant readers |
| DLQ fills after a dependency outage | Retries exhausted during outage | Circuit breaker pauses consumption; replay DLQ after recovery |
Where this usually goes wrong
- Publishing to the broker inside the database transaction and assuming it is atomic.
- Making events too thin, forcing every consumer to call back to the producer.
- Using the event bus as a database: unbounded retention and ad hoc queries.
- No DLQ owner. A DLQ nobody watches is just data loss with extra steps.
- Changing an event's meaning without a version bump.
- Treating "exactly-once" marketing as a guarantee for your whole flow.
- Skipping observability until the first incident.
When not to use event-driven patterns
- A single service with a single database: a plain transaction is simpler. A modular monolith with in-process events can go very far.
- Workflows that need request and response semantics with strict latency: use synchronous calls with timeouts and retries.
- Teams without operations capacity for brokers, DLQs and schema governance: the reliability bill is real.
- Long, multi-step, human-in-the-loop processes: consider durable execution instead of hand-rolled sagas.
Questions that come up
Outbox or CDC? Start with the polling outbox (simple, any database) and move to CDC when volume or latency requires it and you can operate it.
Can I get exactly-once processing? Effectively yes, by combining at-least-once delivery with idempotent handlers. You cannot get it from the network alone.
How long should I keep dedupe records? Longer than the maximum time a message can be redelivered or replayed. Days to weeks is common; verify against your retention.
Should every event go through the outbox? Every event that must reflect a committed state change. Purely informational telemetry can use other paths.
Sources and docs
- Microservices.io: Transactional outbox
- Microservices.io: Saga pattern
- Debezium outbox event router
- Apache Kafka documentation: message delivery semantics
- Amazon SQS FIFO queues
- PostgreSQL: SELECT ... FOR UPDATE SKIP LOCKED
- CloudEvents specification
- Related posts on this site: Durable execution and Temporal, Modular monolith architecture, API rate limiting, idempotency and pagination, Zero-downtime Postgres migrations, SLOs and error budgets