Durable Outbox/Inbox Pattern Design
This design implements a transactionally durable outbox/inbox pattern for reliable, ordered, and at-least-once message delivery in distributed systems (e.g., microservices with relational DBs like Postgres). It ensures:
- Durability: Messages are written atomically with business changes.
- Ordering: Strict per-aggregate ordering using composite keys.
- Retry semantics: Exponential backoff, max retries, dead-letter queues (DLQ).
- Fanout: Supports 1:N delivery to multiple consumers via partitioned brokers (e.g., Kafka).
Assumptions:
- Database: Postgres (supports SKIP LOCKED, advisory locks).
- Broker: Kafka (for partitioning, ordering, fanout via topics/consumer groups).
- Services: Each producer/consumer has its own DB shard (outbox/inbox tables).
- Idempotency: UUIDv4 message IDs + consumer-side dedup.
1. Data Models (Database Schemas)
Outbox Table (Producer Service)
Stores outgoing events, written in the same transaction as business mutations.
CREATE TABLE outbox (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Message ID (idempotency)
aggregate_id VARCHAR(255) NOT NULL, -- Ordering key part 1 (e.g., user_id)
sequence_number BIGSERIAL NOT NULL, -- Ordering key part 2 (auto-inc per aggregate)
type VARCHAR(100) NOT NULL, -- Event type (e.g., 'UserUpdated')
payload JSONB NOT NULL, -- Event data
created_at TIMESTAMPTZ DEFAULT NOW(),
published_at TIMESTAMPTZ, -- NULL = pending
attempts INTEGER DEFAULT 0,
next_attempt_at TIMESTAMPTZ DEFAULT NOW(),
locked_until TIMESTAMPTZ, -- For poller concurrency
UNIQUE(aggregate_id, sequence_number) -- Enforce ordering
);
CREATE INDEX idx_outbox_pending ON outbox (aggregate_id, sequence_number)
WHERE published_at IS NULL AND next_attempt_at <= NOW();
CREATE INDEX idx_outbox_next_attempt ON outbox (next_attempt_at)
WHERE published_at IS NULL;
Usage in Transaction:
BEGIN;
UPDATE users SET name = 'New' WHERE id = 'user-123';
INSERT INTO outbox (aggregate_id, type, payload)
VALUES ('user-123', 'UserUpdated', '{"user_id": "user-123", "name": "New"}');
COMMIT;
- Sequence auto-increments per
aggregate_id, ensuring order.
Inbox Table (Consumer Service)
Tracks received messages for idempotency and at-least-once processing.
CREATE TABLE inbox (
id UUID PRIMARY KEY, -- Message ID from outbox
aggregate_id VARCHAR(255) NOT NULL,
sequence_number BIGINT NOT NULL,
type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMPTZ DEFAULT NOW(),
processed_at TIMESTAMPTZ, -- NULL = unprocessed
attempts INTEGER DEFAULT 0,
next_attempt_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(id), -- Global idempotency
UNIQUE(aggregate_id, sequence_number) -- Per-aggregate dedup
);
CREATE INDEX idx_inbox_pending ON inbox (aggregate_id, sequence_number)
WHERE processed_at IS NULL AND next_attempt_at <= NOW();
Dead-Letter Table (Shared or Per-Service)
For poisoned messages after max retries.
CREATE TABLE dlq (
id UUID PRIMARY KEY,
aggregate_id VARCHAR(255),
sequence_number BIGINT,
type VARCHAR(100),
payload JSONB,
attempts INTEGER,
last_error TEXT,
dlq_at TIMESTAMPTZ DEFAULT NOW()
);
2. Producer Relay (Outbox Poller)
A dedicated process (e.g., Kubernetes cronjob or Debezium/Kafka Connect) polls and publishes.
Polling Logic
Publish Flow
- Fetch batch.
- For each message:
- Publish to Kafka topic (e.g.,
events).
- Key:
${aggregate_id} (ensures same partition for ordering).
- Value: JSON
{id, aggregate_id, sequence_number, type, payload}.
- Headers:
sequence_number.
- On success:
UPDATE outbox SET published_at = NOW(), locked_until = NULL;.
- On Failure (per-message):
- Increment
attempts.
- Set
next_attempt_at = NOW() + (2 ^ attempts) * 30s (exponential backoff, cap at 1h).
- Max attempts=10 → Move to DLQ:
INSERT INTO dlq SELECT *; DELETE FROM outbox;.
- Commit DB changes in batch.
Guarantees:
- Ordering: Kafka partitions preserve
aggregate_id order; sequence_number for ties/gaps.
- Durability: WAL + Kafka acks=all.
3. Consumer (Inbox Processor)
Kafka consumer group per consumer service/topic.
Consumption Flow
- Consume from topic (enable auto-commit=false).
- For each message:
BEGIN;
-- Idempotent insert (ignore if exists)
INSERT INTO inbox (id, aggregate_id, sequence_number, type, payload)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (id) DO NOTHING;
COMMIT;
- Process Pending (separate poller or in consumer loop):
- Query:
SELECT * FROM inbox WHERE processed_at IS NULL AND next_attempt_at <= NOW() ORDER BY aggregate_id, sequence_number FOR UPDATE SKIP LOCKED LIMIT 100;.
- Business logic: e.g.,
UPDATE orders SET status = payload->>'status' WHERE aggregate_id = ?;.
- On success:
UPDATE inbox SET processed_at = NOW();.
- On failure:
- Increment
attempts, next_attempt_at = NOW() + (2 ^ attempts) * 10s.
- Max=5 → DLQ.
Kafka Config:
enable.idempotence=true.
- Consumer group per service for independent scaling.
4. Ordering Keys
- Composite Key:
(aggregate_id, sequence_number).
aggregate_id: Entity ID (e.g., user-123, order-456). Ensures logical partitioning.
sequence_number: DB auto-inc (BIGSERIAL). Gapless within aggregate.
- Enforcement:
- DB UNIQUE constraint.
- Poller/query ORDER BY.
- Kafka key=aggregate_id → Same partition → FIFO.
- Strictness: Per-aggregate total order. Cross-aggregate unordered (parallelism).
5. Retry Semantics
| Component | Backoff | Max Retries | Failure Handling |
|---|
| Producer Publish | Exp: 30s * 2^attempts (cap 1h) | 10 | DLQ + alert |
| Consumer Process | Exp: 10s * 2^attempts (cap 30m) | 5 | DLQ + alert |
| Kafka Delivery | Broker retries (acks=all) | Infinite (until expiry) | Retention 7d |
- Idempotency: Message ID + inbox check prevents duplicates.
- Monitoring: Prometheus metrics (pending count, lag, retry rate). Alerts on DLQ inserts.
- Manual Recovery: Reprocess DLQ via admin tool.
6. Fanout (1:N Delivery)
- Producer: Publish once to a fanout topic (e.g.,
events.v1).
- Consumers: Multiple consumer groups (e.g.,
order-service, notification-service).
- Each group gets full copy (Kafka fanout).
- Independent inboxes → Per-consumer ordering/idempotency.
- Scaling:
- Horizontal: More consumer instances → Parallel partitions.
- Cross-region: Mirror topics (Kafka MirrorMaker).
- Topic Partitioning: 100-1000 partitions, key=aggregate_id (hash partitioning).
Example Fanout:
Outbox (User Service) → Kafka 'user-events' →
Consumer Group 'order-svc' (Inbox A)
Consumer Group 'billing-svc' (Inbox B)
Consumer Group 'analytics-svc' (Inbox C)
7. Deployment & Ops
- Relay/Poller:
- Kubernetes CronJob (every 5s) or streaming (Debezium CDC for WAL polling).
- Shards: 10-50 pollers via hash modulo.
- Cleanup: Cron:
DELETE FROM outbox WHERE published_at < NOW() - 7d;.
- Performance:
- Batch 1000 → 10k msg/s.
- Indexes tuned for hot paths.
- Edge Cases:
- Duplicates: Inbox dedup.
- Gaps: App logic detects via sequence (e.g., replay from last known).
- Schema Evolution: JSONB + versioned types.
- Exactly-Once: Kafka Transactions (producer + consumer).
This pattern achieves 99.99%+ reliability with standard tooling. For production, add tracing (Jaeger) and tests (Chaos Monkey). Source code skeletons available on request!