Fanout: One message in the inbox/outbox might trigger multiple downstream actions or messages.
I need to structure this as a system design proposal.
1. High-Level Concept:
Outbox Pattern: Usually used in microservices. When a service changes state (DB write), it also writes a message to an "outbox" table within the same transaction. A separate process (Relay/CDC) reads this table and publishes to a message broker.
Inbox Pattern: Used on the consumer side. Before processing a message, check an "inbox" table to see if it's already been processed (idempotency) or to ensure ordering.
Durable: Persisted to disk/DB, so nothing is lost on crash.
2. Architecture Components:
Producer Service:
Application Logic.
Database (State + Outbox Table).
Transactional Outbox logic.
Relay (Outbox Processor):
Polling or CDC (Change Data Capture).
Responsible for pushing to the Broker.
Message Broker: Kafka/RabbitMQ/SQS (The pipe).
Consumer Service:
Listener.
Inbox Table (for idempotency/ordering).
Application Logic.
Fanout logic.
3. Deep Dive: Ordering Keys
Problem: Parallel processing breaks ordering.
Solution: Partitioning based on keys (e.g., order_id, user_id).
Producer side: Ensure the Outbox ID is monotonically increasing per key or use a composite key, but usually, the broker handles partitioning based on the key provided by the Relay.
Consumer side: The Inbox table must handle versioning.
Implementation detail:
If using Kafka: Use the entity ID as the partition key.
If using DB polling: SELECT * FROM outbox WHERE key = ? ORDER BY created_at.
Inbox Constraint: INSERT INTO inbox (key, sequence_id) ... unique constraint. If sequence ID <= last processed, skip.
Relay Polling: "Select for update skip locked" is crucial for scaling the relay without double-processing.
Ordering: If using Kafka, it's easy. If using DB polling, the Relay must query ORDER BY created_at and ensure it processes sequentially per aggregate_id. This is hard to parallelize.
Better Approach for Relay: Use CDC (Debezium). It captures changes in commit order. If order is crucial per key, the consumer must handle it or the partitioner must route it correctly.
Let's structure the answer:
Architecture Overview
Data Model (The "Durable" part)
Handling Ordering (The "Key" part)
Handling Retries (The "Semantics" part)
Handling Fanout (The "Scale" part)
Complete Workflow (Putting it together)
Wait, does the user mean "Fanout" as in the inbox pattern triggers multiple outboxes? Yes, typically this is a saga or choreography pattern.
Or does it mean "One write triggers multiple subscribers"? I will cover both: the Relay fans out to topics, OR the Consumer fans out to new Outbox entries.
Specific Design for Ordering + Retries:
The "Inbox" pattern is primarily for idempotency. To enforce ordering with retries:
If Message 2 fails, do we stop processing Message 3?
Yes. If strict ordering is required.
The Inbox table needs a version column.
Consumer Logic:
Start Transaction.
Read current state for Key=X.
Check Inbox for Message (Key=X, Version=V).
If Version <= Current_Version, skip (duplicate).
If Version == Current_Version + 1, apply logic.
If Version > Current_Version + 1, this is an out-of-order "future" message. Nack/Delay/Lock.
Commit.
Let's refine the solution to be technology-agnostic but leaning towards SQL + Kafka/Queue.
Plan:
Core Concept: Transactional integrity.
Database Schema: outbox and inbox tables.
The "Relay" (Polling Publisher): Handles moving from Outbox to Broker.
The "Consumer" (Idempotent Receiver): Handles Inbox logic.
Deep Dive: Ordering: Partitioning/Sharding keys.
Deep Dive: Retries: DLQs, Backoff, Visibility timeouts.
Deep Dive: Fanout: Composite destinations.
Let's start drafting. I will focus on a robust SQL-based implementation as it's the standard for "Durable" patterns.
Self-Correction on Fanout:
If I have an Inbox message that needs to trigger 3 things, do I update the Inbox and write to Outbox in one transaction? Yes.
BEGIN TX INSERT INTO inbox (id...) INSERT INTO outbox (msg1...) INSERT INTO outbox (msg2...) UPDATE user_state...COMMIT
This is the "Transactional Inbox/Outbox" chaining.
Okay, ready to generate the response. I will use clear headers, code blocks for SQL/Logic, and diagrams where helpful (text-based).
This looks solid. I will implement the design. Note specific SQL syntax for "Skip Locked" as it's crucial for the relay performance. Note the "Sequence Number" for ordering.
One nuance: Ordering Keys.
Ideally, the Producer assigns a sequence number per aggregate ID. Or the Relay assigns a Kafka partition. If the DB is the source of truth, created_at + auto_inc is usually enough, provided the Relay reads in order.
Consumer side ordering:
This is the hardest part with retries.
If I have a stream: M1, M2, M3.
M1 processed.
M2 fails (retry).
M3 arrives.
If strict order: M3 cannot process until M2 succeeds.
Queue solution: Use a partitioned queue (Kafka). M1, M2, M3 are in partition P1. Consumer reads P1 sequentially. If M2 fails, it blocks P1 (or loops).
DB Polling solution: Consumer polls SELECT * FROM inbox WHERE status='pending' ORDER BY seq. If top item is M2 (failed), it must wait. M3 cannot be picked up if the query is strict or the lock is exclusive.
Solution: If M2 fails transiently, release lock, sleep, retry. M3 waits. If M2 fails permanently (DLQ), M2 is marked DLQ, M3 proceeds.
I will present a solution that works with both generic Message Queues and direct DB polling.
Fanout:
Fanout usually happens at the Broker level (Topic fanout) OR the Application level (One event -> N actions).
I will define the Application-level fanout: "Chain Reaction".
Inbox -> Process -> Write to Outbox (1:N).
Final check of requirements:
Durable: DB backed.
Ordering: Key-based partitioning/sequencing.
Retry: Visibility timeout + DLQ + Idempotency.
Fanout: Chained transactions.
Let's go.
This design outlines a robust, production-grade system implementing the Transactional Outbox and Inbox patterns. This architecture guarantees "Effectively Once" processing, strict ordering per entity, and resilient fanout capabilities.
1. High-Level Architecture
The system is divided into three distinct layers to ensure separation of concerns and durability.
Producer Service (Outbox Layer): Commits business logic and outgoing messages in a single local DB transaction.
Relay Service (CDC Layer): Polls the Outbox and pushes to the Message Broker. This decouples the database from the broker.
Consumer Service (Inbox Layer): Pulls from Broker, checks Inbox for duplicates, and processes business logic idempotently.
We use standard SQL schemas. The design relies on unique constraints to handle concurrency and idempotency.
A. Outbox Table (Producer Side)
This table acts as a temporary holding buffer within the producer's database.
sql
CREATE TABLE outbox (
id UUID PRIMARY KEY, -- Random UUID to avoid hotspots
aggregate_type VARCHAR(50), -- e.g., "ORDER"
aggregate_id VARCHAR(50), -- e.g., "12345" (The Ordering Key)
event_type VARCHAR(50), -- e.g., "ORDER_CREATED"
payload JSONB NOT NULL,
status VARCHAR(20) DEFAULT 'PENDING', -- PENDING, SENT
created_at TIMESTAMP DEFAULT NOW(),
processed_at TIMESTAMP,
-- Index for the Relay to poll efficiently
INDEX idx_outbox_poll (status, created_at)
);
B. Inbox Table (Consumer Side)
This table ensures we never process the same event twice.
sql
CREATE TABLE inbox (
message_id UUID PRIMARY KEY, -- Matches Outbox ID
aggregate_id VARCHAR(50), -- For locking/ordering checks
status VARCHAR(20), -- RECEIVED, PROCESSED, FAILED
received_at TIMESTAMP DEFAULT NOW(),
processed_at TIMESTAMP,
-- Ensure we can check existence quickly
UNIQUE (message_id)
);
3. Design Feature: Ordering Keys
To maintain strict order (e.g., OrderCreated must happen before OrderShipped), we cannot simply process events in parallel globally. We must use Scoped Sequencing.
Key Definition: The combination of aggregate_type + aggregate_id forms the Partition Key.
The Relay Logic:
The Relay service queries the outbox table ordered by created_at.
It groups messages by the Partition Key.
Broker Routing: The Relay sends the message to a Message Broker (like Kafka or RabbitMQ) using the aggregate_id as the routing/partition key. This ensures all events for Order:123 land in the same partition.
Consumer Logic (Strict Order):
The consumer reads the partition sequentially.
DB Locking: Upon receiving a message, the Consumer issues a SELECT ... FOR UPDATE on the inbox table (or a dedicated lock table) specifically for that aggregate_id.
This creates a mutex. If OrderShipped arrives while OrderCreated is processing, it waits for the lock.
4. Design Feature: Retry Semantics
We assume the network is unreliable. We distinguish between Transient Failures (timeout, DB deadlock) and Permanent Failures (code bug, schema mismatch).
Producer Side (Relay)
Guarantee: At-least-once delivery to the Broker.
Mechanism: The Relay updates the Outbox row status to SENT only after the Broker acknowledges the write.
Failure: If the Broker is down, the Relay loop simply retries in the next polling interval (e.g., every 5s). The message stays in PENDING.
Consumer Side (Inbox)
Idempotency Check:
sql
INSERT INTO inbox (message_id, status, aggregate_id)
VALUES ($1, 'RECEIVED', $2)
ON CONFLICT (message_id) DO NOTHING;
If this returns 0 rows affected, we know the message is a duplicate (redelivery) and we ACK it immediately to the Broker.
Retry with Backoff:
If processing fails with a transient error:
NACK (Negative Acknowledgement) the message with a delay.
Use Exponential Backoff (e.g., 1s, 5s, 30s).
Dead Letter Queue (DLQ): If retries exceed a threshold (e.g., 5 attempts), move the message to a DLQ topic/table for human inspection. Do not block the queue indefinitely.
5. Design Feature: Fanout
Fanout occurs when one incoming event triggers actions in multiple downstream services. There are two ways to handle this in a durable pattern.
Approach A: Broker-Level Fanout (Standard)
The Producer writes one message to the Outbox. The Relay pushes it to a Topic. N consumers subscribe to that topic.
Pros: Simple producer.
Cons: No coordination between downstream services.
def consume_message(msg):
# 1. Idempotency Check
exists = db.query("SELECT 1 FROM inbox WHERE message_id = ?", msg.id)
if exists:
return Ack() # Already done, skip
# 2. Acquire Lock for Ordering Key (Wait if necessary)
# This ensures sequential processing for the same Order ID
lock = db.execute("SELECT * FROM inbox_locks WHERE agg_id = ? FOR UPDATE", msg.aggregate_id)
try:
# 3. Transactional Processing
db.begin_transaction()
# Mark as received (Inbox)
db.execute("INSERT INTO inbox (message_id, aggregate_id) VALUES (?, ?)", msg.id, msg.aggregate_id)
# Business Logic
process_order(msg.payload)
db.commit()
return Ack()
except TransientError as e:
db.rollback()
return Nack(delay=calculate_backoff())
except FatalError as e:
db.rollback()
send_to_dlq(msg)
return Ack() # Remove from queue, send to DLQ for manual fix
Summary of Guarantees
Durability: Messages are persisted in DB before any network calls (Outbox).
Ordering: Achieved by using aggregate_id as a partition key on the Broker and SELECT FOR UPDATE locking on the Consumer.
At-Least-Once Delivery: The Relay guarantees the message enters the Broker eventually.
Effective-Once Processing: The Inbox pattern ensures that even if a message is delivered twice, the logic runs only once.
Fanout: Handled either by standard Pub/Sub topics or by writing multiple distinct entries to the Outbox in a single transaction.