Video in progress

After moving to microservices, how do you build queries and reports that combine data from several services, like "all of a customer's orders, payments and shipments"?

There are three ways: combine by calling services at query time (API composition), a separate read model built from events (a projection), and a data warehouse. Composition for small interactive views, a projection for complex filters, the warehouse for reports; connecting directly to another team's DB is not an option.

📖 Answer

In the monolith this was a single JOIN. Now orders, payments and shipments are three databases owned by three teams. The easiest and worst way is to connect the reporting service read-only to all the databases. A year later the payments team renames a column and the report breaks silently, and your heavy query slows down their prod database.

  1. API composition. A BFF or a dedicated service calls all three services in parallel at query time and merges in memory.
  • good: small volume, a single customer page, always-fresh data;
  • bad: "orders that are paid but not delivered, sorted by date": the filter depends on fields in several services, and you can't paginate in memory. And availability is the product of all three services.
  1. A projection. The reporting service listens to OrderPlaced, PaymentCaptured, ShipmentDelivered events and keeps a denormalized table in its own database. Filtering, sorting and pagination are plain SQL. The cost:
  • eventual consistency: a few seconds of stale state after a payment;
  • events can arrive out of order (a shipment before its order), so write with upserts and versions;
  • you must be able to rebuild the projection from scratch: events are kept long enough, or services provide snapshots.
  1. An analytical warehouse. Tables flow into ClickHouse or BigQuery through CDC, and reports are SQL. Best for finance and management, not for the customer page. One catch: CDC exposes the service's internal schema, so you need an "external schema" contract: outbox events or dedicated views.

How to choose: by who needs the query and how fresh the data must be. The customer's "my orders" page is a projection, with a read-your-writes patch for a new order (the client puts what it just created at the top of the list itself). An operator panel is composition. The monthly report is the warehouse.

If you have a lot of this kind of joining, that's a signal: the service boundaries may have been drawn wrong, and maybe orders and shipments are really one bounded context.