Eventual Consistency

Eventual Consistency

When two pieces of state can't share a transaction, they can only be eventually consistent: there is a window during which they're out of sync. EDA makes this window explicit; ignoring it is a bug.

Strong vs eventual

Strong consistency Eventual consistency
Transactional One DB, one tx Multiple DBs or async tx
Read after write Always sees latest May see stale (briefly)
Failure model Tx aborts, rollback Retries, compensations
Performance Limited by single-tx scope Scales horizontally
Complexity Hidden by DB Explicit

You can't have both across multiple aggregates / bounded contexts / services. Pick deliberately.

Where it shows up

The trade

You give up:

You gain:

Patterns for handling it

Outbox

Write the event to an outbox table in the same transaction as the state change. A separate worker dispatches from the outbox.

async def place_order(cmd):
    async with uow:
        order = Order.new(cmd)
        await orders.save(order)
        await outbox.add(order.pull_events())
        await uow.commit()

async def dispatch_loop():
    while True:
        events = await outbox.fetch_pending(limit=100)
        for e in events:
            await bus.publish(e)
            await outbox.mark_done(e.id)
        await asyncio.sleep(0.1)

Guarantees: if the state change committed, the event will eventually be published.

Idempotent subscribers

Subscribers will see the same event more than once (broker redelivery, dispatch retry). Each subscriber must handle duplicates safely. Two common strategies:

  1. Idempotency key. Subscriber stores (event_id, subscriber_name) after processing. Skips if already seen.
  2. Idempotent operation. "Set quantity to 5" is idempotent; "subtract 1" is not. Prefer the former for handlers.

Compensation (Saga)

Long-running workflow across aggregates. If step N fails, run compensating actions for steps 1..N-1. No global rollback; explicit undo:

Place order -> Reserve stock -> Capture payment
                                       v fail
                            Release stock
                            Cancel order

Versioning

Two services, both deriving state from an event. Producer adds a field; consumer is on older schema. Versioning the event lets both deploy independently.

Reading the "in-between"

What does a user see during the eventual-consistency window?

UX strategies:

Anti-patterns

The hardest part

Telling product/UX/support that "it'll show up in a few seconds" is the default, not a bug. Once accepted, EDA + eventual consistency simplifies most cross-boundary problems. Until accepted, every consistency-window report looks like a bug.