← Back to SQL, page 23

sql-0452 · Hard senior

An order service must save an order and publish an 'order placed' event to a message broker. How do you avoid saving without publishing, or publishing without saving?

Use the transactional outbox pattern: in the same database transaction as the order, insert the event into an outbox table. A separate relay process reads unsent outbox rows, publishes them to the broker and marks them sent. Since the order and the event commit together, neither can exist without the other; consumers must handle the occasional duplicate delivery.

Full answer
text
outbox(id bigserial PK, aggregate_type, aggregate_id, event_type, payload jsonb,
       created_at, published_at NULL)
CREATE INDEX ON outbox (id) WHERE published_at IS NULL;

Flow:

  1. BEGIN; INSERT INTO orders ...; INSERT INTO outbox (... 'OrderPlaced' ...); COMMIT;
  2. The relay polls WHERE published_at IS NULL ORDER BY id LIMIT 100 (with FOR UPDATE SKIP LOCKED if several relays run), publishes, then sets published_at.
  3. If the relay crashes after publishing but before marking, the event is published again on restart, so delivery is at least once. Consumers deduplicate by event id.

Why not publish directly from the service: the commit can succeed and the publish fail (lost event), or the publish succeed and the commit roll back (event about an order that does not exist). Two-phase commit across the database and broker is possible in theory but rarely supported or worth its cost.

Change data capture on the outbox table (reading the write-ahead log) is an alternative to polling.

Key points

  • Write the event in the same transaction
  • A relay publishes and marks rows
  • Delivery is at least once
  • Consumers deduplicate by event id
  • CDC can replace polling

Common mistakes

  • Publishing to the broker inside the transaction
  • Assuming exactly-once delivery

Follow-ups

  • How would you keep events in order per order id?
  • How would you clean up old outbox rows?

Tips

  • Explain both failure modes it prevents