Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Design reliable publishing of domain events to Kafka from services that write to PostgreSQL, so that no event is lost and none is published for rolled-back changes.

We use the transactional outbox pattern: the service writes the business change and an event row into an outbox table in the same PostgreSQL transaction, so the event exists if and only if the change committed. A relay, either a polling publisher or change data capture with Debezium, reads the outbox and publishes to Kafka, keyed by the aggregate id so events for one aggregate stay in order. Delivery is at least once, so consumers deduplicate by event id, and we monitor outbox lag and clean up published rows.

Why this question is asked

Writing to a database and publishing to Kafka are two separate systems, and no ordinary transaction covers both. If we write first and the publish fails, an event is lost; if we publish first and the transaction rolls back, consumers act on a change that never happened. Interviewers ask this design question because the answer shows whether we understand dual writes and the guarantees we can really get. In this answer, we will look at why the naive approaches fail, design the outbox, compare the two relay styles, and then cover ordering, idempotency and operations.

1Why Dual Writes Fail

A dual write is any code that changes two systems one after the other and hopes both succeed. Whatever order we choose, a crash between the two steps leaves them disagreeing. Sending inside the database transaction is no better: Kafka has already received the message when the database rolls back. Distributed transactions that span the database and the broker exist in theory, but Kafka does not take part in XA transactions with PostgreSQL, and even where such protocols work they are slow and fragile.

So we stop trying to write to two places. We write to one place, the database, and turn that write into a Kafka message afterwards, reliably.

2Write the Event in the Same Transaction

The outbox is an ordinary table. Each row is one event, with an id, the aggregate it belongs to, its type and its payload. The service inserts into it in the same transaction as the business change.

Java
create table outbox (
id uuid primary key,
aggregate_type text not null, -- 'order'
aggregate_id text not null, -- '42', becomes the Kafka key
event_type text not null, -- 'OrderPlaced'
payload jsonb not null,
created_at timestamptz not null default now(),
published_at timestamptz
);
@Transactional
public Order placeOrder(OrderRequest req) {
Order o = orders.save(Order.from(req));
outbox.save(OutboxRow.of(UUID.randomUUID(), "order", o.getId().toString(),
"OrderPlaced", json(OrderPlaced.of(o))));
return o;
}
// commit -> order row and outbox row both exist
// rollback -> neither exists

This one step gives us the core guarantee. Because both rows are in one database transaction, there is never an event for a rolled-back change, and never a committed change without its event. Everything after this point only has to move rows from the table to Kafka without losing any.

3The Relay

A relay is the process that reads outbox rows and publishes them. There are two common styles.

A polling publisher runs a query every few hundred milliseconds, such as select ... from outbox where published_at is null order by created_at limit 100 for update skip locked, sends each row to Kafka, waits for the broker's acknowledgement, and then marks the rows as published. FOR UPDATE SKIP LOCKED lets several relay instances share the work without taking the same rows. It is simple and needs nothing but the database, but it adds query load and some latency.

Change data capture, CDC, reads the database's write-ahead log, the log PostgreSQL writes every change to, through a logical replication slot. Debezium does this and has an outbox event router that turns inserts into the outbox table into Kafka messages, using a column such as aggregate_id as the key. It has low latency and no polling load, but it brings Kafka Connect and Debezium as extra systems to run.

Step throughThe outbox pipeline
  1. Order serviceWrites the order and the outbox row in one transaction
  2. PostgreSQLOrders table, outbox table, write-ahead log
  3. RelayPolling publisher, or Debezium reading the WAL
  4. Kafka topicKeyed by aggregate id, one partition per key
  5. ConsumersDeduplicate by event id, then apply the change

5 layers, from the top down. Step through them one at a time.

The only atomic step is the first one; every later step is retried until it succeeds.

4At Least Once, So Consumers Are Idempotent

