Eventual Consistency — Real World Patterns

Eventual consistency means that replicas or services converge to the same state over time. It is a pragmatic tradeoff that enables high availability and scalability but requires careful design to avoi

Eventual Consistency — Real World Patterns#

Eventual consistency means that replicas or services converge to the same state over time. It is a pragmatic tradeoff that enables high availability and scalability but requires careful design to avoid user-visible anomalies.

Where Eventual Consistency Appears#

  • Multi-region databases with asynchronous replication.
  • Microservices that communicate via events.
  • CQRS systems with separate read and write models.

Core Patterns#

1. Outbox Pattern#

Write domain changes and integration events in the same transaction, then publish the events asynchronously. This prevents lost updates and ensures reliable propagation.

2. Saga with Compensations#

Sagas allow a chain of local transactions with compensating actions to reconcile failures.

3. Read Model Projections#

Materialize a query-friendly read model from event streams. This is a common way to provide low-latency reads while preserving eventual consistency.

Spring Boot Example with Outbox#

1
2
3
4
5
6
@Entity
public class Order {
    @Id
    private String id;
    private String status;
}
1
2
3
4
5
6
7
@Entity
public class OutboxEvent {
    @Id
    private String id;
    private String aggregateId;
    private String payload;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Service
public class OrderService {
    private final OrderRepository orderRepository;
    private final OutboxRepository outboxRepository;

    public OrderService(OrderRepository orderRepository, OutboxRepository outboxRepository) {
        this.orderRepository = orderRepository;
        this.outboxRepository = outboxRepository;
    }

    @Transactional
    public void confirmOrder(String orderId) {
        Order order = orderRepository.findById(orderId).orElseThrow();
        order.setStatus("CONFIRMED");
        orderRepository.save(order);
        outboxRepository.save(OutboxEvent.from(order));
    }
}

Managing User Expectations#

  • Provide status fields like PENDING, CONFIRMED, FAILED.
  • Use notifications or webhooks to signal final state.
  • Offer read-your-writes within a session when possible.

Monitoring Consistency Lag#

Track lag metrics:

  • Event processing delay.
  • Read model staleness.
  • Replication lag in multi-region stores.

Summary#

Eventual consistency is not a single technique but a collection of patterns that trade immediacy for resilience. Outbox, sagas, and projection-based read models make eventual consistency practical and observable.

Contents