Schema design over gRPC
Message granularity, request and response envelopes, pagination with page tokens, and FieldMask projection.
Learning objectives
By the end of this chapter you can:
- Size a protobuf message around one reusable concept, and choose between nesting a field and referencing it by id.
- Wrap even a single scalar in a dedicated
FooRequest/FooResponseenvelope so the schema can grow a field without breaking a caller. - Page a collection with an opaque, server-defined
page_tokeninstead of a client-supplied offset or page number. - Project a response with
google.protobuf.FieldMask, with an unset mask staying backward compatible.
Why this matters
RoutingService.ListRoutes has been in routing.proto since the contract was declared. It is the RPC whose job is the shape of a whole catalog rather than the correctness of one call. Pagination and projection are schema questions, settled when the message is built and before any handler code exists: how big to make a message, how to wrap a response so it can grow, and how a client gets exactly the fields it asked for from a catalog neither side wants to ship in full on every call.
Message granularity
A message is exactly as big as one reusable concept. Money, Location, Leg and Route in shipping.type.v1 each mean one thing (an amount, a port, one hop, a planned path), so RoutingService, BookingService and TrackingService can share them without importing a type built for another serviceâs convenience.
The opposite failure is a message sized around one call site. A GetQuoteRouteInfo that mixes Route fields with pricing fields works for GetQuote and is wrong for ListRoutes, which needs a Route with no quote. Keeping Route and Money separate lets ListRoutes return a bare Route and GetQuote return a Route with a Money from the same types.
The second axis is nesting depth. Embedding full Booking objects in Route, or full Route objects in every Leg, hands a client asking for a small thing a tree most of which it discards. The rule:
| Situation | Model it as | Example |
|---|---|---|
| The childâs identity depends on its parent | Nest the message | Route holds repeated Leg legs; a leg only means something in a routeâs sequence |
| The child has its own lifecycle and its own callers | Reference by id (a string field, resolved by a separate call) |
A Route.carrier_id references a Carrier, which is looked up and listed independently |
Request and response envelopes
Every RPC takes a dedicated FooRequest and returns a dedicated FooResponse, never a bare domain type and never two RPCs sharing a request. gRPCâs single-message rule forces the request wrapper. The reason to keep it for one scalar anyway is that a message can grow a field and a bare parameter cannot, without changing the method signature and breaking every callerâs generated code.
ListRoutesRequest already carries page_size, page_token and field_mask. A future filter, such as routes from one carrier, is one new optional field, source- and wire-compatible with every client built today. ListRoutesResponse holds repeated Route routes next to next_page_token; a bare repeated Route would have had nowhere to put the token.
What the response omits matters as much: no total count, no âhas moreâ boolean, no page number. A count is a second query that must stay consistent with every page already returned, and a boolean must agree with a catalog that may change between page 1 and page 2. next_page_token is the whole continuation protocol, because a token only describes where this sequence of calls left off, which the server knows from the page it just built. An envelope padded with every value a UI might someday show becomes the god-message that granularity warns against.
Pattern: Pagination with Page Tokens
The problem
A ListRoutes that returns the whole catalog works with five routes and fails with five million. Without pagination every caller pays for the worst-case catalog on every call, including the one who wanted the first three. Slicing on the client is slower over the wire and impossible to bound in advance.
The solution
A paginated list takes a page_size hint and an opaque page_token, and returns a next_page_token that is empty on the last page.
The convention is Googleâs AIP-158, in the same family as AIP-161 (field masks) and AIP-131 (standard methods). None of them is gRPC specific, and a paginated REST collection follows the same rules.
page_sizeis a hint. The server may return fewer items; a full page is a courtesy.page_tokenis opaque. A client never parses it or builds one by hand.- The loop is the same whatever the encoding: call with
page_token="", keep calling with the previousnext_page_token, stop when it comes back empty.
How Quarkus and Python model it
Both stacks run the same four steps over the same fixed catalog of five routes (RouteCatalog.java, app/catalog.py):
- Clamp
page_size: zero or less becomes the default of 3, and above the maximum of 5 it is clamped down, so the server protects itself without making the client guess. - Resolve
page_tokento a start index. An empty token starts at 0. A token that doesnât parse, or parses out of range, returnsINVALID_ARGUMENTwith aBadRequestnamingpage_token, the same rich-error shape as before. - Slice with
end = min(start + page_size, catalog.size()).next_page_tokenisendas a string whileendis short of the catalog, and empty otherwise. - Project each route in the slice through the requestâs
field_mask, once per route, because the mask describes oneRouteand never the response envelope.
Tokens here are stringified offsets ("3"), the simplest deterministic thing a static in-memory list can produce. Over a changing datastore an offset breaks: a row inserted ahead of the callerâs position makes the next page skip or repeat rows, with no error anywhere. A real token encodes a stable cursor, such as a last-seen sort key with a filter fingerprint, and the client contract is identical because the token is opaque.
Pattern: FieldMask Projection
The problem
A Route with legs, carriers and timestamps suits a client rendering a detailed itinerary and wastes bandwidth and serialization for one that wants a price list. Without projection, every caller pays for the richest consumerâs needs, or the service grows a second RPC and a second message for each view.
The solution
A request carries a google.protobuf.FieldMask naming the fields it wants, and the server populates only those.
Fields not named stay at their zero value, which proto3âs wire format and JSON mapping omit, so ânot asked forâ and âabsentâ are the same observable fact.
Projection only narrows. An unset or empty mask means everything, the one reading that keeps ListRoutes compatible with a client built before field_mask existed: it never sets the field and gets the full Route it always got. Adding the field was a safe additive change, and the absent-field default had to preserve what existing callers relied on.
How Quarkus and Python model it
/**
* Returns {@code route} unchanged when the caller sent no mask (an unset
* {@code FieldMask} means "I want everything", the only reading that
* keeps {@code ListRoutes} backward compatible with a client built before
* this field existed). Otherwise builds a FRESH, empty {@code Route}
* builder and merges only the named top-level paths into it, so any field
* not named in the mask stays at its zero value and is therefore absent
* from the wire (proto3 omits unset/default scalar and message fields).
* {@link FieldMaskUtil#normalize} sorts and de-duplicates the paths first,
* which also happens to be where an unrecognized path is rejected via
* {@link FieldMaskUtil#isValid}, never silently ignored.
*/
private static Types.Route applyFieldMask(Types.Route route, FieldMask mask) {
if (mask.getPathsCount() == 0) {
return route;
}
if (!FieldMaskUtil.isValid(Types.Route.getDescriptor(), mask)) {
throw new IllegalArgumentException("field_mask names a path Route does not have: "
+ mask.getPathsList());
}
FieldMask normalized = FieldMaskUtil.normalize(mask);
Types.Route.Builder projected = Types.Route.newBuilder();
FieldMaskUtil.merge(normalized, route, projected);
return projected.build();
}
def _apply_field_mask(route: types_pb2.Route, mask: field_mask_pb2.FieldMask) -> types_pb2.Route:
"""Returns `route` unchanged when the caller sent no mask (an unset
FieldMask means "I want everything", the only reading that keeps
ListRoutes backward compatible with a client built before this field
existed). Otherwise builds a FRESH, empty Route and merges only the named
top-level paths into it, so any field not named in the mask stays at its
zero value and is therefore absent from the wire (proto3 omits
unset/default scalar and message fields). Raises ValueError for a path
Route does not have, rather than silently ignoring it."""
if not mask.paths:
return route
if not mask.IsValidForDescriptor(types_pb2.Route.DESCRIPTOR):
raise ValueError(f"field_mask names a path Route does not have: {list(mask.paths)}")
projected = types_pb2.Route()
mask.MergeMessage(route, projected)
return projected
Both use the well-known-type library each stack ships instead of hand-rolled field clearing. They reject a path the target message doesnât have, start from a fresh, empty builder, and merge only the named paths into it. Starting empty is what turns merge into project: FieldMaskUtil.merge and FieldMask.MergeMessage copy named fields from source to destination and clear nothing. A path can name a nested field (price.currency) as readily as a top-level one, and the validity check turns a typo into INVALID_ARGUMENT instead of a silently empty projection.
Decision
Use an opaque page token over an offset or page number whenever the collection can change between calls, which is any collection backed by a live datastore. Use FieldMask when one message serves callers with different needs, such as a summary list and a detail view of Route, instead of defining two RPCs or two response messages; the cost is that a client must know which paths exist, and the validity check makes a wrong one fail loudly. Skip both for a small, fixed collection cheap to return whole, like a lookup table of supported currencies.
đ€ Explore with your agent
âIn
examples/13-schema-design, reviewListRouteson both stacks (RoutingServiceImpl.javaandpython/app/routing_service.py) against this rule: an unsetfield_maskreturns the full route, a mask only narrows, and the mask applies to eachRoute, never to the response envelope. Confirm that the pathprice.currencyreturns only the currency insidepriceon both stacks, and change only what fails.âCheck:
grpcurl -plaintext -d '{"pageSize":1,"fieldMask":{"paths":["price.currency"]}}' localhost:9130 shipping.routing.v1.RoutingService/ListRoutesreturnspriceholding onlycurrency, and the same call on port 9131 returns identical JSON.
Build, run, observe
examples/13-schema-design/verify.sh starts both stacks with docker compose (Quarkus on 9130, Python on 9131), pages the five-route catalog through both, and checks the projection. By hand:
grpcurl -plaintext -d '{"pageSize":3}' \
localhost:9130 shipping.routing.v1.RoutingService/ListRoutes
{
"routes": [
{ "id": "rte_001", "legs": [...], "price": { "currency": "USD", "amount": "1200.00" } },
{ "id": "rte_002", "legs": [...], "price": { "currency": "USD", "amount": "2400.00" } },
{ "id": "rte_003", "legs": [...], "price": { "currency": "USD", "amount": "1800.50" } }
],
"next_page_token": "3"
}
grpcurl -plaintext -d '{"pageSize":3,"pageToken":"3"}' \
localhost:9130 shipping.routing.v1.RoutingService/ListRoutes
{
"routes": [
{ "id": "rte_004", "legs": [...], "price": { "currency": "USD", "amount": "1150.75" } },
{ "id": "rte_005", "legs": [...], "price": { "currency": "USD", "amount": "2600.25" } }
]
}
next_page_token is absent from the second response, not present and empty. proto3 omits a string at its zero value from JSON like any default, so a missing field is the signal that there is no next page. The mask goes in as a message, not the comma-string shorthand a compiled client could use:
grpcurl -plaintext -d '{"pageSize":1,"fieldMask":{"paths":["id","price"]}}' \
localhost:9130 shipping.routing.v1.RoutingService/ListRoutes
{
"routes": [
{ "id": "rte_001", "price": { "currency": "USD", "amount": "1200.00" } }
]
}
legs is gone: not empty, not null, never written. The Python stack on port 9131 returns byte-identical JSON for all three calls, and the two pages donât overlap.
Experiments:
- Send
"pageToken":"nope": the call fails withINVALID_ARGUMENTand aBadRequestnamingpage_token. - Send a mask path
Routedoesnât have, such as"paths":["nope"]: the call fails withINVALID_ARGUMENTinstead of returning an empty route. - Send
"pageSize":0and then"pageSize":50: the first returns 3 routes, the second all 5.
For deeper coverage
- Google AIP-158: Pagination: the opaque-page-token convention
ListRoutesfollows. - Google AIP-161: Field masks: the standard the projection implements.
- Protocol Buffers: Proto3 language guide: message design, nesting, and the well-known types,
FieldMaskamong them. - Cloud Native Design Patterns, âCompositionâ: the same granularity and envelope questions applied to composing responses across services.
- Clément Jean, gRPC Go for Professionals, Packt, 2023: Protobuf schema design in depth.