Sub topic 10
Living with eventual consistency
This chapter assumes you know what events, producers, consumers and brokers are, and that you understand local database transactions. It builds on the earlier chapters on delivery guarantees and idempotent consumers.
What eventual consistency means
A system is eventually consistent if, when no new updates arrive, every copy of the data converges to the same value. The guarantee says nothing about when. Between the moment one service changes its state and the moment every consumer has reacted, the system holds copies that disagree. That period is the inconsistency window.
Event-driven systems have this window by design. A producer commits its change and publishes an event. The broker stores it and delivers it later. Each consumer processes it on its own schedule, so each one updates its own data at a different time.
Compare this with a single database transaction. There, other readers see either the old state or the new state, never a mix. Across services, you give up that guarantee in exchange for independent deployment, independent failure and independent scaling.
Where the window comes from
Several separate delays add up to the window:
- Publishing delay. With the outbox pattern, the event waits for the relay to pick it up.
- Broker delay. Events queue up behind others in the same partition.
- Consumer lag. A slow or busy consumer falls behind the head of the log.
- Retries. A failed event is retried with backoff, and a poison message may sit in a dead-letter queue until someone acts.
- Rebalancing and restarts. Consumers pause while partitions are reassigned.
Normally the window is milliseconds. During an incident it can be hours. Design for the bad case, not the average.
Common errors
These mistakes appear again and again in event-driven systems.
- Reading your own write from a read model. A user submits a form, is redirected to a list page, and their item is missing. The write went to the write store and the list comes from a projection that has not caught up.
- Check-then-act across services. Service A reads service B's replicated data to check a rule, such as "customer is not blocked", and then acts. The replica may be stale, so the rule can be violated.
- Assuming cross-service ordering. Events from different producers or partitions have no global order. A consumer may see
order.shippedfrom one service beforepayment.capturedfrom another. - Treating "published" as "done". The producer returned success, but nothing downstream has happened yet.
- Hiding the lag. Nobody measures the window, so users discover it before the team does.
Techniques for read-your-writes
When a user must see the effect of their own action, you have several options. None of them removes the window. They only stop the user from noticing it.
| Technique | How it works | Cost |
|---|---|---|
| Return the result in the command response | The write service returns the new state, and the client shows it directly | Client may show data that differs from the later read model |
| Optimistic UI | The client assumes success and renders the change locally, then reconciles | Needs rollback handling for failures |
| Version token | The write returns a version. The read waits until the read model reaches that version | Reads can block or time out |
| Read from the write store | Route this one query to the source of truth | Couples the query to the writer and adds load |
| Show a pending state | The UI says "processing" and polls or receives a push update | Honest, but the user must wait |
The version token approach is easy to implement and works well for a single aggregate. The example below simulates it with a queue and a background projector.
import queue
import threading
import time
events = queue.Queue()
write_store = {} # source of truth
read_model = {} # eventually consistent projection
def projector():
while True:
event = events.get()
if event is None:
break
time.sleep(0.3) # simulated consumer lag
read_model[event["order_id"]] = {
"status": event["status"],
"version": event["version"],
}
def place_order(order_id):
version = write_store.get(order_id, 0) + 1
write_store[order_id] = version
events.put({"order_id": order_id, "status": "placed", "version": version})
return version # the client keeps this as a token
def get_order(order_id, min_version=0, timeout=2.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
row = read_model.get(order_id)
if row is not None and row["version"] >= min_version:
return row
time.sleep(0.05)
return None # still stale after the timeout
worker = threading.Thread(target=projector, daemon=True)
worker.start()
token = place_order("o-1")
print("immediate read:", read_model.get("o-1")) # None: stale
print("read with token:", get_order("o-1", min_version=token))
events.put(None)
worker.join()The first read returns None because the projector has not run yet. The second read waits until the projection reaches the version the write returned. The timeout matters. If the projector is down, an unbounded wait would hang the request, so the function gives up and the caller must decide what to show.
Protecting invariants
Some rules must never be broken, such as "a bank account never goes below zero" or "a seat is sold once". Eventual consistency makes these hard to enforce across services. Use these approaches, roughly in order of preference:
- Keep the invariant inside one transaction boundary. Put the data that must agree in the same service and database. If two pieces of data share a strict rule, they probably belong together.
- Reserve, then confirm. Make the scarce resource a first-class step. A "reserve stock" command succeeds or fails atomically in the owning service, and later events confirm or release the reservation.
- Allow the violation and compensate. Accept that two orders may claim the last item, then cancel or refund one. Airlines overbook for the same reason. This works when the business can tolerate and fix the error.
- Use a saga. When a process spans services, coordinate it with explicit steps and compensating actions. A later chapter covers sagas.
Designing for stale reads
Some staleness is harmless and does not need any technique. Product listings, dashboards and recommendation lists tolerate a few seconds of delay. For each read path, decide how stale is acceptable and write it down. Two questions help:
- What is the worst thing that happens if the user sees data that is a minute old?
- What does the user do next, and does that action depend on this read being fresh?
If the answer to the second question is "they act on it", look at the action. Make the action itself safe by checking versions. For example, an update that carries expectedVersion fails cleanly if the state has moved on, which is optimistic concurrency control.
Make events safe to apply out of order when you cannot control ordering. Compare version numbers or timestamps from the event against what you have stored, and ignore older ones. This is a last-writer-wins rule based on the event's version, not on arrival time.
def apply_status_event(store, event):
current = store.get(event["order_id"])
if current is not None and current["version"] >= event["version"]:
return False # older or duplicate event: ignore
store[event["order_id"]] = {
"status": event["status"],
"version": event["version"],
}
return True
store = {}
apply_status_event(store, {"order_id": "o-1", "status": "shipped", "version": 3})
apply_status_event(store, {"order_id": "o-1", "status": "placed", "version": 1})
print(store["o-1"]) # still shipped, version 3This also makes the handler idempotent, because a redelivered event carries a version that is already applied.
Measuring the window
You cannot manage a delay you do not measure. Track these signals:
- Consumer lag, the number of events or seconds between the newest event in a partition and the last one the consumer processed.
- End-to-end latency, the time from the event's
occurredAtto the moment a consumer finishes handling it. - Age of the oldest unpublished outbox row.
- Dead-letter queue depth.
Alert on the age of the oldest unprocessed event more than on raw counts. A queue of 10,000 events that drains in a second is healthy. A queue of 10 that has not moved for an hour is not.
Communicating with users
Eventual consistency is a product decision as much as a technical one. Honest wording helps: "Your order was received" is accurate, while "Your order is confirmed" may not be yet. Confirmation emails, status pages and "last updated" timestamps all tell users how fresh the data is. A system that is slightly stale and says so is easier to trust than one that looks instant and is sometimes wrong.
Exercise
A user updates their shipping address and is redirected to a profile page that still shows the old address. The profile page reads from a projection fed by address.changed events. Name two ways to fix what the user sees, and say what each costs.
Show answer
Option 1: return the new address in the update response and have the client render it (or use optimistic UI). It is simple, but the client's view can differ from the projection until it catches up. Option 2: return a version token from the update and have the profile read wait until the projection reaches that version, with a timeout. It shows correct data, but the read can block or time out if the consumer is lagging. Reading directly from the write store also works, but it couples the query to the writer and adds load.
Exercise
A consumer receives status = shipped (version 3) and then, because of a retry, status = placed (version 1). What should it do with the second event, and why does this also protect against duplicate delivery?
Show answer
It should ignore the second event, because the stored version (3) is already greater than or equal to the event's version (1). The same check ignores a redelivered event with a version that has already been applied, so the handler is idempotent without a separate list of processed IDs.