Make a state change and the event announcing it atomic: either both are durably recorded or neither is. Deliver the event to downstream consumers at least once, in per-entity order, even if the broker is down when the business transaction commits.
Any service that saves a row and then tells other services about it has the dual-write problem. The database and the message broker are two systems, and no single commit spans both. One of the two writes will eventually succeed while the other fails. The transactional outbox fixes this. You write the event into a table in the same database, inside the same transaction as the business change. A separate relay process then copies those rows to the broker. This guide follows one invented booking service from the incident that exposed the problem to an outbox design you can defend in an interview. It covers the schema, the relay loop, ordering, cleanup and the failure modes interviewers like to probe.
The problem
A situation where the obvious design starts to hurt.
Tidewater Ferries sells seats on coastal ferry sailings. The booking service runs on Postgres and handles about 220 booking confirmations per second at peak, when summer timetables open. Each confirmation must produce a BookingConfirmed event on the Kafka topic booking-events. Three consumers depend on it: the boarding-pass service, the email notifier and the seat-inventory read model behind the public availability page.
The original handler committed the booking to Postgres and then called producer.send. During a rolling restart of the Kafka cluster, sends failed for about 14 minutes after the producer's retries ran out. The handler logged the error and returned 200 because the booking was already committed. In that window, 1,140 passengers had paid, confirmed bookings with no boarding pass and no confirmation email. The availability page also kept showing their seats as free, so two sailings were oversold.
An earlier attempt had flipped the order: publish first, then commit. That failed the other way. When two customers raced for the last seat, the second commit hit a unique constraint and rolled back, but its event had already gone out. The boarding-pass service issued a pass for a booking that did not exist.
Wrapping both writes in a distributed transaction was rejected. Kafka does not take part in XA with Postgres, and two-phase commit would have tied booking latency to broker availability. The team needed the booking and its event to be atomic without making the broker part of the request path.
The solution
What the pattern proposes.
Add an outbox table to the booking database. In the same transaction that inserts the booking row, the handler inserts an outbox row with an event_id (UUID), the aggregate_id (the booking id), the event_type and a JSON payload. If the transaction commits, both rows exist. If it rolls back, neither does. The request never touches Kafka, so a broker outage no longer fails bookings or loses events.
A separate relay process polls for unpublished rows: published_at IS NULL, ordered by id, LIMIT 500, FOR UPDATE SKIP LOCKED. It publishes each row to Kafka keyed by aggregate_id, so all events for one booking land on the same partition and keep their order. It then sets published_at on the rows that were acknowledged. If a publish fails, the relay stops the batch at that row and records the error. A later event for the same booking can never overtake an earlier one.
Delivery is at least once. If the relay crashes after Kafka acknowledges a message but before it marks the row published, the row is sent again on the next poll. Every message carries event_id as a header, and consumers record processed event_ids in their own store in the same transaction as their side effect, so duplicates are skipped. A nightly job deletes published rows older than 7 days to keep the table and its partial index small.
At Tidewater, end-to-end lag from commit to Kafka sits around the 200 ms poll interval under normal load. During a broker outage, events queue up in Postgres and drain at roughly 2,000 to 3,000 per second once the brokers return.
An everyday analogy
The same idea, outside software.
Think of a hotel front desk that takes a booking and writes a slip for housekeeping in the same ledger, on the same line, with the same pen stroke. If the clerk tears the line out because the card was declined, the slip goes with it. A porter walks past the desk every few minutes, collects any slips not yet marked delivered, takes them to housekeeping and ticks them off.
If the porter gets interrupted between handing over a slip and ticking it, housekeeping may see the same slip twice. That is why each slip has a number, and housekeeping keeps a list of numbers it has already handled.
Structure
The pieces and how they relate.
Participants
- Booking service (producer)
- Runs the business transaction. Inserts the booking and the outbox row on the same connection, inside one BEGIN/COMMIT. It never talks to Kafka, so broker health does not affect booking latency or success.
- Outbox table
- Durable, ordered queue living in the service's own database. Columns: id bigserial (order), event_id uuid (dedupe key), aggregate_id (partition key), event_type, payload jsonb, created_at, published_at, attempts, last_error. A partial index on id WHERE published_at IS NULL keeps polling cheap.
- Outbox relay
- Background worker that locks a batch of unpublished rows, publishes them in id order, marks the acknowledged ones published and commits. It halts a batch at the first failure to preserve per-aggregate order.
- Message broker (Kafka topic booking-events)
- Carries events to consumers. Keying by booking id sends every event for a booking to one partition, so Kafka keeps them in order. The producer runs with acks=all and enable.idempotence=true.
- Idempotent consumers
- Boarding-pass, email and inventory services. Each records the event_id in a processed_events table in the same transaction as its side effect and skips any event_id it has already seen, which turns at-least-once delivery into effectively-once processing.
- Cleanup job
- Deletes published rows older than a retention window (7 days at Tidewater) in batches of 10,000, so the table and its index stay small and autovacuum keeps up.
Pseudocode
The solution to the scenario, language-neutral.
-- schema
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
event_id uuid NOT NULL UNIQUE DEFAULT gen_random_uuid(),
aggregate_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
attempts int NOT NULL DEFAULT 0,
last_error text
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
-- write path (request handler)
function confirmBooking(booking):
BEGIN
INSERT INTO bookings (...) VALUES (booking...)
INSERT INTO outbox (aggregate_id, event_type, payload)
VALUES (booking.id, 'BookingConfirmed', toJson(booking))
COMMIT -- both rows or neither
-- relay (one active instance)
function relayOnce(batchSize = 500):
BEGIN
rows = SELECT id, event_id, aggregate_id, event_type, payload
FROM outbox WHERE published_at IS NULL
ORDER BY id LIMIT batchSize FOR UPDATE SKIP LOCKED
sent = []
for row in rows:
try:
broker.publish(topic = 'booking-events',
key = row.aggregate_id,
value = row.payload,
headers = { event-id: row.event_id, event-type: row.event_type })
sent.append(row.id)
catch error:
UPDATE outbox SET attempts = attempts + 1, last_error = error WHERE id = row.id
break -- never let a later event overtake this one
UPDATE outbox SET published_at = now() WHERE id IN sent
COMMIT
return len(sent)
loop forever:
n = relayOnce()
if n == 0: sleep(200 ms)
-- consumer side
function handle(message):
BEGIN
if INSERT INTO processed_events(event_id) ON CONFLICT DO NOTHING affected 0 rows:
ROLLBACK; return -- duplicate
applySideEffect(message)
COMMITThe code
The same solution in TypeScript, Python and PHP.
import { Pool } from 'pg';
// Schema: see the outbox table definition. event_id defaults to gen_random_uuid().
export interface Publisher {
publish(topic: string, key: string, value: string, headers: Record<string, string>): Promise<void>;
}
export interface Booking {
id: string;
sailingId: string;
passengerId: string;
seats: number;
}
const TOPIC = 'booking-events';
export async function confirmBooking(pool: Pool, b: Booking): Promise<void> {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
'INSERT INTO bookings (id, sailing_id, passenger_id, seats, status) VALUES ($1, $2, $3, $4, $5)',
[b.id, b.sailingId, b.passengerId, b.seats, 'CONFIRMED'],
);
const payload = { bookingId: b.id, sailingId: b.sailingId, passengerId: b.passengerId, seats: b.seats };
await client.query(
'INSERT INTO outbox (aggregate_id, event_type, payload) VALUES ($1, $2, $3)',
[b.id, 'BookingConfirmed', JSON.stringify(payload)],
);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
interface OutboxRow {
id: string;
event_id: string;
aggregate_id: string;
event_type: string;
payload: string;
}
export async function relayOnce(pool: Pool, publisher: Publisher, batchSize = 500): Promise<number> {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query<OutboxRow>(
'SELECT id, event_id, aggregate_id, event_type, payload::text AS payload FROM outbox ' +
'WHERE published_at IS NULL ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED',
[batchSize],
);
const sent: string[] = [];
for (const row of rows) {
try {
await publisher.publish(TOPIC, row.aggregate_id, row.payload, {
'event-id': row.event_id,
'event-type': row.event_type,
});
sent.push(row.id);
} catch (err) {
await client.query(
'UPDATE outbox SET attempts = attempts + 1, last_error = $2 WHERE id = $1',
[row.id, String(err)],
);
break; // keep per-aggregate order: nothing after a failed row goes out
}
}
if (sent.length > 0) {
await client.query('UPDATE outbox SET published_at = now() WHERE id = ANY($1::bigint[])', [sent]);
}
await client.query('COMMIT');
return sent.length;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
export async function runRelay(pool: Pool, publisher: Publisher, signal: AbortSignal): Promise<void> {
while (!signal.aborted) {
let n = 0;
try {
n = await relayOnce(pool, publisher);
} catch (err) {
console.error('outbox relay batch failed', err);
}
if (n === 0) {
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
}import logging
import threading
from typing import Protocol
import psycopg
from psycopg.types.json import Jsonb
# Connections are opened with autocommit=True so conn.transaction() owns BEGIN/COMMIT.
TOPIC = 'booking-events'
log = logging.getLogger('outbox')
class Publisher(Protocol):
def publish(self, topic: str, key: str, value: str, headers: dict[str, str]) -> None: ...
def confirm_booking(conn: psycopg.Connection, booking: dict) -> None:
with conn.transaction():
conn.execute(
'INSERT INTO bookings (id, sailing_id, passenger_id, seats, status) VALUES (%s, %s, %s, %s, %s)',
(booking['id'], booking['sailing_id'], booking['passenger_id'], booking['seats'], 'CONFIRMED'),
)
payload = {
'bookingId': booking['id'],
'sailingId': booking['sailing_id'],
'passengerId': booking['passenger_id'],
'seats': booking['seats'],
}
conn.execute(
'INSERT INTO outbox (aggregate_id, event_type, payload) VALUES (%s, %s, %s)',
(booking['id'], 'BookingConfirmed', Jsonb(payload)),
)
def relay_once(conn: psycopg.Connection, publisher: Publisher, batch_size: int = 500) -> int:
sent: list[int] = []
with conn.transaction():
rows = conn.execute(
'SELECT id, event_id, aggregate_id, event_type, payload::text FROM outbox '
'WHERE published_at IS NULL ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED',
(batch_size,),
).fetchall()
for row_id, event_id, aggregate_id, event_type, payload in rows:
try:
publisher.publish(
TOPIC,
aggregate_id,
payload,
{'event-id': str(event_id), 'event-type': event_type},
)
except Exception as exc:
conn.execute(
'UPDATE outbox SET attempts = attempts + 1, last_error = %s WHERE id = %s',
(str(exc), row_id),
)
break # keep per-aggregate order: nothing after a failed row goes out
sent.append(row_id)
if sent:
conn.execute('UPDATE outbox SET published_at = now() WHERE id = ANY(%s)', (sent,))
return len(sent)
def run_relay(conn: psycopg.Connection, publisher: Publisher, stop: threading.Event) -> None:
while not stop.is_set():
n = 0
try:
n = relay_once(conn, publisher)
except psycopg.Error:
log.exception('outbox relay batch failed')
if n == 0:
stop.wait(0.2)<?php
declare(strict_types=1);
// PDO must be created with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION.
interface Publisher
{
/** @param array<string, string> $headers */
public function publish(string $topic, string $key, string $value, array $headers): void;
}
const TOPIC = 'booking-events';
/** @param array{id: string, sailing_id: string, passenger_id: string, seats: int} $booking */
function confirmBooking(PDO $pdo, array $booking): void
{
$pdo->beginTransaction();
try {
$pdo->prepare('INSERT INTO bookings (id, sailing_id, passenger_id, seats, status) VALUES (?, ?, ?, ?, ?)')
->execute([$booking['id'], $booking['sailing_id'], $booking['passenger_id'], $booking['seats'], 'CONFIRMED']);
$payload = json_encode([
'bookingId' => $booking['id'],
'sailingId' => $booking['sailing_id'],
'passengerId' => $booking['passenger_id'],
'seats' => $booking['seats'],
], JSON_THROW_ON_ERROR);
$pdo->prepare('INSERT INTO outbox (aggregate_id, event_type, payload) VALUES (?, ?, ?)')
->execute([$booking['id'], 'BookingConfirmed', $payload]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
function relayOnce(PDO $pdo, Publisher $publisher, int $batchSize = 500): int
{
$pdo->beginTransaction();
try {
$select = $pdo->prepare(
'SELECT id, event_id, aggregate_id, event_type, payload::text AS payload FROM outbox '
. 'WHERE published_at IS NULL ORDER BY id LIMIT ? FOR UPDATE SKIP LOCKED'
);
$select->bindValue(1, $batchSize, PDO::PARAM_INT);
$select->execute();
$sent = [];
foreach ($select->fetchAll(PDO::FETCH_ASSOC) as $row) {
try {
$publisher->publish(TOPIC, $row['aggregate_id'], $row['payload'], [
'event-id' => $row['event_id'],
'event-type' => $row['event_type'],
]);
$sent[] = (int) $row['id'];
} catch (Throwable $e) {
$pdo->prepare('UPDATE outbox SET attempts = attempts + 1, last_error = ? WHERE id = ?')
->execute([$e->getMessage(), $row['id']]);
break; // keep per-aggregate order: nothing after a failed row goes out
}
}
if ($sent !== []) {
$pdo->prepare('UPDATE outbox SET published_at = now() WHERE id = ANY(?::bigint[])')
->execute(['{' . implode(',', $sent) . '}']);
}
$pdo->commit();
return count($sent);
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
/** @param callable(): bool $shouldStop */
function runRelay(PDO $pdo, Publisher $publisher, callable $shouldStop): void
{
while (!$shouldStop()) {
$n = 0;
try {
$n = relayOnce($pdo, $publisher);
} catch (Throwable $e) {
error_log('outbox relay batch failed: ' . $e->getMessage());
}
if ($n === 0) {
usleep(200_000);
}
}
}When to use it
Situations where it pays off.
A service must update its own database and notify other services, and losing or inventing an event causes real harm, such as a paid booking with no ticket.
The outbox turns two writes to two systems into one local transaction plus an asynchronous copy, so the event exists exactly when the state change exists.
The broker is less available than your database, or you do not want broker latency in the request path.
Requests only touch Postgres. Broker outages turn into relay lag that drains later, not failed or inconsistent requests.
Consumers need events for the same entity in the order they happened, for example BookingConfirmed before BookingCancelled.
Outbox ids give a total commit-ordered sequence per database. Keying by aggregate id and halting on failure preserves that order through the broker.
You are building a saga or a CQRS read model that relies on every state change producing an event.
Sagas stall and read models drift if a single event is lost. The outbox gives each step a guaranteed, replayable record.
You cannot or will not run log-based change data capture infrastructure such as Debezium yet.
A polling relay needs only SQL and a producer client. You can switch the relay to CDC on the outbox table later without changing the write path.
How to implement it
Steps to introduce it in existing code.
Create the outbox table in the same database and schema as the business tables, with a bigserial id for ordering, a UUID event_id for dedupe, an aggregate_id for partitioning, and a partial index on id WHERE published_at IS NULL.
In every handler that changes state, insert the outbox row on the same connection and inside the same transaction as the business write. Make the domain method return the events so the repository writes both together and nobody forgets the second insert.
Write the relay: lock a batch with ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED, publish each row keyed by aggregate_id with event_id in a header, stop at the first failure, mark the successes published and commit.
Run exactly one active relay per outbox table, using a leader lease or a single-replica deployment. If you need more throughput, shard the work by hash of aggregate_id, never by competing over the same rows.
Configure the producer with acks=all and enable.idempotence=true. Set a publish timeout, say 5 seconds, well below the relay's statement_timeout, so a hung broker cannot hold row locks indefinitely.
Make every consumer idempotent. Insert the event_id into a processed_events table inside the consumer's own transaction and skip on conflict.
Add a cleanup job that deletes published rows older than 7 days in batches of 10,000, and alert when the oldest unpublished row is older than 60 seconds or attempts exceeds 20.
Pros and cons
What you gain and what you pay.
Pros
- Atomicity between state and event without distributed transactions: a rolled-back booking can never emit an event, and a committed one always will.
- Broker outages no longer fail user requests. They show up as relay lag, and the backlog drains automatically when the broker recovers.
- Per-aggregate ordering comes almost for free from the outbox id sequence and keyed partitions.
- The outbox is a queryable audit trail. You can answer questions like whether booking B-48213 had its event published, and when, with plain SQL.
- Needs no new infrastructure beyond the database and broker you already run.
Cons
- Delivery is at least once, so every consumer must deduplicate. You have only moved the problem out of the producer, not removed it.
- Adds write load to the primary database: one extra insert per event, later an update and a delete, plus polling queries every 200 ms.
- Events are delayed by the poll interval and batch time. Read-your-writes across services is not guaranteed.
- A single relay is a throughput ceiling and an operational component to monitor. Scaling it while keeping order requires partitioned relays.
Trade-offs
Decisions you'll have to make, each with its price.
Poll interval of 200 ms versus 2 seconds
You gain200 ms keeps commit-to-Kafka lag below roughly a quarter second, which matters for the email and availability page.
You payAbout 5 polls per second per relay. Each poll is cheap with the partial index, but it is constant load on the primary even when idle. At 2 seconds the load drops tenfold and lag rises to match.
Batch size of 500 rows per transaction
You gainAmortises the select and update round trips. One relay can drain a backlog at a few thousand events per second.
You payRow locks are held while all 500 publishes run. A slow broker extends the transaction, so you need a publish timeout and a statement_timeout of around 30 seconds to bound it.
Single active relay versus several relays with SKIP LOCKED
You gainA single relay guarantees global id order, and therefore per-booking order, with no extra coordination.
You payThroughput is capped by one process. Several relays racing on SKIP LOCKED can publish BookingCancelled before BookingConfirmed for the same booking unless you shard rows by hash of aggregate_id.
Delete published rows after 7 days versus immediately
You gainSeven days of history lets you replay events to rebuild a broken consumer and answer support questions with SQL.
You payAt 220 events per second at peak, the table can hold tens of millions of rows. Deletes must run in small batches, and autovacuum must be tuned, or table and index bloat slows polling.
Hold the transaction open during publish versus claim-then-publish
You gainHolding the lock is simple. A crashed relay releases its locks automatically and another instance resumes.
You payLong transactions block vacuum and pin connections. The alternative is to set a claimed_by and claimed_at lease, commit, publish, then mark rows done. That is shorter-lived but needs lease expiry logic.
How it fails
What goes wrong in production and how to prevent it.
Relay crashes after Kafka acks but before published_at is committed, so the batch is re-sent
What to doExpected under at-least-once delivery. Send event_id as a message header and have every consumer insert it into processed_events with ON CONFLICT DO NOTHING in the same transaction as its side effect, skipping when no row was inserted.
Kafka is down for 20 minutes and around 260,000 rows pile up in the outbox
What to doBookings keep succeeding. Alert when the oldest unpublished created_at is older than 60 seconds. On recovery the relay drains in batches of 500, so make sure the partial index exists and that autovacuum on outbox is aggressive (autovacuum_vacuum_scale_factor around 0.01).
A poison row (oversized payload, rejected by the broker) blocks every event behind it
What to doBecause the relay halts on failure, one bad row stalls the queue. After 20 attempts, move the row to an outbox_dead table and alert. Block only later rows with the same aggregate_id, not the whole stream. Enforce max payload size at insert time.
Two relay instances run after a bad deploy and publish events for one booking out of order
What to doRun the relay as a single replica, or have it hold a Postgres advisory lock (pg_try_advisory_lock) and exit if it cannot acquire it. To scale out, assign each relay a hash range of aggregate_id.
Developer adds a new state change but forgets the outbox insert, so events silently go missing
What to doMake domain methods return events and have one repository method persist state and events together. Add an integration test that checks every committed state transition produces an outbox row.
Bigserial ids commit out of order: transaction A takes id 100 but commits after B with id 101, and the relay marks 101 published first
What to doOrdering only matters per aggregate, and two transactions on the same booking serialize on its row lock, so per-booking order holds. If you need global order, poll only rows older than about 1 second, or use CDC, which reads in commit order.
In a system design interview
When to bring it up and how to explain it.
Use it as soon as a design has a service that writes to its own database and also publishes an event other services depend on, such as order placed, payment captured or booking confirmed. Interviewers often hint at it by asking what happens if the broker is down or the process dies right after the commit.
What you could say
The risk here is a dual write. The booking goes to Postgres and the event goes to Kafka, and nothing makes those atomic. If I publish after commit, a crash or broker outage loses the event. If I publish before commit, a rollback leaves a phantom event. So I'd use a transactional outbox. In the same transaction that inserts the booking, I insert a row into an outbox table with an event_id, the booking id as aggregate id, the event type and a JSON payload. Both rows commit or neither does, and the request never touches Kafka. A relay polls unpublished rows ordered by id, about 500 at a time with FOR UPDATE SKIP LOCKED, and publishes them keyed by booking id so each booking's events stay in one partition. It marks them published and stops at the first failure so nothing overtakes a failed event. Delivery is at least once, so consumers dedupe on event_id in their own transaction. I'd run one active relay behind an advisory lock, and alert on the age of the oldest unpublished row. I'd also clean up published rows after a week. At higher volume I'd swap polling for CDC on the outbox table without changing the write path.
Likely follow-ups
How do you scale the relay beyond one instance without breaking order?
Partition the work by hash of aggregate_id. Each relay owns a range, for example hashtext(aggregate_id) mod 4 equal to its index, and keeps its own lease. Order only has to hold per aggregate, and each aggregate is owned by exactly one relay, so the guarantee survives. Alternatively, move to CDC, which streams in commit order from a single WAL reader.
What happens if the consumer's side effect is an external email API that cannot join its transaction?
Record the event_id and an intent row in the consumer's database first, then call the provider with the event_id as its idempotency key if it supports one. If it does not, you accept a small duplicate window: mark the email sent after the call succeeds, and a crash in between can resend once.
Why not put the event in Kafka and have the booking service consume its own event to write the database?
That is the listen-to-yourself approach. It makes Kafka the source of truth, but the API can no longer tell the user the booking succeeded until the event is consumed. Constraints like seat uniqueness are also checked late. The outbox keeps the database authoritative and lets the request validate and respond synchronously.
How do you know the outbox is healthy in production?
Track three metrics: the age of the oldest unpublished row, the count of unpublished rows, and the maximum attempts on any row. Page when age exceeds 60 seconds or attempts exceed 20. Also watch table size and dead tuples, because a stalled cleanup job degrades polling well before anything fails outright.
Relations with other guides
Patterns it's often confused or combined with.
- Change Data Capture: Stream Database Changes from the Log
CDC is the main alternative to a polling relay. A tool such as Debezium tails the write-ahead log of the outbox table and publishes rows, which removes polling load and lag but adds connector infrastructure and replication slot management.
- Idempotency Keys: Making Retried Writes Safe
The outbox guarantees at-least-once delivery. Idempotency keys on the consumer side, here the event_id, are what make duplicate deliveries harmless.
- Saga: Multi-Service Transactions with Compensations
Each saga step changes local state and must reliably emit the event that triggers the next step. The outbox is the standard way to make that step atomic.
- Event Sourcing: Store What Happened, Derive What Is
With event sourcing the event store is the source of truth and can be published from directly. The outbox gives similar publishing guarantees to services that keep conventional state tables.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
The relay retries failed publishes on every poll. Adding exponential backoff per row stops a poison message or a down broker from hot-looping the relay.
- CQRS: Separate Write and Read Models with Projections
CQRS read models such as Tidewater's seat-availability view are fed by events. The outbox ensures no write to the command side is missing from the read side.
Common questions
Short answers to the usual doubts.
Why not just retry the Kafka publish after the database commit?
Retries live in process memory. If the pod is killed, OOMs or is redeployed between the commit and a successful send, the event is gone and nothing records that it was owed. The outbox makes the obligation durable in the same commit as the state, so a crash at any point leaves a row the relay will still pick up.
Does the outbox give exactly-once delivery?
No. The relay can crash after Kafka acknowledges a message but before it marks the row published, and the row will be sent again. You get at-least-once delivery plus a stable event_id. Exactly-once processing comes from consumers deduplicating on that id inside their own transaction.
Polling relay or change data capture?
Polling is simpler and needs only SQL. It costs one indexed query per poll and adds about one poll interval of latency. CDC on the outbox table, for example Debezium reading the Postgres WAL, has lower latency and no polling load, but you have to operate a connector and a replication slot that can bloat WAL if the connector stalls. Many teams start with polling and move to CDC above a few thousand events per second.
Should the outbox payload be the full entity or just an id?
Prefer a self-contained payload with the fields consumers need at the time of the change. An id-only event forces consumers to call back into the booking service. That reintroduces coupling and can return newer state than the event describes. Version the payload with a schema_version field so you can evolve it.
Can I use the outbox if my service writes to two different databases?
Only for changes in the database that holds the outbox. The pattern relies on a single local transaction. If a use case spans two databases, give each its own outbox and coordinate the two with a saga, not a cross-database transaction.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Queues and messagingTake the test
- An event platform for 10 teamsSolve the exercise