Video in progress
An admin panel has to show orders, customer names and payment statuses in one table with filtering and pagination. How do you do it if the data lives in three different services?
API composition (querying each service and merging in memory) works at a small scale, but breaks with filtering and pagination on another service's field. In that case I build a separate read model (CQRS) assembled from events.
📖 Answer
The first attempt is usually like this: get 20 orders from order-service, then make batch requests to the other two services by their customerId and paymentId, and merge. It works as long as the page is sorted and filtered only by order fields.
The problem starts when the requirement is "orders whose payment is FAILED, with a customer name starting with 'Ali', by date, page 3". No single service can solve this on its own. Pulling everything into memory and filtering isn't feasible with 2 million orders. Fetching page by page from each service and merging gives wrong results (the page boundaries don't line up).
The read model approach:
@KafkaListener(topics = {"order-events", "customer-events", "payment-events"})
public void project(DomainEvent e) {
switch (e) {
case OrderCreated o -> view.upsertOrder(o);
case CustomerRenamed c -> view.updateCustomerName(c.customerId(), c.name());
case PaymentFailed p -> view.updatePaymentStatus(p.orderId(), "FAILED");
default -> { }
}
}
The admin-orders-view service keeps denormalized rows in its own table (or in Elasticsearch), and any filter becomes a single simple query.
The costs: the data lags by a few seconds; if an event is lost or there's a bug, the read model ends up wrong, so you need to be able to rebuild it from scratch (replay). A few seconds of delay usually isn't a problem for an admin, but agree on that with the business.
Sign up to mark studied questions and save your progress.