Skip to main content

The Outbox Pattern — How to Stop Losing Events When Your Database and Message Broker Disagree

TL;DR — Writing to a database and publishing to RabbitMQ in two separate steps is a ticking time bomb. The Outbox Pattern eliminates this risk by making your database the single source of truth for all outgoing events.

Updated 8 min readMarkdown

The Problem Nobody Talks About Until Production Burns

You've built a clean microservice. The flow looks beautiful on paper:

  1. Order is placed

  2. Save to DB

  3. Publish event to RabbitMQ

  4. Downstream services react

Until your RabbitMQ publish fails after the DB commit.

Or your service crashes between the two calls. Or the broker is down for 3 seconds during a deploy.

Now your database says the order exists — but no event was ever published. Your inventory service never decremented stock. Your email service never sent a confirmation. Your analytics pipeline missed the event entirely.

Welcome to the dual-write problem — the silent killer of distributed systems.

Two separate I/O operations — one to your database, one to your message broker — with no atomic guarantee between them.


Why You Can't Just Wrap It in a Try-Catch

A naive fix looks like this:

orderRepository.save(order);         // DB write
rabbitTemplate.convertAndSend(       // RabbitMQ publish
    "orders.exchange",
    "order.created",
    event
);

The problem? These are two completely independent systems. If the broker is temporarily unreachable, you're stuck choosing between two bad options:

Option What Happens
Skip the event Silent data loss — downstream never knows
Retry blindly Risk of double-publishing if first attempt went through

There's no rollback for a message already sent. And there's no "undo" for a DB commit when the broker times out afterward.

This isn't a code bug. It's an architectural gap.


The Outbox Pattern: Make the DB the Source of Truth

The core idea is elegant:

Treat your message broker as an eventual consumer, not a synchronous dependency.

Instead of publishing to RabbitMQ directly, you write the event into an outbox table in the same DB transaction as your business data. One atomic commit. Then, a separate relay process reads from that table and publishes to RabbitMQ asynchronously.

How the flow looks:

┌─────────────────────────────────────────┐
│           Application Service           │
│                                         │
│   BEGIN TRANSACTION                     │
│     INSERT INTO orders (...)       ───┐ │
│     INSERT INTO outbox_events (...) ──┘ │  ← same atomic transaction
│   COMMIT                                │
└──────────────────┬──────────────────────┘
                   │
         ┌─────────▼──────────┐
         │   Outbox Relay /   │
         │   Polling Process  │
         └─────────┬──────────┘
                   │  publishes
         ┌─────────▼──────────┐
         │      RabbitMQ      │
         │   (Exchange/Queue) │
         └────────────────────┘

If the DB commit succeeds → event will eventually be published.
If the DB commit fails → event is never written, nothing to publish.

The broker is now completely decoupled from your critical write path. 🎯


🗃️ The Outbox Table Schema

CREATE TABLE outbox_events (
    id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    aggregate_type VARCHAR(100) NOT NULL,   -- e.g., 'Order', 'Payment'
    aggregate_id   VARCHAR(100) NOT NULL,   -- e.g., the order UUID
    event_type     VARCHAR(100) NOT NULL,   -- e.g., 'ORDER_CREATED'
    payload        JSONB        NOT NULL,   -- the full event body
    status         VARCHAR(20)  NOT NULL DEFAULT 'PENDING',
    created_at     TIMESTAMP    NOT NULL DEFAULT NOW(),
    published_at   TIMESTAMP
);

-- Index for the relay to efficiently poll pending events
CREATE INDEX idx_outbox_status_created 
    ON outbox_events(status, created_at);

Writing to the Outbox (Same Transaction as Business Logic)

@Transactional
public Order placeOrder(CreateOrderRequest request) {

    // 1. Business logic — save the order
    Order order = orderRepository.save(
        Order.builder()
            .customerId(request.getCustomerId())
            .totalAmount(request.getTotal())
            .status(OrderStatus.CONFIRMED)
            .build()
    );

    // 2. Write event to outbox — SAME transaction, not RabbitMQ
    OutboxEvent event = OutboxEvent.builder()
        .aggregateType("Order")
        .aggregateId(order.getId().toString())
        .eventType("ORDER_CREATED")
        .payload(objectMapper.valueToTree(new OrderCreatedEvent(order)))
        .status("PENDING")
        .build();

    outboxEventRepository.save(event);

    // Both writes commit together, or both roll back together ✅
    return order;
}

Note: No RabbitMQ call anywhere in this method. If the transaction rolls back for any reason, the outbox event is also rolled back. Clean and atomic.


📡 The Relay Process: Two Approaches

Approach 1 — Polling Relay (Simple, Great for Most Cases)

A scheduled job queries for PENDING events and publishes them:

