Skip to content
javahacks.dev
Microservices

Eventual Consistency Explained for Java Developers

Eventual consistency explained for Java developers: why it exists, read your writes problems, design patterns for UIs and APIs and how to handle conflicts.

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the OpenJDK, Postman, NGINX, Spring Boot and GraphQL logos.

A user places an order, the page redirects to "your orders", and the new order is not in the list. They refresh and it appears. Nothing is broken; the order was written to one place and the list reads from another that had not caught up yet. That gap is eventual consistency: a promise that if no new updates arrive, every copy of the data will converge to the same value, and no promise about when. Teams meet it the day they add a read replica, a cache, a search index, a message queue or a second service, and the bugs it causes are not exceptions. They are confused users and support tickets. This post explains where the gap comes from, shows a small event-driven example you can run, the patterns that make it manageable, how to design the screens around it, how to test it and when you must have strong consistency instead. Examples use Spring Boot 4 and Java 25.

Where it comes from

A single database with one writer and no copies is strongly consistent: once a transaction commits, every later read sees it. You lose that guarantee the moment the same fact lives in two places that are updated at different moments.

Source of copiesTypical delayWhat a reader may see
Read replicaMilliseconds to seconds under loadThe data before the latest commit
Cache with a TTLUp to the TTLA value that has already changed
Search index fed by eventsSecondsA document not yet indexed or already stale
Another service's projectionSeconds to minutesA summary built from older events
A message still in a queueAs long as the queue is backed upThe state before the message is processed

You choose this on purpose, to get availability, lower latency or independence between services, which is the trade at the heart of the CAP theorem for Java services. The cost is that you can no longer assume a read follows the writes you just made. Werner Vogels' essay Eventually Consistent is the classic statement of why large systems accept this.

An example

An order service writes orders and publishes an event. A separate read model, which could be another service, listens and keeps a per-customer summary for the "your orders" screen. Between the write and the update there is a window in which the two disagree.

The write side stores the order and emits an event in the same step:

src/main/java/dev/javahacks/orders/OrderService.javajava
@Service
class OrderService {

    private final OrderRepository orders;
    private final ApplicationEventPublisher events;

    OrderService(OrderRepository orders, ApplicationEventPublisher events) {
        this.orders = orders;
        this.events = events;
    }

    @Transactional
    public long place(long customerId, long totalCents) {
        Order saved = orders.save(new Order(customerId, totalCents));
        events.publishEvent(new OrderPlaced(saved.getId(), customerId, totalCents));
        return saved.getId();
    }
}

The read side updates its own table asynchronously, after the transaction has committed:

src/main/java/dev/javahacks/orders/CustomerSummaryProjection.javajava
@Component
class CustomerSummaryProjection {

    private final JdbcClient jdbc;

    CustomerSummaryProjection(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    @Async
    @TransactionalEventListener
    void on(OrderPlaced e) {
        jdbc.sql("""
                insert into customer_summary (customer_id, order_count, total_cents)
                values (:c, 1, :t)
                on conflict (customer_id)
                do update set order_count = customer_summary.order_count + 1,
                              total_cents = customer_summary.total_cents + :t
                """)
            .param("c", e.customerId())
            .param("t", e.totalCents())
            .update();
    }
}

@TransactionalEventListener runs only after the order transaction commits, so a rolled-back order never reaches the projection. @Async moves the handler to another thread, so the caller returns before the summary is updated. That return is the inconsistency window: for a few milliseconds the order exists and the summary does not. If the handler crashes, the summary stays behind forever, which is why real systems use a durable outbox and a broker, not an in-process event; the idempotent handling that makes redelivery safe is in duplicate messages and idempotent consumers.

You can watch the window. A test that reads immediately usually sees the old value:

java
long id = orders.place(7, 4999);
Integer countNow = jdbc.sql("select order_count from customer_summary where customer_id = 7")
        .query(Integer.class).optional().orElse(0);
System.out.println("right after place: " + countNow);
Text
right after place: 0

and a moment later it reads 1. The exact count you see depends on timing, which is the nature of the problem.

Patterns that help

You cannot remove the gap, but you can shrink its consequences.

Read your own writes. The one case users always notice is their own change. Serve the writer from the primary for a short period after they write, or return the created resource in the response of the write and let the client show it directly instead of re-reading a list. A session-scoped "last write" timestamp that routes reads to the primary for a few seconds is a common implementation.

Version numbers and conditional updates. Two writers acting on stale copies overwrite each other unless the update says which version it saw. Optimistic locking turns a lost update into a visible conflict; see optimistic locking with JPA:

java
@Entity
class Order {
    @Id @GeneratedValue Long id;
    @Version long version;     // update fails if someone else changed the row
}

Idempotent handlers. Events can be delivered twice. A handler that adds 1 to a counter must not double-count; key it by event id and ignore repeats.

Sagas for multi-step work. A business operation across services can no longer be one transaction. Break it into steps with compensations for the failures, as in the saga pattern in Java. The wider discussion of why the single big transaction is not available is in handling distributed transactions.

CQRS where the shapes differ. Writing one normalized model and reading another denormalized one is often what an eventually consistent design is for; Martin Fowler's page on CQRS covers when it earns its complexity and when it does not.

Convergence by reconciliation. A periodic job that compares the read model to the source and repairs differences catches the events that were lost. Count the repairs; a rising number means the pipeline has a defect.

Design the experience

Most eventual consistency pain is a user interface problem. Tell the user what is true now.

  • After a write, show the result locally and mark it as pending: "Order received, confirmation coming" instead of an empty list.
  • Show timestamps or "updated just now" on derived data, so staleness is visible.
  • Disable or hide actions whose preconditions may not yet hold, rather than failing after the click.
  • Prefer a status model (PLACED, CONFIRMED) over a boolean, so the in-between state has a name.
  • Make retries safe, so a user who clicks twice because nothing seemed to happen does not create two orders.

If a screen must be right, such as a payment confirmation, read from the authoritative source and accept the extra latency.

Test it

Race conditions make for flaky tests unless you handle the wait deliberately. Do not sleep for a guessed time; poll for the condition with a timeout using Awaitility:

java
@Test
void summaryCatchesUp() {
    orders.place(7, 4999);

    await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
        assertThat(summary.orderCountFor(7)).isEqualTo(1));
}

This states the contract honestly: the summary becomes correct within five seconds. Test the failure side too: kill the consumer, place orders, restart it and assert it catches up; deliver the same event twice and assert the count is 1; and measure the real lag in production as a metric (the age of the oldest unprocessed event), with an alert when it grows.

When you need strong consistency

Some operations cannot tolerate stale reads or concurrent divergence: debiting an account, reserving the last seat, checking a uniqueness constraint, enforcing a quota. Keep those inside one database transaction, with the right isolation level, or protect them with a unique constraint and a conditional update. Design the service boundaries so that data which must agree lives in the same service. If two services need to agree on one fact, one of them must own it and the other must ask, accepting a failure when the owner is unreachable.

When this does not apply

A single database with synchronous reads from the primary has no eventual consistency to design around. A small application with one server and an in-memory cache that is cleared on write does not need an event pipeline. And if your user base cannot see or care about a one-second delay, as with analytics dashboards or recommendation lists, accept the lag and spend the effort elsewhere. The cost of managing the gap grows with the number of copies, so keep them few.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.