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:
BEGIN; INSERT INTO orders ...; INSERT INTO outbox (... 'OrderPlaced' ...); COMMIT;- The relay polls
WHERE published_at IS NULL ORDER BY id LIMIT 100(withFOR UPDATE SKIP LOCKEDif several relays run), publishes, then setspublished_at. - 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