Video in progress
A user creates an order and doesn't see it in the list, because the read model is updated late through Kafka. How do you solve the "read-your-writes" problem at the architecture level?
First I find out where you really need strong consistency, which is often only for the user who just wrote. Then I choose a solution: return the result in the write response, wait until the read model has caught up using a version or offset, or have that user read from the write database for a short time.
📖 Answer
In a CQRS and event-driven system this is unavoidable: the command service writes to the DB, the event goes through Kafka to the query service, which updates its own index. That usually takes 100-500 ms, and seconds under load. Meanwhile the user clicks "Save", jumps straight to the list, sees an empty spot, clicks again, and now there are two orders.
I order the options by cost:
-
Solve it on the UI side. The command response returns the fully created object, and the frontend adds it to the list itself (optimistic). Cheapest, and enough in most cases. An idempotency key protects against the duplicate click.
-
Wait with a version. The command response returns a
version(or the Kafka offset of the event). The query request comes withminVersion=17, and the query service waits briefly until its read model reaches that version:
@GetMapping("/orders")
List<OrderView> list(@RequestParam long customerId, @RequestParam(required = false) Long minVersion) {
if (minVersion != null) {
projection.awaitVersion(customerId, minVersion, Duration.ofSeconds(2)); // if it doesn't arrive: stale data + an "updating" marker
}
return views.findByCustomer(customerId);
}
This is precise and honest, but every projection has to track its own "where have I got to" state.
-
Routing by session. For N seconds after a write, that user's reads are served from the command service's own database. Simple, but two read paths means two sources of bugs.
-
A synchronous projection. The command service updates the read model in the same transaction, and Kafka is only for the other consumers. Strong consistency, but the boundary between services gets blurry.
There's an organizational side too: for each domain I write down, together with the product team, a list of "which screens can tolerate a delay". On a report page, 5 seconds bothers nobody, while on a payment status screen it means an immediate call to support. And I track the projection lag (end-to-end latency) as an SLO, so the problem shows up on the dashboard before the user sees it.
The worst solution is doing nothing because "it's fast anyway": on the first day the load goes up, it stops working.
Sign up to mark studied questions and save your progress.