@Component
@RequiredArgsConstructor
public class OutboxEventRelay {

    private final OutboxEventRepository outboxRepo;
    private final RabbitTemplate rabbitTemplate;
    private final ObjectMapper objectMapper;

    @Scheduled(fixedDelay = 5000) // runs every 5 seconds
    @Transactional
    public void publishPendingEvents() {

        List<OutboxEvent> pendingEvents = outboxRepo
            .findTop50ByStatusOrderByCreatedAtAsc("PENDING");

        for (OutboxEvent event : pendingEvents) {
            try {
                rabbitTemplate.convertAndSend(
                    event.getAggregateType().toLowerCase() + ".exchange",
                    event.getEventType().toLowerCase(),
                    event.getPayload().toString()
                );

                event.setStatus("PUBLISHED");
                event.setPublishedAt(Instant.now());
                outboxRepo.save(event);

            } catch (Exception ex) {
                // Log and leave as PENDING — will retry next cycle
                log.error("Failed to publish outbox event {}: {}", event.getId(), ex.getMessage());
            }
        }
    }
}

Pros:

  • Simple to implement

  • No additional infrastructure

  • Works perfectly at moderate scale

Cons:

  • Slight latency (up to 5 seconds per the example above)

  • DB polling adds some load at high throughput


Approach 2 — Change Data Capture with Debezium (For Higher Scale)

At higher scale, you don't poll — you listen to the database's Write-Ahead Log (WAL) using Debezium.

Postgres WAL → Debezium Connector → Kafka / RabbitMQ

Every INSERT into outbox_events is streamed in near real-time without any polling overhead. Debezium even supports a dedicated Outbox Event Router SMT (Single Message Transform) that flattens the event directly into your exchange/topic.

Polling Relay Debezium CDC
Latency Seconds Milliseconds
Infrastructure None extra Kafka + Debezium
Complexity Low Moderate–High
Scale Moderate High
Best for Startups, early stage High-throughput systems

Start with polling. Migrate to CDC when your event volume actually justifies the ops overhead.


Handling At-Least-Once Delivery

The Outbox Pattern guarantees at-least-once delivery — meaning if your relay crashes mid-publish, the same event might be published again on the next cycle.

This is expected and fine, as long as your consumers are idempotent — i.e., they safely ignore or skip duplicate events.

@RabbitListener(queues = "inventory.order-created")
@Transactional
public void handleOrderCreated(String payload) {

    OrderCreatedEvent event = objectMapper.readValue(payload, OrderCreatedEvent.class);

    // Idempotency check — skip if already processed
    if (processedEventRepository.existsById(event.getEventId())) {
        log.info("Duplicate event {} — skipping", event.getEventId());
        return;
    }

    // Process the event
    inventoryService.decrementStock(event.getOrderItems());

    // Mark as processed
    processedEventRepository.save(new ProcessedEvent(event.getEventId()));
}

Rule of thumb: Events should carry a stable eventId. Consumers track which IDs they've already handled.


Before vs After

Concern Without Outbox With Outbox
Atomicity of DB write + event publish No guarantee Single transaction
Event loss on broker downtime Yes, silently Queued in DB, retried
Service crash between DB and broker Lost forever Relay picks it up
Duplicate event risk Possible Managed via idempotency
Audit trail of all events None Full history in outbox table
Complexity Low Moderate

When Should You Use This?

Use the Outbox Pattern when:

  • Your service writes to a DB and publishes events to RabbitMQ / Kafka

  • You cannot afford silent event loss (orders, payments, inventory, notifications)

  • Downstream services depend on your events to do critical work

  • You're in a microservices or event-driven architecture

You probably don't need it if:

  • You're in a monolith with in-process event handling

  • You're using XA/distributed transactions (though those come with their own pain)

  • Your events are truly fire-and-forget with no downstream impact


Key Takeaways

1. The dual-write problem is real and it will bite you in production.

2. The Outbox Pattern solves it by making your DB the single source of truth for outgoing events.

3. Start with a polling relay — it's simple, effective, and good enough for most teams.

4. Design consumers to be idempotent — at-least-once delivery is a feature, not a bug.

5. Migrate to Debezium CDC only when polling becomes a bottleneck.


The Outbox Pattern won't make your system perfectly consistent — distributed systems don't work that way. But it gives you a reliable, auditable event trail and eliminates the most common source of silent data loss in event-driven architectures.

If this helped, drop a reaction and share it with someone building microservices. And if you're using a different approach for reliable event publishing — I'd love to hear about it in the comments below.


Tags: #SystemDesign #Microservices #RabbitMQ #Java #SpringBoot #EventDrivenArchitecture #DistributedSystems #BackendDevelopment

No comments yet. Be the first to comment.