A pattern that ensures atomicity between database changes and message publishing in distributed systems. When business data changes, an event is stored in an Outbox table within the same transaction, and a separate process reads it and publishes it to the message broker. It solves the "Dual Write" problem and ensures data consistency.
How the pattern works: In a distributed system, writing to two systems at once, such as "updating the DB and then publishing a message to Kafka," is risky. If the DB commit succeeds but the Kafka publish fails, a data inconsistency occurs. The Outbox Pattern first stores the message in an outbox table in the DB (in a single transaction), and a separate process reads it and publishes it to the message broker with "at-least-once" delivery.
Usage scenarios: It is used for event-driven communication between microservices, for implementing Saga patterns such as order-payment-shipping, and for data synchronization based on CDC (Change Data Capture). It is used to safely publish an "order created event" when an order is created in e-commerce, or when a payment service publishes a payment completed event.
Advantages: Data consistency is guaranteed and no messages are lost. Even if the message broker fails, the messages remain stored in the outbox and can be recovered. Because it uses existing RDBMS transactions, it can be implemented in a familiar way. Instead of polling, real-time publishing is also possible with CDC tools such as Debezium.
Disadvantages: It requires an additional table and process (a poller or CDC). Messages may be published more than once, so the receiver must handle idempotency. If the outbox table grows large, performance degrades, so periodic cleanup is needed. Adopting a CDC tool increases operational complexity.
Using Debezium + Kafka Connect, you can detect the binlog/WAL without polling and publish events in real time. On AWS, a similar implementation uses DynamoDB Streams + Lambda, and on GCP, Cloud Spanner Change Streams.
💻 Code Example
# Outbox Pattern 구현 - Python + SQLAlchemy
from sqlalchemy import create_engine, Column, String, DateTime, Text, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import json
import uuid
import threading
import time
Base = declarative_base()
# Outbox 테이블 정의
class OutboxMessage(Base):
"""이벤트를 저장하는 Outbox 테이블"""
__tablename__ = 'outbox'
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
aggregate_type = Column(String(100), nullable=False) # e.g., 'Order'
aggregate_id = Column(String(100), nullable=False) # e.g., order_id
event_type = Column(String(100), nullable=False) # e.g., 'OrderCreated'
payload = Column(Text, nullable=False) # JSON 데이터
created_at = Column(DateTime, default=datetime.utcnow)
published = Column(Boolean, default=False)
published_at = Column(DateTime, nullable=True)
class Order(Base):
"""주문 도메인 모델"""
__tablename__ = 'orders'
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
customer_id = Column(String(100), nullable=False)
total_amount = Column(String(20), nullable=False)
status = Column(String(50), default='PENDING')
created_at = Column(DateTime, default=datetime.utcnow)
class OrderService:
"""주문 서비스 - Outbox 패턴 적용"""
def __init__(self, session_factory):
self.session_factory = session_factory
def create_order(self, customer_id: str, items: list, total_amount: float) -> Order:
"""
주문 생성 + 이벤트를 Outbox에 저장 (단일 트랜잭션)
"""
session = self.session_factory()
try:
# 1. 주문 생성
order = Order(
customer_id=customer_id,
total_amount=str(total_amount),
status='CREATED'
)
session.add(order)
# 2. Outbox에 이벤트 저장 (같은 트랜잭션!)
event_payload = {
'order_id': order.id,
'customer_id': customer_id,
'items': items,
'total_amount': total_amount,
'status': 'CREATED',
'created_at': datetime.utcnow().isoformat()
}
outbox_message = OutboxMessage(
aggregate_type='Order',
aggregate_id=order.id,
event_type='OrderCreated',
payload=json.dumps(event_payload)
)
session.add(outbox_message)
# 3. 단일 트랜잭션으로 커밋
# DB 저장과 이벤트 저장이 원자적으로 처리됨!
session.commit()
print(f"✅ 주문 생성 완료: {order.id}")
print(f"✅ Outbox 이벤트 저장: OrderCreated")
return order
except Exception as e:
session.rollback()
print(f"❌ 주문 생성 실패: {e}")
raise
finally:
session.close()
class OutboxPoller:
"""
Outbox 폴러 - 주기적으로 Outbox를 읽어 메시지 발행
실제 환경에서는 Debezium CDC 사용 권장
"""
def __init__(self, session_factory, message_publisher):
self.session_factory = session_factory
self.publisher = message_publisher
self.running = False
def start(self, poll_interval: float = 1.0):
"""폴링 시작"""
self.running = True
thread = threading.Thread(target=self._poll_loop, args=(poll_interval,))
thread.daemon = True
thread.start()
def stop(self):
self.running = False
def _poll_loop(self, interval: float):
while self.running:
self._process_outbox()
time.sleep(interval)
def _process_outbox(self):
session = self.session_factory()
try:
# 미발행 메시지 조회 (FOR UPDATE로 락)
messages = session.query(OutboxMessage).filter(
OutboxMessage.published == False
).order_by(OutboxMessage.created_at).limit(100).with_for_update().all()
for msg in messages:
try:
# 메시지 브로커로 발행
self.publisher.publish(
topic=f"{msg.aggregate_type.lower()}-events",
key=msg.aggregate_id,
value=msg.payload,
headers={
'event_type': msg.event_type,
'message_id': msg.id
}
)
# 발행 완료 표시
msg.published = True
msg.published_at = datetime.utcnow()
print(f"📤 이벤트 발행: {msg.event_type} ({msg.aggregate_id})")
except Exception as e:
print(f"❌ 발행 실패, 재시도 예정: {e}")
# 실패해도 다음 폴링에서 재시도
session.commit()
except Exception as e:
session.rollback()
print(f"❌ Outbox 처리 오류: {e}")
finally:
session.close()
# Kafka 발행자 예시
class KafkaMessagePublisher:
def __init__(self, bootstrap_servers: str):
from kafka import KafkaProducer
self.producer = KafkaProducer(
bootstrap_servers=bootstrap_servers,
value_serializer=lambda v: v.encode('utf-8') if isinstance(v, str) else v
)
def publish(self, topic: str, key: str, value: str, headers: dict = None):
header_list = [(k, v.encode()) for k, v in (headers or {}).items()]
self.producer.send(topic, key=key.encode(), value=value, headers=header_list)
self.producer.flush()
# 사용 예시
if __name__ == "__main__":
engine = create_engine('postgresql://localhost/orders')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
# 서비스 생성
order_service = OrderService(Session)
# 폴러 시작
publisher = KafkaMessagePublisher('localhost:9092')
poller = OutboxPoller(Session, publisher)
poller.start()
# 주문 생성 (DB + Outbox 원자적 저장)
order = order_service.create_order(
customer_id='CUST-001',
items=[{'product_id': 'PROD-1', 'quantity': 2}],
total_amount=50000
)
// Outbox Pattern - Node.js + Prisma + TypeScript
import { PrismaClient, Prisma } from '@prisma/client';
import { Kafka, Producer } from 'kafkajs';
import { v4 as uuidv4 } from 'uuid';
const prisma = new PrismaClient();
// Prisma 스키마 (schema.prisma)
/*
model Order {
id String @id @default(uuid())
customerId String
totalAmount Decimal
status String @default("PENDING")
createdAt DateTime @default(now())
}
model OutboxMessage {
id String @id @default(uuid())
aggregateType String
aggregateId String
eventType String
payload Json
published Boolean @default(false)
publishedAt DateTime?
createdAt DateTime @default(now())
@@index([published, createdAt])
}
*/
interface OrderCreatedEvent {
orderId: string;
customerId: string;
items: Array<{ productId: string; quantity: number }>;
totalAmount: number;
status: string;
createdAt: string;
}
class OrderService {
/**
* 주문 생성 - Outbox 패턴으로 이벤트 저장
*/
async createOrder(
customerId: string,
items: Array<{ productId: string; quantity: number }>,
totalAmount: number
) {
// Prisma 트랜잭션으로 원자성 보장
const result = await prisma.$transaction(async (tx) => {
// 1. 주문 생성
const order = await tx.order.create({
data: {
customerId,
totalAmount,
status: 'CREATED',
},
});
// 2. Outbox에 이벤트 저장 (같은 트랜잭션!)
const eventPayload: OrderCreatedEvent = {
orderId: order.id,
customerId,
items,
totalAmount,
status: 'CREATED',
createdAt: new Date().toISOString(),
};
await tx.outboxMessage.create({
data: {
aggregateType: 'Order',
aggregateId: order.id,
eventType: 'OrderCreated',
payload: eventPayload as unknown as Prisma.JsonObject,
},
});
console.log(`✅ 주문 생성: ${order.id}`);
console.log(`✅ Outbox 저장: OrderCreated`);
return order;
});
return result;
}
/**
* 주문 취소 - 상태 변경 + 이벤트 저장
*/
async cancelOrder(orderId: string, reason: string) {
return await prisma.$transaction(async (tx) => {
const order = await tx.order.update({
where: { id: orderId },
data: { status: 'CANCELLED' },
});
await tx.outboxMessage.create({
data: {
aggregateType: 'Order',
aggregateId: orderId,
eventType: 'OrderCancelled',
payload: {
orderId,
reason,
cancelledAt: new Date().toISOString(),
} as Prisma.JsonObject,
},
});
return order;
});
}
}
/**
* Outbox 폴러 - 미발행 메시지를 Kafka로 발행
*/
class OutboxPublisher {
private producer: Producer;
private isRunning = false;
constructor(kafkaBrokers: string[]) {
const kafka = new Kafka({
clientId: 'outbox-publisher',
brokers: kafkaBrokers,
});
this.producer = kafka.producer();
}
async start(pollIntervalMs: number = 1000) {
await this.producer.connect();
this.isRunning = true;
console.log('🚀 Outbox 폴러 시작');
while (this.isRunning) {
await this.processOutbox();
await this.sleep(pollIntervalMs);
}
}
async stop() {
this.isRunning = false;
await this.producer.disconnect();
}
private async processOutbox() {
// 미발행 메시지 조회 및 처리
const messages = await prisma.outboxMessage.findMany({
where: { published: false },
orderBy: { createdAt: 'asc' },
take: 100,
});
for (const msg of messages) {
try {
// Kafka로 발행
await this.producer.send({
topic: `${msg.aggregateType.toLowerCase()}-events`,
messages: [
{
key: msg.aggregateId,
value: JSON.stringify(msg.payload),
headers: {
eventType: msg.eventType,
messageId: msg.id,
},
},
],
});
// 발행 완료 표시
await prisma.outboxMessage.update({
where: { id: msg.id },
data: {
published: true,
publishedAt: new Date(),
},
});
console.log(`📤 발행: ${msg.eventType} (${msg.aggregateId})`);
} catch (error) {
console.error(`❌ 발행 실패: ${msg.id}`, error);
// 다음 폴링에서 재시도
}
}
}
private sleep(ms: number): Promise {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
/**
* Outbox 클리너 - 오래된 발행 완료 메시지 삭제
*/
async function cleanupOutbox(retentionDays: number = 7) {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
const result = await prisma.outboxMessage.deleteMany({
where: {
published: true,
publishedAt: { lt: cutoffDate },
},
});
console.log(`🧹 ${result.count}개 오래된 Outbox 메시지 삭제`);
}
// 사용 예시
async function main() {
const orderService = new OrderService();
// 주문 생성 (원자적으로 DB + Outbox 저장)
const order = await orderService.createOrder(
'customer-123',
[{ productId: 'prod-1', quantity: 2 }],
50000
);
// Outbox 폴러 시작 (별도 프로세스로 실행 권장)
const publisher = new OutboxPublisher(['localhost:9092']);
await publisher.start();
}
main();
// Debezium CDC를 사용한 Outbox Pattern
// 폴링 대신 DB 변경 로그(binlog/WAL)를 실시간 캡처
// 1. Outbox 테이블 생성 (PostgreSQL)
/*
CREATE TABLE outbox (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
aggregate_type VARCHAR(100) NOT NULL,
aggregate_id VARCHAR(100) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Debezium이 읽은 후 자동 삭제를 위한 인덱스
CREATE INDEX idx_outbox_created ON outbox(created_at);
*/
// 2. Debezium Connector 설정 (Kafka Connect)
{
"name": "outbox-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "debezium",
"database.password": "secret",
"database.dbname": "orders_db",
"database.server.name": "orders",
// Outbox 테이블만 캡처
"table.include.list": "public.outbox",
// Outbox 이벤트 라우터 사용
"transforms": "outbox",
"transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
// 토픽 라우팅 설정
"transforms.outbox.table.field.event.key": "aggregate_id",
"transforms.outbox.table.field.event.type": "event_type",
"transforms.outbox.table.field.event.payload": "payload",
"transforms.outbox.route.by.field": "aggregate_type",
"transforms.outbox.route.topic.replacement": "${routedByValue}-events",
// 발행 후 레코드 삭제 (선택사항)
"transforms.outbox.table.expand.json.payload": "true",
// 스냅샷 설정
"snapshot.mode": "initial",
// 오프셋 저장
"offset.storage.topic": "debezium-offsets",
"offset.flush.interval.ms": "1000"
}
}
// 3. 결과: aggregate_type에 따라 자동으로 토픽 생성
// - Order → order-events 토픽
// - Payment → payment-events 토픽
// 4. Kafka Consumer에서 이벤트 수신
/*
{
"key": "order-12345",
"value": {
"orderId": "order-12345",
"customerId": "cust-001",
"totalAmount": 50000,
"status": "CREATED",
"createdAt": "2024-01-15T10:30:00Z"
},
"headers": {
"id": "msg-uuid-xxx",
"eventType": "OrderCreated"
}
}
*/
// 5. Docker Compose 예시
/*
version: '3.8'
services:
zookeeper:
image: confluentinc/cp-zookeeper:7.5.0
environment:
ZOOKEEPER_CLIENT_PORT: 2181
kafka:
image: confluentinc/cp-kafka:7.5.0
depends_on:
- zookeeper
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
connect:
image: debezium/connect:2.4
depends_on:
- kafka
- postgres
environment:
BOOTSTRAP_SERVERS: kafka:9092
GROUP_ID: outbox-connect
CONFIG_STORAGE_TOPIC: connect-configs
OFFSET_STORAGE_TOPIC: connect-offsets
STATUS_STORAGE_TOPIC: connect-status
ports:
- "8083:8083"
postgres:
image: postgres:15
environment:
POSTGRES_USER: debezium
POSTGRES_PASSWORD: secret
POSTGRES_DB: orders_db
command:
- "postgres"
- "-c"
- "wal_level=logical" # CDC 필수 설정
*/
// 6. Connector 등록 API 호출
/*
curl -X POST http://localhost:8083/connectors \
-H "Content-Type: application/json" \
-d @outbox-connector.json
*/
🗣️ Say It Like This in Practice
💬 When designing an event-driven architecture
"If you create an order and publish directly to Kafka, you get a Dual Write problem. If Kafka fails after the DB commit, the event is lost. If you store the event in the same transaction using the Outbox pattern, and Debezium reads it via CDC and publishes it, at-least-once delivery is guaranteed."
💬 When discussing duplicate message handling
"The Outbox pattern is at-least-once, so messages can be published more than once. The receiver side must handle idempotency using message_id. If you use the Inbox pattern together with it, the receiving side can also guarantee duplicate handling at the DB level."
💬 When discussing Outbox table management
"If the Outbox table keeps accumulating, performance drops. Run a batch job that deletes published records after keeping them for about 7 days. Or, if you turn on Debezium's delete mode, records are deleted automatically after capture."
⚠️ Cautions & Best Practices
❌
Message order is not guaranteed
If multiple instances poll, the order can get mixed up. If order matters, partition by aggregate_id or use a single poller.
❌
Outbox table bloat
If you do not delete published records, the table grows and query performance degrades. Be sure to implement a periodic cleanup (retention) policy.
❌
Duplicate messages not handled
Because publishing is at-least-once, if the receiver does not handle duplicates, the data gets corrupted. Apply message_id-based idempotency or the Inbox pattern.
✅
Outbox Pattern Best Practices
Use CDC (Debezium) for real-time publishing, idempotency via message_id, cleanup of published records, and detection of unpublished messages through monitoring.