How do you implement the Transactional Outbox table in SQL?
Topic: microservices, SQL Side. Level: Hard.
Answer
Add an `outbox` table written in the *same transaction* as the business change. A relay/CDC process reads unpublished rows, emits them to the broker, and marks them published. This makes the DB write and the intent-to-publish atomic, solving the dual-write problem. Index on `published` for the poller; retention job purges old published rows.
```sql
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
aggregate_id UUID NOT NULL,
type TEXT NOT NULL, -- e.g. 'OrderPlaced'
payload JSONB NOT NULL,
published BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_outbox_unpublished ON outbox (id) WHERE published = FALSE;
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status) VALUES (...);
INSERT INTO outbox (aggregate_id, type, payload)
VALUES ('...', 'OrderPlaced', '{"orderId":"..."}'); -- same tx
COMMIT; -- CDC/relay publishes the outbox row after commit
```