Skip to main content
InterviewHubPRO
Section Overview
Q21

Question 21 of 50

Part 3: Advanced Architecture & Production Patterns (Senior / Lead)

42%
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:

  1. When saving an Aggregate, the Repository extracts all uncommitted domain events recorded by the aggregate.
  2. In the same atomic database transaction, it writes the aggregate row AND inserts the events into an outbox table.
  3. 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()
      });
    }
  });
}