Exercise — Outbox Pattern: guarantee an event is published exactly when the row is committed.

Topic: microservices, Data Management. Level: Hard.

Answer

Write to `outbox` inside the business transaction. A poller (or CDC) reads unpublished rows, publishes them, and marks them sent — retrying on failure. Because publishing and marking-sent aren't atomic, delivery is at-least-once; consumers dedupe on the event id. ```java // Relay: runs on a schedule, publishes committed outbox rows @Scheduled(fixedDelay = 500) void relay() { for (OutboxEvent e : outboxRepo.findTop100ByPublishedFalseOrderById()) { kafka.send(e.getTopic(), e.getAggregateId(), e.getPayload()); e.setPublished(true); // if this fails, row re-published next tick outboxRepo.save(e); } } // Consumer dedupes: if (processedRepo.existsById(e.eventId())) return; // already handled ```