Queries: API composition and CQRS
Each FTGO service keeps its data private, so a screen that shows an order's status, ticket, courier and payment can no longer be one SQL join. This chapter shows how to answer such queries: ask each owner and combine the answers, or keep a ready-made view up to date from events.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 10 we stored aggregates as events: full history, and reliable publishing as part of every save. That left one problem open: an event store can load one aggregate by id, but it cannot filter or sort, and many FTGO screens need data that lives in several services at once.
How do you answer a query that spans services, each with a private database? By the end you can implement a query with API composition, recognize when it breaks down, build and maintain a CQRS view, choose its database, and decide where (and whether) to cache.
One screen, four owners: API composition
A customer opens the Order Status screen for order 101. It shows the order and its status (Order Service), when the kitchen expects it to be ready (Kitchen Service), the courier and arrival time (Delivery Service) and whether the card was charged (Accounting). In the monolith, findOrder(orderId) was one SELECT with joins. Now each piece sits in a private database that no other service may read.
Put an API composer in front of the services. It calls every service that owns part of the answer through its API, then joins the results in memory and returns one response.
Who plays the composer? A web app that runs inside FTGO's network can do it itself, because calls on a fast LAN are cheap. For mobile apps and external clients, the API gateway is a better place (the subject of chapter 12). A query that is used internally, or that has complex logic, can get its own small composer service.
API composition is simple to understand and needs no extra database. That makes it the first thing to try. Its costs show up in the figure below.
One query becomes five calls (composer plus four providers). If each is 99.5% available, the query is only about 97.5% available, so the composer should fall back to cached or partial data when one provider is down. The answers can also disagree: Order Service may already say CANCELLED while Kitchen Service still shows an open ticket. And this works only while each provider can find its part quickly by id.
When composition is not enough: filters, joins and the wrong owner
The Order Status screen is small and centered on one id. Screens that filter and sort across services are a different story.
The Order History screen calls findOrderHistory(consumerId, filter): a consumer's orders, filtered by a keyword such as "pizza" and by status, sorted by date, one page at a time. Only Order Service knows the menu items. Delivery and Accounting do not even store them, so they cannot filter by keyword. The composer must pull large lists from every service and join them in memory. And the "find available restaurants near me" query needs a geospatial index that Restaurant Service's database may not offer, and that its team should not have to run.
A side example shows how fast this gets out of hand. An online shop keeps products, prices and stock in three services, and a listing page wants "clothing under $50, in stock". The composer asks Product Service for six clothing items, finds that Pricing Service has only two under $50, asks for six more, and repeats until the page is full.
Composition is fine for small data centered on one id, such as an order detail page. For filters, sorting and paging across services it means many calls, big in-memory joins and slow pages. And some queries need a kind of database that no owner has. The answer must be prepared before the query arrives.
Keep a ready-made view: CQRS
If joining at read time is too slow, join at write time instead, as the data changes.
Use one model to change the data and a separate model to answer queries. The command side owns the data and publishes domain events. The query side subscribes to those events and keeps a read-only view, a replica already shaped for its queries.
For FTGO, a query-only Order History Service subscribes to events from Order, Kitchen, Delivery and Accounting. Its handlers write one pre-joined record per order. Both findOrderHistory() and findOrder() then become one fast read, with no in-memory join and no calls to other services.
The online shop from the side example gets the same fix. A read model handles the events of Product, Pricing and Inventory and keeps a denormalized, searchable list ready for the listing page. A new filter or a new screen becomes another view built from the same streams.
CQRS is also how an event-sourced service from chapter 10 answers anything beyond "load by id". The two patterns side by side:
Another service and another database to build and run, and a view that always trails the writes a little. The team must also decide what kind of database each view lives in.
Let the queries pick the view database
A view exists for its queries, so the queries, not habit, should decide its store.
FTGO's views ask very different questions. Order History looks up one order by id and lists a consumer's orders by date. A keyword search over past orders needs full-text matching. "Available restaurants near me" needs a geospatial index. One general-purpose database would serve some of these badly.
Pick the store that answers this view's queries best. Many views only need updates and lookups by id, which suits NoSQL stores; keep a relational database for views that need SQL reporting.
| If the view needs… | Use a… | Examples |
|---|---|---|
| Look up a JSON object by id | Document or key-value store | MongoDB, DynamoDB, Redis |
| Query JSON objects by fields | Document store | MongoDB, DynamoDB |
| Text search | Search engine | Elasticsearch |
| Graph queries (fraud) | Graph database | Neo4j |
| SQL reporting / BI | Relational database | PostgreSQL, MySQL |
A worked case: FTGO's Order History view on DynamoDB. Each event handler, for example the one for OrderCreated, calls a data access object, OrderHistoryDao. The DAO writes with a conditional UpdateItem, so one item per order is changed only when the update makes sense. A secondary index on consumer id plus creation time returns each consumer's history already sorted.
Each new kind of store is one more technology to operate. And whichever store you pick, it is fed by events that can arrive twice, arrive in parallel, and arrive after the user has already looked.
Keeping the view correct: duplicates, concurrency and lag
The view's data access code must survive the messaging behavior from chapter 5 and the delay built into CQRS.
The broker redelivers DeliveryPickedUp after DeliveryDelivered has already been handled, and the view sets order 101 back to "picked up". At the same time, a customer adds a dessert to order 102, the Order Service call returns OK, and the customer reloads Order History, which has not seen the event yet and shows the order without the dessert.
Store the highest event id applied to each aggregate in the view record, and skip any event with an id at or below it. Protect a record that several handlers update with optimistic or pessimistic locking.
The lag needs a different answer. The command side can return a token, such as the id of the event it published. The client passes it with its next query, and the query service says "not caught up yet, retry shortly" until the view has processed that event. Often it is simpler: the client updates its own local copy from the command's response and does not re-read at once.
Together these make a short checklist for any view's data access module:
Every handler must track ids and every client must cope with a view that lags. The last row of the checklist is the hardest: a view that is added later needs events from before it existed.
Building a view that did not exist yesterday
A view kept up to date from live events only knows what happened after it was switched on.
FTGO wants a new "most popular restaurants this year" view. The handlers are easy to write, but the broker keeps events only for a limited time (say, seven days), so a year of orders is no longer there to replay.
Copy every event to cheap long-term storage, such as Amazon S3. To build a new view, a batch job (for example with Apache Spark) computes the view as of time T from the archive. The view's handlers then apply only the newer events on top.
A durable log offers a lighter path when it fits. As in chapter 10, a service can publish one whole document per entity, keyed by id, on a compacted topic. A read model of such documents needs far less code than one that stitches together six partial events. If the view is damaged, or a new search need appears, it consumes the topic from the start with its normal code, adding instances to go faster, with no downtime and no special migration tool.
An archive and a batch job are more infrastructure, and compacted topics only keep the latest state. Views also do not remove load entirely: popular data is still read again and again, from a view or from the owning service.
The same read, again and again: caching
Composition and views decide where the answer comes from. Caching decides how often you have to fetch it at all.
At lunchtime, thousands of customers open the same few restaurant pages (an illustrative load). Each page asks Restaurant Service for the same menu, and the Order History screen asks it for the same restaurant names, over and over. Restaurant Service spends its capacity answering questions it answered a second ago, and when it is slow every one of those pages is slow.
Keep a copy of a recent answer close to whoever asks, and serve repeats from the copy. Cache for one of three reasons: performance, scale or robustness, and pick where to cache and how to invalidate with that reason in mind.
Where to put the cache? Take FTGO's "top ten restaurants" list. Order History Service computes it and needs restaurant names from Restaurant Service. A request cache in Order History stores the finished top-ten result: fastest, but useful only for that exact request. A client-side cache of names in Order History saves calls for any request that needs a name. A server-side cache inside Restaurant Service helps every caller, but each caller still pays the network hop.
Every cached copy goes stale at some point, so choose how to invalidate it:
| Invalidation | Idea | Watch out |
|---|---|---|
| Time to live (TTL) | Entry is valid for a set time | Blunt: data can be stale for the whole TTL |
| Conditional GET (ETag) | Ask for the resource only if changed; 304 if not | Still a round trip, but saves rebuilding it |
| Notification | Origin sends an event when data changes | Needs a broker. Send heartbeats so silence is noticed |
| Write-through | Update cache and origin together | Easy only on the server side |
| Write-behind | Update cache first, origin later | Data loss risk; unclear source of truth. Rare |
Every cache trades freshness for speed, and nested caches make staleness hard to reason about. And all of this still assumes the client knows which service to ask: FTGO's mobile app would have to call composers, views and services one by one for every screen.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| API composition | A query needs data from several services' private databases | Many calls, lower availability, no consistency across answers; weak for filters and big joins |
| CQRS view | Cross-service queries that filter, sort or page, or need a special database | Another service and datastore; the view lags the writes |
| View database chosen per query | One general database answers some queries badly | More technologies to operate |
| Idempotent, versioned view updates | Duplicate or out-of-order events corrupt the view | Track the last event id per record; locking for concurrent handlers |
| Consistency token | A user reads the view before it has caught up with their own change | Clients must pass the token and retry, or update a local copy |
| Event archive and incremental build | A new view needs events older than the broker keeps | Long-term storage and a batch job |
| Compacted topic of documents | Rebuilding or adding a read model needs special tools | Only the latest state per key is kept |
| Caching | The same reads load services again and again | Stale data; nested caches add up |
Recap
- API composition calls each service that owns part of the answer and joins the results in memory; it is simple, so try it first, but every provider lowers availability.
- Composition breaks down for filters, sorting and paging across services, and for queries that need a kind of database the owner does not have.
- CQRS keeps a read-only view, updated from other services' events, so a cross-service query becomes one fast read; the price is more infrastructure and some lag.
- Choose each view's database from its queries, make its updates idempotent, and design clients to cope with replication lag.
- Build new views from archived events plus newer ones, or from a compacted topic of documents read from the start.
- Cache for performance, scale or robustness, pick an invalidation method on purpose, and keep the number of caches as small as possible.
Quick check
Show answer
About 97.5%, because all five (composer plus four providers) must be up: 0.995^5 ≈ 0.975. Returning cached or partial data when one provider is down helps.
DeliveryPickedUp event after DeliveryDelivered. What breaks, and which pattern fixes it?
Show answer
Without protection, the handler sets the order back to "picked up" and customers see a wrong status. Make view updates idempotent and versioned: store the highest event id applied to each order and skip any event at or below it.
Show answer
Up to about 2 minutes, because Order History may refill its cache from a server-side entry that is already nearly 1 minute old. Nested caches add up, so cache in as few places as possible.
FTGO can now answer cross-service queries, but external clients still have to know which service, composer or view to call, and a mobile app on a slow network would make many calls for every screen.
CQRS: common questions
What is CQRS?
Command Query Responsibility Segregation: writes go to one model and reads come from a separate model, often a denormalised view kept up to date by events.