# The Transactional Outbox Pattern A service saves an order to its database and must also publish an `OrderCreated` event to Kafka. If it writes the database and then publishes, a crash in between loses the event. If it publishes first, a failed database write leaves a phantom event. This "dual write" problem is a common interview probe. ## The pattern 1. In the **same database transaction** as the business change, insert a row into an `outbox` table describing the event (ID, type, payload, created time). 2. A separate **relay** process reads unsent outbox rows and publishes them to the broker, then marks them sent (or deletes them). Because the order and the outbox row commit atomically, an event exists if and only if the order exists. ## Relay options - **Polling**: query unsent rows every few hundred milliseconds. Simple; adds some load and latency. - **Change data capture**: tools like Debezium tail the database's log and publish outbox inserts. Lower latency, no polling queries. ## Delivery guarantees The relay can crash after publishing but before marking a row sent, so events may be published **more than once**. Consumers must be idempotent, for example by recording processed event IDs. Ordering per entity can be kept by using the entity ID as the message key. ## Housekeeping Delete or archive sent rows regularly so the table stays small, and alert if the oldest unsent row gets too old (relay stuck). ## Related: the inbox pattern On the consuming side, store incoming message IDs in an inbox table within the same transaction as the side effects, which makes processing exactly-once in effect. ## Interview tip Whenever a design says "save to DB and publish an event", name the outbox pattern and idempotent consumers. Disclosure: I'm with Linkjob AI (https://www.linkjob.ai/), an AI coding interview helper.