Transactional Outbox Pattern in Go and PostgreSQL: Publishing Domain Events Without Dual-Write Race Conditions
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

The Dual-Write Trap Between SQL Databases and Message Brokers
Consider this common pattern in an order service:
- tx.Commit() writes the new order to PostgreSQL.
- broker.Publish("order.created", payload) sends the event to RabbitMQ or Kafka.
If the container is OOM-killed, redeployed, or loses its TCP connection to RabbitMQ milliseconds after step 1 succeeds, the order is permanently committed in PostgreSQL, but the order.created event is never published. Reversing the order (publishing to RabbitMQ before committing SQL) is even worse: if tx.Commit() fails on a constraint violation, downstream services process a phantom order that does not exist in the database.
1. Atomic Single-Database Commit via the Outbox Table
The Transactional Outbox Pattern solves this without slow two-phase distributed commits (2PC). Inside the exact same PostgreSQL transaction that inserts the business record, we insert the serialized event into an outbox_events table:
BEGIN;
INSERT INTO orders (id, tenant_id, amount_cents, status)
VALUES ($1, $2, $3, 'PAID');
INSERT INTO outbox_events (id, aggregate_type, aggregate_id, event_type, payload, status)
VALUES ($4, 'order', $1, 'order.paid.v1', $5::jsonb, 'PENDING');
COMMIT;
Either both rows commit atomically, or neither does.
2. Concurrent Outbox Relay Worker with FOR UPDATE SKIP LOCKED
A lightweight background worker pool in Go polls pending outbox rows using SELECT ... FOR UPDATE SKIP LOCKED so multiple Kubernetes pod replicas can drain the outbox concurrently without ever locking each other or publishing the same row twice:
WITH locked_batch AS (
SELECT id, event_type, payload
FROM outbox_events
WHERE status = 'PENDING'
ORDER BY created_at ASC
LIMIT 100
FOR UPDATE SKIP LOCKED
)
UPDATE outbox_events o
SET status = 'PROCESSING', locked_at = NOW()
FROM locked_batch lb
WHERE o.id = lb.id
RETURNING o.id, o.event_type, o.payload;