Cross-Service Query Design
Choose a read path that can answer the consumer's actual question under change and failure.
A joined response is a new contract: successful calls to every owner do not establish a
common snapshot, an exact global page, or permission to return every field.
This skill owns the choice and contract of the cross-service query. Keep an adequate
existing API, local query or reporting solution when it satisfies that contract. It does
not require extracting services or replacing mutable state with an event store.
Discover the question before choosing the mechanism
Inspect the endpoint and its consumers, domain rules, API/event contracts, ADRs, query plans,
traces, access policies, incidents and recovery runbooks. Capture only evidence that changes
the choice:
- Purpose and authority: display, search, reconciliation, export or a decision authorizing
an effect? Who owns each fact and who may change it? Can a missing/stale fact change eligibility?
- Query semantics: predicates, join keys and cardinality, null/absence meaning, duplicates,
sort/ties, totals, pagination and expected data growth. Which owner can identify candidates
before enrichment? A sample response does not establish the complete query contract.
- Visibility: required freshness per fact, read-your-writes, coherent snapshot or permitted
mixed versions, completeness, and the response when a source is late or unavailable.
- Access: caller/tenant, row and field permissions, revocation/deletion visibility, caches,
background consumers and exports. Authentication of a service is not end-user authorization.
- Cost and recovery: request/byte/concurrency budgets, measured joint dependency latency,
update volume, source replay/backfill support, retention and acceptable rebuild/outage time.
- Target stack: JDK/toolchain, resolved Spring/driver versions, transaction managers, actual
datasource routing, client deadlines and deployment constraints. Inspect build and runtime
evidence; do not infer deployed behavior from annotations or a starter dependency.
Separate found requirements from conventions and hypotheses. If the allowed delay or partial
answer policy is absent, inspect consumers first; ask only when the missing policy changes the
decision. Continue a query inventory or bounded experiment while the decision stays conditional.
Never turn an unknown freshness guarantee into an assumed number.
The architectural guidance is framework-independent. The partial Java/Spring example uses
Java 25 without preview and Spring Framework 7.0.9 as an authoring baseline; it is not a
tested application or permission to upgrade the target. Spring Data Commons 4.1.1 and
PostgreSQL 17 sources support conditional pagination guidance. Match target versions before
adapting APIs or configuration.
Establish what an answer proves
- Separate a display from a command precondition. A dashboard can show stock observed
earlier. An order command must enforce its stock invariant through the authoritative owner,
for example an atomic reservation under that owner's rules. Even a freshly composed read
followed by a write has a race. Revalidate at the effect boundary or use a proven protocol
covering all affected invariants; moving the query to the primary alone does not close it.
- Define freshness and completeness independently. All required sources may answer with
old state; recent returned rows may omit an unavailable owner. Distinguish not found,
not visible under policy, unavailable, pending projection and known deleted. Do not leak
existence when the public authorization contract intentionally merges some of these cases.
- Name the coherence requirement. Independent owner reads or projection checkpoints are
not a distributed snapshot. If a parent and its dependent record must appear together,
specify the required causal/version relationship and how the query enforces it. A
timestamp on each row or the newest event timestamp is not that proof.
- Make degraded behavior consumable. Return an explicitly contracted partial/stale result,
delay within budget, or fail. An absent payment answer must not become zero debt. An
all-required query cannot silently switch to partial success to satisfy a latency target.
Expose authorized status/coverage information without publishing private service topology.
- Keep permissions valid on every path. Apply tenant/row/field policy to primary reads,
projections, caches, fallback paths and pagination. A projection of mutable permissions needs
its own accepted revocation bound; zero-delay revocation cannot rest on an asynchronous copy
without another enforcing mechanism. Keep effect authorization at its authoritative owner.
For cross-service predicates, exact totals or cursor semantics, read
query semantics and Java/Spring boundaries.
Choose the least complex sufficient read path
| Evidence |
Candidate and condition |
Reject or reconsider when |
| One owner can answer the query, or existing local/reporting data satisfies it |
Keep that query and its supported access contract; optimize only a demonstrated bottleneck. |
It needs unsupported access to another owner's private schema or lacks the required visibility/security contract. |
| Small bounded candidate set, owner APIs support batch enrichment, request-time observations fit the latency budget |
Compose APIs. Identify the candidate owner and the semantic join, then bound total work. |
Exact cross-owner filtering/order demands unbounded scans, or required owners cannot meet the joint deadline. |
| Repeated cross-owner joins, global filters/sorts or high query load; delayed visibility is acceptable |
Build a purpose-specific read model if supported feeds/backfills, ownership and recovery cost are viable. |
Source history/state cannot rebuild it, the lag contract cannot be enforced, or the required operating capacity is absent. |
| Most data can be projected but one fact needs stronger freshness |
Consider a projection plus authoritative enrichment only if the fact cannot invalidate candidate membership/order, or a bounded complete query plan handles that change. |
Revalidation removes rows after paging while the response still promises exact pages/totals. |
| Large export/reconciliation needs a defined cutoff and cannot fit an interactive request |
Use a bounded asynchronous report with explicit snapshot/coverage and access semantics. |
It silently changes the requested business cutoff, omits failed ranges or stores an unbounded sensitive export. |
CQRS separates command and query models; it does not require separate services, separate
databases or event sourcing. A projection can be maintained from ordinary state plus supported
change contracts. A local read model updated in the same transaction differs from an
asynchronous cross-service projection. Use the smallest separation that resolves the query;
do not announce system-wide CQRS merely because one reporting view is useful.
Fowler's CQRS discussion explains the distinction
and complexity trade-off.
For composition, record candidate/leaf limits, maximum bytes, batch sizes, end-to-end deadline,
admission and behavior after timeout. Measure the root request with realistic concurrency and
data skew. Parallel calls, virtual threads and a GraphQL resolver do not remove query work or
the need for bounds. Use existing batch APIs when their semantics fit; do not convert one list
request into an unnoticed call per row.
For a read model, read projection lifecycle before
approving the design. Name its owner, authoritative inputs, query/index shape, progress
evidence, deletion handling, rebuild source and cutover criterion. Eventual consistency alone
supplies neither a delay deadline nor a repair mechanism.
Execute the requested scope
- Decision/design: deliver the query contract, alternatives including retention of the
current path, chosen path with evidence, resource/visibility budgets and a discriminating
validation plan. Include projection recovery only when a projection is chosen.
- Review/diagnosis: report the failing contract and its consequence, observed evidence,
proposed correction and remaining uncertainty. Do not infer a capacity fix from one trace.
- Implementation: change the query boundary and actual consumers together when authorized.
Add only justified DTOs, adapters, indexes or feeds; preserve domain ownership and existing
framework conventions. Wire authentication/authorization, configuration, error/degraded
responses, metrics and recovery for the chosen path. Do not leave the new contract as an
unused interface or move business-command rules into the query assembler.
Use an immutable query representation or explicit result state where it prevents accidental
mutation or ambiguity. Do not expose ORM entities, provider errors or raw cursor payloads as
the public contract. Avoid a universal query engine when a specific bounded use case suffices.
Validate the contract
Select checks for the changed claim, reusing adequate evidence. A design may end with a
reproducible test plan; implementation should execute the available relevant checks.
- Compare joined results against a controlled authoritative fixture: empty, one-to-many,
duplicate, deleted and missing inputs. Exercise filters/order across page boundaries.
- Reach a scan cap with no eligible rows and overflow a response with batch matches. Verify
consumer continuation preserves the remaining matches without declaring premature exhaustion.
- Change a sort/filter field between pages; verify the promised snapshot or live traversal
semantics, cursor expiry and behavior after a projection generation changes.
- Delay/fail one required source and one optional enrichment. Verify that missing data is not
converted to a favorable business value, and work remains bounded after caller timeout.
- Replay duplicates and reordered updates; interrupt projection processing at its commit
boundary. Verify visible state, durable progress and recovery rather than process health.
- Use hostile tenant IDs, copied cursors, revoked permissions and a stale cache/projection.
Check rows, fields, totals and metadata for leaks, including fallback and export paths.
- For an effect-authorizing consumer, race two commands after the same observed state. The
owner's invariant must hold even if both clients saw an acceptable read.
Measure freshness from a known source change to its query-visible result and track missing
coverage separately. Check stalls on quiet feeds; last-event age is not itself source lag.
Keep metrics bounded in cardinality. Measure rebuild/catch-up with representative volume before
promising a recovery time; a configuration setting proves no production guarantee.
Report commands/results, versions, fixture coverage and limitations. Distinguish structural
checks, executed code/contract tests, executed agent evaluations and written walkthroughs.
Do not claim improved latency or agent decisions without a suitable measurement/comparison.
Handoffs
Use optional specialists when their mechanisms become necessary; pass the query contract,
observed versions, failing evidence and requested result.
- Use
service-data-ownership when a feed, export, SQL read or other data access lacks an
authorized contract or a defined owner. Resolve authority and supported interfaces there,
then use the approved contracts to choose the query path here.
scatter-gather owns fan-out completion, deadlines and cancellation mechanics.
consistency-models owns the formal visibility/session model; distributed-transactions-and-sagas
owns protocols for effects spanning authorities, with idempotency for repeat-safe processing.
event-sourcing owns adoption and authoritative event history; change-data-capture-operations
owns capture/snapshot continuity. Neither is implied by choosing a read model.
spring-http-clients, spring-transactions-and-events and spring-boot-jpa own concrete
Spring wiring; spring-security-for-apis owns framework enforcement.
sql-query-performance owns local plans/index analysis; distributed-systems-testing owns
broader fault experiments. This skill retains the cross-service answer's acceptance criteria.
1---2name: cross-service-query-design3description: >-4 Choose API composition or a read model when a query joins data owned by multiple5 services, a list needs cross-service filtering or ordering, or projection lag changes6 what a consumer may conclude. Define freshness, completeness, authorization, query7 bounds and rebuild. Excludes fan-out mechanics, event-store adoption and CDC operations.8metadata:9 source: https://skillmd.com/skills/robsonkades/cross-service-query-design10---1112# Cross-Service Query Design1314Choose a read path that can answer the consumer's actual question under change and failure.15A joined response is a new contract: successful calls to every owner do not establish a16common snapshot, an exact global page, or permission to return every field.1718This skill owns the choice and contract of the cross-service query. Keep an adequate19existing API, local query or reporting solution when it satisfies that contract. It does20not require extracting services or replacing mutable state with an event store.2122## Discover the question before choosing the mechanism2324Inspect the endpoint and its consumers, domain rules, API/event contracts, ADRs, query plans,25traces, access policies, incidents and recovery runbooks. Capture only evidence that changes26the choice:2728- **Purpose and authority:** display, search, reconciliation, export or a decision authorizing29 an effect? Who owns each fact and who may change it? Can a missing/stale fact change eligibility?30- **Query semantics:** predicates, join keys and cardinality, null/absence meaning, duplicates,31 sort/ties, totals, pagination and expected data growth. Which owner can identify candidates32 before enrichment? A sample response does not establish the complete query contract.33- **Visibility:** required freshness per fact, read-your-writes, coherent snapshot or permitted34 mixed versions, completeness, and the response when a source is late or unavailable.35- **Access:** caller/tenant, row and field permissions, revocation/deletion visibility, caches,36 background consumers and exports. Authentication of a service is not end-user authorization.37- **Cost and recovery:** request/byte/concurrency budgets, measured joint dependency latency,38 update volume, source replay/backfill support, retention and acceptable rebuild/outage time.39- **Target stack:** JDK/toolchain, resolved Spring/driver versions, transaction managers, actual40 datasource routing, client deadlines and deployment constraints. Inspect build and runtime41 evidence; do not infer deployed behavior from annotations or a starter dependency.4243Separate found requirements from conventions and hypotheses. If the allowed delay or partial44answer policy is absent, inspect consumers first; ask only when the missing policy changes the45decision. Continue a query inventory or bounded experiment while the decision stays conditional.46Never turn an unknown freshness guarantee into an assumed number.4748The architectural guidance is framework-independent. The partial Java/Spring example uses49**Java 25 without preview and Spring Framework 7.0.9** as an authoring baseline; it is not a50tested application or permission to upgrade the target. Spring Data Commons **4.1.1** and51PostgreSQL **17** sources support conditional pagination guidance. Match target versions before52adapting APIs or configuration.5354## Establish what an answer proves55561. **Separate a display from a command precondition.** A dashboard can show stock observed57 earlier. An order command must enforce its stock invariant through the authoritative owner,58 for example an atomic reservation under that owner's rules. Even a freshly composed read59 followed by a write has a race. Revalidate at the effect boundary or use a proven protocol60 covering all affected invariants; moving the query to the primary alone does not close it.612. **Define freshness and completeness independently.** All required sources may answer with62 old state; recent returned rows may omit an unavailable owner. Distinguish not found,63 not visible under policy, unavailable, pending projection and known deleted. Do not leak64 existence when the public authorization contract intentionally merges some of these cases.653. **Name the coherence requirement.** Independent owner reads or projection checkpoints are66 not a distributed snapshot. If a parent and its dependent record must appear together,67 specify the required causal/version relationship and how the query enforces it. A68 timestamp on each row or the newest event timestamp is not that proof.694. **Make degraded behavior consumable.** Return an explicitly contracted partial/stale result,70 delay within budget, or fail. An absent payment answer must not become zero debt. An71 all-required query cannot silently switch to partial success to satisfy a latency target.72 Expose authorized status/coverage information without publishing private service topology.735. **Keep permissions valid on every path.** Apply tenant/row/field policy to primary reads,74 projections, caches, fallback paths and pagination. A projection of mutable permissions needs75 its own accepted revocation bound; zero-delay revocation cannot rest on an asynchronous copy76 without another enforcing mechanism. Keep effect authorization at its authoritative owner.7778For cross-service predicates, exact totals or cursor semantics, read79[query semantics and Java/Spring boundaries](references/query-contracts.md).8081## Choose the least complex sufficient read path8283| Evidence | Candidate and condition | Reject or reconsider when |84| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |85| One owner can answer the query, or existing local/reporting data satisfies it | Keep that query and its supported access contract; optimize only a demonstrated bottleneck. | It needs unsupported access to another owner's private schema or lacks the required visibility/security contract. |86| Small bounded candidate set, owner APIs support batch enrichment, request-time observations fit the latency budget | Compose APIs. Identify the candidate owner and the semantic join, then bound total work. | Exact cross-owner filtering/order demands unbounded scans, or required owners cannot meet the joint deadline. |87| Repeated cross-owner joins, global filters/sorts or high query load; delayed visibility is acceptable | Build a purpose-specific read model if supported feeds/backfills, ownership and recovery cost are viable. | Source history/state cannot rebuild it, the lag contract cannot be enforced, or the required operating capacity is absent. |88| Most data can be projected but one fact needs stronger freshness | Consider a projection plus authoritative enrichment only if the fact cannot invalidate candidate membership/order, or a bounded complete query plan handles that change. | Revalidation removes rows after paging while the response still promises exact pages/totals. |89| Large export/reconciliation needs a defined cutoff and cannot fit an interactive request | Use a bounded asynchronous report with explicit snapshot/coverage and access semantics. | It silently changes the requested business cutoff, omits failed ranges or stores an unbounded sensitive export. |9091CQRS separates command and query models; it does not require separate services, separate92databases or event sourcing. A projection can be maintained from ordinary state plus supported93change contracts. A local read model updated in the same transaction differs from an94asynchronous cross-service projection. Use the smallest separation that resolves the query;95do not announce system-wide CQRS merely because one reporting view is useful.96[Fowler's CQRS discussion](https://martinfowler.com/bliki/CQRS.html) explains the distinction97and complexity trade-off.9899For composition, record candidate/leaf limits, maximum bytes, batch sizes, end-to-end deadline,100admission and behavior after timeout. Measure the root request with realistic concurrency and101data skew. Parallel calls, virtual threads and a GraphQL resolver do not remove query work or102the need for bounds. Use existing batch APIs when their semantics fit; do not convert one list103request into an unnoticed call per row.104105For a read model, read [projection lifecycle](references/projection-lifecycle.md) before106approving the design. Name its owner, authoritative inputs, query/index shape, progress107evidence, deletion handling, rebuild source and cutover criterion. Eventual consistency alone108supplies neither a delay deadline nor a repair mechanism.109110## Execute the requested scope111112- **Decision/design:** deliver the query contract, alternatives including retention of the113 current path, chosen path with evidence, resource/visibility budgets and a discriminating114 validation plan. Include projection recovery only when a projection is chosen.115- **Review/diagnosis:** report the failing contract and its consequence, observed evidence,116 proposed correction and remaining uncertainty. Do not infer a capacity fix from one trace.117- **Implementation:** change the query boundary and actual consumers together when authorized.118 Add only justified DTOs, adapters, indexes or feeds; preserve domain ownership and existing119 framework conventions. Wire authentication/authorization, configuration, error/degraded120 responses, metrics and recovery for the chosen path. Do not leave the new contract as an121 unused interface or move business-command rules into the query assembler.122123Use an immutable query representation or explicit result state where it prevents accidental124mutation or ambiguity. Do not expose ORM entities, provider errors or raw cursor payloads as125the public contract. Avoid a universal query engine when a specific bounded use case suffices.126127## Validate the contract128129Select checks for the changed claim, reusing adequate evidence. A design may end with a130reproducible test plan; implementation should execute the available relevant checks.131132- Compare joined results against a controlled authoritative fixture: empty, one-to-many,133 duplicate, deleted and missing inputs. Exercise filters/order across page boundaries.134- Reach a scan cap with no eligible rows and overflow a response with batch matches. Verify135 consumer continuation preserves the remaining matches without declaring premature exhaustion.136- Change a sort/filter field between pages; verify the promised snapshot or live traversal137 semantics, cursor expiry and behavior after a projection generation changes.138- Delay/fail one required source and one optional enrichment. Verify that missing data is not139 converted to a favorable business value, and work remains bounded after caller timeout.140- Replay duplicates and reordered updates; interrupt projection processing at its commit141 boundary. Verify visible state, durable progress and recovery rather than process health.142- Use hostile tenant IDs, copied cursors, revoked permissions and a stale cache/projection.143 Check rows, fields, totals and metadata for leaks, including fallback and export paths.144- For an effect-authorizing consumer, race two commands after the same observed state. The145 owner's invariant must hold even if both clients saw an acceptable read.146147Measure freshness from a known source change to its **query-visible** result and track missing148coverage separately. Check stalls on quiet feeds; last-event age is not itself source lag.149Keep metrics bounded in cardinality. Measure rebuild/catch-up with representative volume before150promising a recovery time; a configuration setting proves no production guarantee.151152Report commands/results, versions, fixture coverage and limitations. Distinguish structural153checks, executed code/contract tests, executed agent evaluations and written walkthroughs.154Do not claim improved latency or agent decisions without a suitable measurement/comparison.155156## Handoffs157158Use optional specialists when their mechanisms become necessary; pass the query contract,159observed versions, failing evidence and requested result.160161- Use `service-data-ownership` when a feed, export, SQL read or other data access lacks an162 authorized contract or a defined owner. Resolve authority and supported interfaces there,163 then use the approved contracts to choose the query path here.164- `scatter-gather` owns fan-out completion, deadlines and cancellation mechanics.165- `consistency-models` owns the formal visibility/session model; `distributed-transactions-and-sagas`166 owns protocols for effects spanning authorities, with `idempotency` for repeat-safe processing.167- `event-sourcing` owns adoption and authoritative event history; `change-data-capture-operations`168 owns capture/snapshot continuity. Neither is implied by choosing a read model.169- `spring-http-clients`, `spring-transactions-and-events` and `spring-boot-jpa` own concrete170 Spring wiring; `spring-security-for-apis` owns framework enforcement.171- `sql-query-performance` owns local plans/index analysis; `distributed-systems-testing` owns172 broader fault experiments. This skill retains the cross-service answer's acceptance criteria.