Chapter 11 of 27 · Part 5: Data management

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

Where we are

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.

This chapter

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

Problem

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.

One screen, four owners findOrder(orderId) Order Status screen Order svc basic info + status Kitchen svc ticket, ready ETA Delivery svc courier, ETA, place Accounting svc payment status In the monolith this was one SELECT with JOINs. Now each piece lives in a private database.
Solution · API composition

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.

findOrder() with API composition Client API composer Order svc Kitchen svc GET /order/{id} GET /orders/{id} GET /tickets?orderId Delivery + Accounting called too order ticket join on orderId OrderDetails Calls that do not depend on each other run in parallel, so the wait is the slowest call, not the sum.

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.

Who plays the composer? Client Web app on the same fast LAN API gateway Gateway external API, mobile Own service Composer svc internal or complex

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.

Benefits and drawbacks of composition Benefit Simple and easy to understand No extra database Drawbacks More overhead many calls, many DBs Lower availability 0.995^5 = 97.5% No consistency order CANCELLED, ticket not Keep it available by returning cached or partial data when one provider is down.
Cost

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.

Problem

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.

Motivations for CQRS Where composition fails findOrderHistory() filter + sort + page findAvailable... geospatial query Wrong owner owner should not run it Order history filters by keyword, but Delivery and Accounting do not even store menu items.

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.

Why filters across services multiply calls Product svc 6 clothing items Pricing svc only 2 under $50 Product svc ask for the next 6 Repeat until the page fills Add a stock filter and sorting and it gets worse. Deep paging also eats the composer's memory.
Cost

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.

Solution · CQRS (Command Query Responsibility Segregation)

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.

CQRS: split writes from reads Command side create, update, del Domain events OrderCreated... Event handlers update the view Query side read-only view DB The view is a replica shaped for one set of queries, kept fresh by events.

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.

Order History Service A query-only service subscribes to events from four services and answers findOrderHistory() and findOrder(). Order svc Order events Kitchen svc Ticket events Delivery svc Delivery events Accounting svc Accounting events Order History svc event handlers View DB pre-joined Answers findOrderHistory() and findOrder() with one fast read, no in-memory join.
A query-only service builds its own view from other services' events.

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.

A read model built from event streams events on a durable log Product service Pricing service Inventory service Read model denormalized, searchable Listing page Add a new filter or screen? Build another view from the same streams.
React to events, do not poll. A read model that polls the services adds load to them, creates runtime dependencies and widens the window in which it is stale. Reacting to events avoids all three. Either way the view holds little or no business logic; that stays with the owning service.

CQRS is also how an event-sourced service from chapter 10 answers anything beyond "load by id". The two patterns side by side:

Two patterns for queries across services API composition Ask each owner, join in memory Simple: try this first Weak for big joins and filters CQRS Keep a ready-made read copy Fast, any query shape More moving parts, a little lag Rule of thumb: use API composition when you can, CQRS when you must.
Benefits and drawbacks of CQRS Benefits Efficient queries across services Best database for each view Queries for event-sourced apps Simpler command and query code Drawbacks More code and datastores Replication lag: views may be stale
Cost

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.

Problem

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.

Solution · A view database chosen per query

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 idDocument or key-value storeMongoDB, DynamoDB, Redis
Query JSON objects by fieldsDocument storeMongoDB, DynamoDB
Text searchSearch engineElasticsearch
Graph queries (fraud)Graph databaseNeo4j
SQL reporting / BIRelational databasePostgreSQL, 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.

Case study: the view on DynamoDB Event handler OrderCreated DAO OrderHistoryDao UpdateItem conditional DynamoDB one item per order A secondary index on consumerId + creation time sorts each consumer's history.
Cost

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.

Problem

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.

Duplicate events must not corrupt the view Broker Event handler View DeliveryPickedUp status = PICKED_UP DeliveryDelivered status = DELIVERED PickedUp (again!) seen id: skip it Record the highest event id per aggregate and ignore anything older.
Solution · Idempotent, versioned view updates

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.

Handling replication lag Client Command svc Query svc revise order OK + token (event id) GET order + token view not caught up yet retry later Or the client simply updates its own local model from the command's response.

Together these make a short checklist for any view's data access module:

Designing the view's data access module Data access concern Answer Concurrent updates optimistic or pessimistic lock Duplicate events idempotent handlers, track ids Eventual consistency return a token; client waits New or changed view rebuild from archived events
Cost

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.

Problem

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.

Solution · Archive events and build incrementally

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.

Building a new view incrementally Archived events e.g. in S3 Batch job e.g. Spark Snapshot view at time T Newer events applied on top Brokers do not keep events forever, so archive them and build views from snapshot + new events.

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.

Cost

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.

Problem

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.

Solution · Caching

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.

Why cache Performance Skip network hops Less load downstream Scale Reads hit copies Origin less contended Robustness Serve if origin is down Keep stale, do not evict Caching for robustness favors availability over consistency.

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.

Where to cache the top-ten restaurants Client Order History service Restaurant svc Request cache: top-10 result Client-side cache: names Server-side cache Order History needs restaurant names from Restaurant Service The request cache is fastest but helps only that one request.

Every cached copy goes stale at some point, so choose how to invalidate it:

InvalidationIdeaWatch out
Time to live (TTL)Entry is valid for a set timeBlunt: data can be stale for the whole TTL
Conditional GET (ETag)Ask for the resource only if changed; 304 if notStill a round trip, but saves rebuilding it
NotificationOrigin sends an event when data changesNeeds a broker. Send heartbeats so silence is noticed
Write-throughUpdate cache and origin togetherEasy only on the server side
Write-behindUpdate cache first, origin laterData loss risk; unclear source of truth. Rare
The golden rule: cache in as few places as possible. Two nested caches with a 1-minute TTL can serve data up to 2 minutes old while the client believes it is at most 1 minute old. The ideal number of caches is zero; add each one as a deliberate optimization.
Cost

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

PatternProblem it solvesWhat it costs
API compositionA query needs data from several services' private databasesMany calls, lower availability, no consistency across answers; weak for filters and big joins
CQRS viewCross-service queries that filter, sort or page, or need a special databaseAnother service and datastore; the view lags the writes
View database chosen per queryOne general database answers some queries badlyMore technologies to operate
Idempotent, versioned view updatesDuplicate or out-of-order events corrupt the viewTrack the last event id per record; locking for concurrent handlers
Consistency tokenA user reads the view before it has caught up with their own changeClients must pass the token and retry, or update a local copy
Event archive and incremental buildA new view needs events older than the broker keepsLong-term storage and a batch job
Compacted topic of documentsRebuilding or adding a read model needs special toolsOnly the latest state per key is kept
CachingThe same reads load services again and againStale data; nested caches add up

Recap

Quick check

If each of five services is 99.5% available, how available is findOrder() with API composition?
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.

FTGO's Order History view is fed by events. The broker redelivers an old 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.

Order History caches restaurant names with a 1-minute TTL, and Restaurant Service caches them server-side with a 1-minute TTL. How stale can a name be in Order History?
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.

Still open

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.

Next: 12 API gateway and backends for frontends →

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.