The relay can crash after Kafka acknowledged a message but before it marked the row as published. On restart it publishes that row again. So delivery is at least once: never lost, sometimes duplicated. Exactly once end to end is not available across a database and a broker, so we make duplicates harmless instead.

Each event carries its outbox id as an event id. The consumer records processed ids in its own database, in the same transaction as the effect of the event, and skips ids it has already seen.

Java
@Transactional
public void on(OrderPlaced e) {
int inserted = jdbc.update(
"insert into processed_event(event_id) values (?) on conflict do nothing", e.eventId());
if (inserted == 0) return; // duplicate, already applied
invoices.createFor(e.orderId()); // applied exactly once in effect
}

5Ordering Per Aggregate

Kafka keeps order only within a partition, and it picks the partition from the message key. Using the aggregate id, the order id here, as the key sends all events for order 42 to the same partition, so OrderPlaced arrives before OrderCancelled. Events for different orders may interleave, which is fine.

The relay must not break this. A polling publisher with several instances can publish events for the same aggregate out of order if two instances take neighbouring rows. Common fixes are a single active relay, or claiming rows per aggregate. Debezium reads the log in commit order, which avoids the problem. On the producer side, enable.idempotence=true, the default in current Kafka clients, prevents duplicates and reordering caused by producer retries.

6Monitoring and Cleanup

The outbox is a queue, so we watch its age: the time since the oldest unpublished row was created. A healthy system shows a lag of under a second; an alert at, say, 60 seconds catches a stuck relay before consumers notice.

Published rows must be removed or the table grows forever. A scheduled job deletes rows published more than a few days ago, in small batches. With Debezium the service can even delete the row in the same transaction right after inserting it, because CDC reads the insert from the log. One more CDC risk is that a stopped connector keeps its replication slot, and PostgreSQL retains write-ahead log for it until disk fills, so slot lag needs its own alert.

7Follow-up questions

Why not use Kafka transactions instead?

Kafka transactions make writes to several Kafka partitions atomic and support exactly-once processing from Kafka to Kafka. They do not include PostgreSQL, so they cannot make a database commit and a publish atomic. The outbox is still needed at the boundary.

Should the payload be the full entity or just the change?

A self-contained event with the fields consumers need is usually best, built when the outbox row is written. Copying the raw entity couples consumers to the database schema, and publishing only an id forces every consumer to call back to the service.

How do you choose between polling and CDC?

Polling is fine for moderate volume, say a few hundred events per second, and is easiest to operate. CDC fits higher volume, low latency needs, or teams that already run Kafka Connect, and it preserves commit order naturally.

8Conclusion

In this answer, we saw that dual writes to PostgreSQL and Kafka cannot be made safe, so we write the event into an outbox table in the same transaction as the business change. A polling relay or Debezium then publishes it, keyed by aggregate id to keep per-aggregate order. Delivery is at least once, so consumers deduplicate by event id, and we monitor outbox age and replication slots and clean up published rows.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use a transactional outbox. The service writes the business change and an outbox row, with an event id, the aggregate id, the type and a JSON payload, in the same PostgreSQL transaction.

Then, if they want more

That gives the key guarantee: no event for a rolled-back change, and no committed change without its event. Then a relay moves rows to Kafka. For moderate volume, a polling publisher with select for update skip locked, publishing and then marking rows as published, is simple.

For higher volume or lower latency I would use Debezium with its outbox router, reading the write-ahead log. Either way delivery is at least once, because the relay can crash after publishing but before marking a row, so consumers store processed event ids in the same transaction as their effect and skip duplicates.

For ordering I use the aggregate id as the Kafka key, so all events for one order land in one partition, and I make sure the relay itself does not reorder them, for example with a single active poller.

Operationally I alert on the age of the oldest unpublished row, delete published rows in batches, and with CDC also alert on replication slot lag so WAL does not fill the disk.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design reliable publishing of domain events to Kafka from services that write to...": https://scrivio-interview-library.netlify.app/databases/transactions/3f01ba296e/