Domain-Driven Design (50 Qs)•Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
How do you implement the Outbox Pattern with Domain Events in production?
senior LevelCode ExampleSystem Design
In Simple Words: To ensure Domain Events are never lost if the message broker is unreachable:
- When saving an Aggregate, the Repository extracts all uncommitted domain events recorded by the aggregate.
- In the same atomic database transaction, it writes the aggregate row AND inserts the events into an
outboxtable. - A background process (or Debezium CDC) streams events from the outbox table to Kafka/RabbitMQ and marks them published.
typescript
// Inside Transactional Repository:
async save(order: Order): Promise<void> {
await this.db.transaction(async (trx) => {
await trx('orders').insert(order.toRow());
for (const event of order.pullDomainEvents()) {
await trx('outbox').insert({
event_type: event.constructor.name,
payload: JSON.stringify(event),
created_at: new Date()
});
}
});
}