Beyond REST: Sketching a GraphQL Schema and a gRPC Service
Sketch the task lookup as a GraphQL schema and as a Protocol Buffers gRPC service, run both, and take away the controls each needs: batched resolvers, depth and cost limits, deadlines, status codes and field-number rules.
Contentsand lesson path
On this page
- The brief
- Step 1: the capability as a GraphQL schema
- Step 2: run it and meet the N+1 problem
- Step 3: guard rails — depth and cost limits
- Step 4: the capability as a gRPC service
- Step 5: field numbers and wire compatibility
- Choosing between the three
- The mistakes to avoid
- Check your understanding
- Apply it
- Review prompt
Lessons of API Design
- From Domain Nouns to Resources and URLs Concept · 20 min
- Errors, Pagination and Filtering Clients Can Rely On Worked example · 25 min
- Safe Retries, Long-Running Operations, Concurrent Updates and Versioning Concept · 30 min
- Lab: Contract-First Design with OpenAPI Lab · 30 min
- Beyond REST: Sketching a GraphQL Schema and a gRPC Service Worked example · 25 min
- Check: Review a Flawed API Design Knowledge check · 10 questions
What you will learn
- Write an OpenAPI contract that client and server teams can build against, and state when GraphQL or gRPC would serve the same clients better.
- Sketch one capability as a GraphQL schema and as a Protocol Buffers service, and name the operational controls each style needs: batched resolvers and query depth and cost limits for GraphQL; deadlines, status codes and field-number compatibility for gRPC.
Prerequisites: HTTP & APIs
01. The brief
You left the OpenAPI lab with a contract that client and server teams can build against. Two conversations that contract cannot end. A mobile team asks why each screen fetches whole tasks and needs several round trips. A platform team wants fast, typed calls between its own services, with streaming and hard timeouts. Both describe needs that REST answers less well than two other styles.
This worked example sketches the capability you have designed all through this skill, looking up tasks and their assignees, as a GraphQL schema and as a gRPC service, and runs both. Watch one thing: your design decisions do not disappear. Cursor pagination, error semantics, retries and compatibility all come along; only their spelling changes. Both demos are printed in full: save schema.graphql and the demo05_graphql.py blocks, in order, in one folder, then run the commands below. Step 4 adds the gRPC demo to the same folder.
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install graphql-core==3.3.2 grpcio==1.85.1 grpcio-tools==1.85.1
python demo05_graphql.py02. Step 1: the capability as a GraphQL schema
GraphQL moves the shape of a response from the server to the client. You publish a schema — a set of types and the fields they offer — at a single endpoint, usually POST /graphql. Clients send a query naming exactly the fields they want; the server runs one resolver function per field and returns precisely what was asked for. The schema below is the whole capability: a tasks query with the filters and cursor you designed in the pagination lesson, a single task(id:) lookup, and a Task type whose assignee field is another type, so a client can walk the relationship in the same request:
type Query {
tasks(state: String, first: Int = 2, after: ID): TaskPage!
task(id: ID!): Task
}
type TaskPage {
items: [Task!]!
nextCursor: ID
}
type Task {
id: ID!
title: String!
state: String!
assignee: User
}
type User {
id: ID!
name: String!
tasks: [Task!]!
}Note what did not change. after and nextCursor are the same opaque cursor from lesson two: a feed that grows while the client walks it has the same problem whatever the transport, and the same fix. GraphQL spells the parameters first and after (the Relay convention), but the design is the one you already justified. One field is new: User.tasks points back to Task, which makes the schema recursive. Step 3 deals with what that allows.
03. Step 2: run it and meet the N+1 problem
The schema is small; the trouble is in how it executes. Resolvers run once per field per parent object, so the assignee resolver runs for each task on the page. Written naively, each run makes its own database query — the N+1 problem: N queries for the page plus one for the list. The demo counts every query. Its fake database prints each one, like a SQL log:
"""N+1 versus a per-request batch loader, and a depth guard that runs first."""
import asyncio
from pathlib import Path
from graphql import (FieldNode, FragmentDefinitionNode, FragmentSpreadNode,
GraphQLError, OperationDefinitionNode, build_schema,
execute, parse, validate)
TASKS = [
{"id": "k101", "title": "Write API guide", "state": "open", "assignee": "u1"},
{"id": "k102", "title": "Review cursors", "state": "open", "assignee": "u2"},
{"id": "k103", "title": "Fix 412 handling", "state": "done", "assignee": "u3"},
{"id": "k104", "title": "Plan v1 sunset", "state": "open", "assignee": "u1"},
]
USERS = {"u1": {"id": "u1", "name": "Ana"}, "u2": {"id": "u2", "name": "Bo"},
"u3": {"id": "u3", "name": "Chen"}}
class FakeDB:
"""In-memory tables that print and count every query, like a SQL log."""
def __init__(self) -> None:
self.queries = 0
def log(self, sql: str) -> None:
self.queries += 1
print(" db query:", sql)
def tasks(self, state=None, first=2, after=None, assignee=None):
self.log("SELECT tasks")
rows = [t for t in TASKS if state in (None, t["state"])
and assignee in (None, t["assignee"])]
if after: # demo cursor: the last id seen (lesson two encodes it)
rows = rows[[t["id"] for t in rows].index(after) + 1:]
more = len(rows) > first
return rows[:first], rows[first - 1]["id"] if more else None
def task(self, task_id):
self.log("SELECT task by id")
return next((t for t in TASKS if t["id"] == task_id), None)The batch loader is the DataLoader idea in about twenty lines. Each assignee resolver asks the loader for one id and gets back a future, a placeholder for a value that arrives later. The first request in an event-loop turn schedules dispatch with call_soon, so it runs only after every resolver on the page has asked; then one query answers them all.
def user(self, user_id):
self.log(f"SELECT user {user_id}")
return USERS.get(user_id)
def users(self, ids):
self.log(f"SELECT users {ids}")
return {i: USERS[i] for i in ids if i in USERS}
class UserLoader:
"""Per request: collect the ids asked for in one event-loop turn, then
load them with one query. A new loader per request means no stale or
cross-user data survives between requests."""
def __init__(self, db: FakeDB) -> None:
self.db, self.pending, self.futures = db, [], {}
def load(self, user_id: str) -> asyncio.Future:
if user_id not in self.futures: # ask for each id once per request
loop = asyncio.get_running_loop()
self.futures[user_id] = loop.create_future()
if not self.pending: # first id this turn: dispatch when idle
loop.call_soon(self.dispatch)
self.pending.append(user_id)
return self.futures[user_id]
def dispatch(self) -> None:
ids, self.pending = self.pending, []
found = self.db.users(ids)
for user_id in ids:
self.futures[user_id].set_result(found.get(user_id))async def resolve_tasks(_, info, state=None, first=2, after=None):
items, cursor = info.context["db"].tasks(state, first, after)
return {"items": items, "nextCursor": cursor}
async def resolve_task(_, info, id):
return info.context["db"].task(id)
async def resolve_assignee(task, info):
loader = info.context["users"]
if loader is None: # naive: one query for every task on the page
return info.context["db"].user(task["assignee"])
return await loader.load(task["assignee"])
async def resolve_user_tasks(user, info):
return info.context["db"].tasks(first=100, assignee=user["id"])[0]
SCHEMA = build_schema(Path("schema.graphql").read_text())
SCHEMA.query_type.fields["tasks"].resolve = resolve_tasks
SCHEMA.query_type.fields["task"].resolve = resolve_task
SCHEMA.type_map["Task"].fields["assignee"].resolve = resolve_assignee
SCHEMA.type_map["User"].fields["tasks"].resolve = resolve_user_tasks== naive: one user query per task ==
db query: SELECT tasks
db query: SELECT user u1
db query: SELECT user u2
db query: SELECT user u3
assignees: ['Ana', 'Bo', 'Chen'] | errors: None
total db queries: 4
== batched: one user query per page ==
db query: SELECT tasks
db query: SELECT users ['u1', 'u2', 'u3']
assignees: ['Ana', 'Bo', 'Chen'] | errors: None
total db queries: 2Same answer, four queries became two, and the gap widens with page size. Two rules matter more than the numbers. Batch per request, never in a global cache: a dictionary shared across requests serves one user's data to another's request and goes stale the moment anyone edits. And the same schema serves every screen shape: because the client names the fields, one query can assemble a whole screen, or two, in a single round trip:
query Screen {
tasks(state: "open", first: 2) {
items { id title assignee { name } }
}
task(id: "k103") { title state }
}== one request, two screens' worth of data ==
db query: SELECT tasks
db query: SELECT task by id
db query: SELECT users ['u1', 'u2']
assignees: ['Ana', 'Bo'] | errors: None
total db queries: 304. Step 3: guard rails — depth and cost limits
Flexible queries are an attack surface as well as a feature. A recursive schema — a Task whose assignee is a User with a tasks field back to Task — lets a small query ask for a tree of work, and each level multiplies the resolver calls. Public GraphQL services therefore guard execution: a depth limit rejects documents that nest past a fixed depth, a cost limit scores each query and rejects the expensive ones, and many also disable open introspection in production. The demo checks depth by parsing the document before executing anything, so a query that nests too deeply is rejected before any resolver runs:
MAX_DEPTH = 4
def depth(node, fragments: dict, memo: dict) -> int:
"""Longest chain of nested fields below node. Fragments count as the
fields they contain, and each fragment is measured only once."""
if node.selection_set is None:
return 0
deepest = 0
for sel in node.selection_set.selections:
if isinstance(sel, FieldNode):
deepest = max(deepest, 1 + depth(sel, fragments, memo))
elif isinstance(sel, FragmentSpreadNode):
name = sel.name.value
if name not in memo and name in fragments:
memo[name] = 0 # a fragment cycle counts 0; validation rejects it
memo[name] = depth(fragments[name], fragments, memo)
deepest = max(deepest, memo.get(name, 0))
else: # an inline fragment (... on Task) adds no level of its own
deepest = max(deepest, depth(sel, fragments, memo))
return deepest
def check_depth(source: str):
"""Parse and measure the document before any resolver can run."""
document = parse(source, max_tokens=2000) # bounds the parser's work too
fragments = {d.name.value: d for d in document.definitions
if isinstance(d, FragmentDefinitionNode)}
for op in document.definitions:
if isinstance(op, OperationDefinitionNode):
found = depth(op, fragments, {})
if found > MAX_DEPTH:
raise GraphQLError(f"depth {found} exceeds maximum {MAX_DEPTH}")
return documentparse turns the query text into a tree of nodes without running anything; its max_tokens limit stops an enormous document before the tree is even built. depth then walks the selections. A field adds one level. A fragment spread (...More) counts as the fields inside its fragment, otherwise an attacker could hide the nesting in fragments. Each fragment is measured once and remembered in memo, so fragments that spread other fragments cannot make the guard itself slow. The last two blocks run everything:
async def run(title: str, source: str, batched: bool) -> None:
print(f"== {title} ==")
db = FakeDB()
context = {"db": db, "users": UserLoader(db) if batched else None}
document = check_depth(source)
errors = validate(SCHEMA, document)
if errors:
print(" invalid:", errors[0].message)
return
result = await execute(SCHEMA, document, context_value=context)
names = [t["assignee"]["name"] for t in result.data["tasks"]["items"]]
print(" assignees:", names, "| errors:", result.errors)
print(" total db queries:", db.queries)
PAGE = "{ tasks(first: 3) { items { title assignee { name } } } }"
SCREEN = """{ tasks(state: "open", first: 2) { items { id title assignee { name } } }
task(id: "k103") { title state } }"""
NESTED = "{ tasks { items { assignee { %s } } } }"
DEEP = NESTED % "tasks { assignee { tasks { title } } }"
HIDDEN = NESTED % "...More" + """
fragment More on User { tasks { assignee { tasks { id } } } }"""
WIDE = "{ %s }" % " ".join(f"a{i}: tasks(first: 100) {{ items {{ id }} }}"
for i in range(50))async def main() -> None:
await run("naive: one user query per task", PAGE, batched=False)
await run("batched: one user query per page", PAGE, batched=True)
await run("one request, two screens' worth of data", SCREEN, batched=True)
print("== depth guard, before execution ==")
for label, source in [("depth 4", NESTED % "name"), ("depth 7", DEEP),
("depth 7 inside a fragment", HIDDEN),
("50 aliased lists, depth 3", WIDE)]:
try:
check_depth(source)
print(f" {label}: accepted")
except GraphQLError as err:
print(f" {label}: rejected, {err.message}")
if __name__ == "__main__":
asyncio.run(main())== depth guard, before execution ==
depth 4: accepted
depth 7: rejected, depth 7 exceeds maximum 4
depth 7 inside a fragment: rejected, depth 7 exceeds maximum 4
50 aliased lists, depth 3: acceptedThe check is deliberately boring: predictable, cheap, and in front of every expensive thing the server can do. The last line shows its limit. Fifty aliased copies of tasks(first: 100) are only three levels deep, yet ask for up to 5,000 rows. Depth cannot see width; a cost limit can, by adding up a score per field (a list field weighted by its first argument, say) and rejecting documents over a budget. The guard also lets a fragment cycle through as depth 0, which is safe only because run validates the document, and validation rejects cycles, before anything executes.
05. Step 4: the capability as a gRPC service
gRPC starts from a different kind of contract: a .proto file describing messages and services. The transport is HTTP/2, the bodies are compact Protocol Buffers, and both ends compile the same file into typed stubs. The capability you have been designing becomes three messages and one service:
syntax = "proto3";
package tasks.v1;
message Task {
string id = 1;
string title = 2;
string state = 3; // open | in_progress | done
string assignee = 4; // user id
reserved 5; // was estimate_hours; never reuse
reserved "estimate_hours";
}
message GetTaskRequest {
string id = 1;
}
message GetTaskResponse {
Task task = 1;
}
message ListTasksRequest {
string team = 1;
string state = 2; // optional filter, like ?state= on REST
int32 limit = 3;
string cursor = 4; // opaque cursor, same idea as REST
}
message ListTasksResponse {
repeated Task tasks = 1;
string next_cursor = 2;
}
service TaskService {
rpc GetTask(GetTaskRequest) returns (GetTaskResponse);
rpc SlowGetTask(GetTaskRequest) returns (GetTaskResponse);
rpc ListTasks(ListTasksRequest) returns (ListTasksResponse);
}python -m grpc_tools.protoc -I. --python_out=. \
--grpc_python_out=. tasks.proto
python demo05_grpc.pyClient and server share generated code instead of a document. Errors use status codes that rhyme with HTTP: a missing task aborts with NOT_FOUND, the 404 of lesson one. The habit to install on day one is the deadline: a call without one can wait forever, so clients set a timeout per call and treat DEADLINE_EXCEEDED like a REST 504, a bounded failure they may retry:
"""The task lookup as a gRPC service: NOT_FOUND, cursors and a deadline."""
import time
from concurrent import futures
import grpc
import tasks_pb2
import tasks_pb2_grpc
TASKS = {t.id: t for t in [ # the same four tasks as the GraphQL demo
tasks_pb2.Task(id="k101", title="Write API guide", state="open", assignee="u1"),
tasks_pb2.Task(id="k102", title="Review cursors", state="open", assignee="u2"),
tasks_pb2.Task(id="k103", title="Fix 412 handling", state="done", assignee="u3"),
tasks_pb2.Task(id="k104", title="Plan v1 sunset", state="open", assignee="u1"),
]}
class TaskService(tasks_pb2_grpc.TaskServiceServicer):
def GetTask(self, request, context):
task = TASKS.get(request.id)
if task is None:
context.abort(grpc.StatusCode.NOT_FOUND, f"no task '{request.id}'")
return tasks_pb2.GetTaskResponse(task=task)
def SlowGetTask(self, request, context):
for _ in range(20): # about one second of work, unless the client leaves
if not context.is_active():
return tasks_pb2.GetTaskResponse()
time.sleep(0.05)
return self.GetTask(request, context)
def ListTasks(self, request, context):
rows = [t for t in TASKS.values() if request.state in ("", t.state)]
if request.cursor: # demo cursor: the last id seen, as in the GraphQL demo
rows = [t for t in rows if t.id > request.cursor]
page = rows[:request.limit or 2]
more = len(rows) > len(page)
return tasks_pb2.ListTasksResponse(
tasks=page, next_cursor=page[-1].id if more else "")SlowGetTask checks context.is_active(), so it stops once the client gives up. The client sets a timeout on every call:
def main() -> None:
server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
tasks_pb2_grpc.add_TaskServiceServicer_to_server(TaskService(), server)
port = server.add_insecure_port("127.0.0.1:0") # any free port
server.start()
with grpc.insecure_channel(f"127.0.0.1:{port}") as channel:
stub = tasks_pb2_grpc.TaskServiceStub(channel)
reply = stub.GetTask(tasks_pb2.GetTaskRequest(id="k101"), timeout=2)
print("GetTask(k101) ->", reply.task.title, f"[{reply.task.state}]")
try:
stub.GetTask(tasks_pb2.GetTaskRequest(id="nope"), timeout=2)
except grpc.RpcError as err:
print("GetTask(nope) ->", err.code().name, "-", err.details())
cursor = ""
for _ in range(2): # walk two pages of open tasks
page = stub.ListTasks(tasks_pb2.ListTasksRequest(
team="t7", state="open", limit=2, cursor=cursor), timeout=2)
print(f"ListTasks(open, 2, cursor={cursor or '-'}) ->",
[t.id for t in page.tasks], "next:", page.next_cursor or "-")
cursor = page.next_cursor
try: # bound every call with a deadline
stub.SlowGetTask(tasks_pb2.GetTaskRequest(id="k101"), timeout=0.2)
except grpc.RpcError as err:
print("SlowGetTask(timeout=0.2) ->", err.code().name)
server.stop(grace=None)
if __name__ == "__main__":
main()GetTask(k101) -> Write API guide [open]
GetTask(nope) -> NOT_FOUND - no task 'nope'
ListTasks(open, 2, cursor=-) -> ['k101', 'k102'] next: k102
ListTasks(open, 2, cursor=k102) -> ['k104'] next: -
SlowGetTask(timeout=0.2) -> DEADLINE_EXCEEDED06. Step 5: field numbers and wire compatibility
In the binary encoding, a Protobuf message is a sequence of numbered fields and the names do not travel; ProtoJSON, though, uses the names as JSON keys, so a rename still breaks JSON clients. Adding a field is compatible, because old readers skip numbers they do not know. Most type changes on the same number are not: old binaries decode the bytes with the wrong layout. (The Protobuf guide lists a few compatible pairs, such as int32 and int64.) When you remove a field, reserve its number and its name, as Task does for estimate_hours: the number stops anyone giving 5 to a new field and corrupting deployed clients, and the name keeps JSON parsing safe. This is the same compatible-versus-breaking split as the versioning policy, enforced by the wire format itself.
07. Choosing between the three
Keep REST with OpenAPI as the default for APIs whose clients you do not control: it works with browsers, curl and caches, its status codes carry meaning everywhere, and humans and tools can read the contract. Choose GraphQL when many client teams need different shapes from the same data and you want them to move without server changes — and budget for the operational work that flexibility costs: per-request batching, depth and cost limits, and resolver monitoring. Choose gRPC between services you own, where low latency, streaming, deadlines and typed stubs earn their keep because both ends deploy together. Real systems often mix them: a public REST API, internal gRPC, and sometimes a GraphQL gateway over both.
08. The mistakes to avoid
09. Check your understanding
10. Apply it
For the skill practice, sketch the task lookup twice: a GraphQL query type with cursor arguments and an assignee field, and a .proto service for the same two operations. Then push each sketch further: next to depth, write a cost walk that scores each field 1 and multiplies the cost of a field's children by its first argument (2 when tasks omits it), reject documents over a budget of 200, and check that WIDE is now rejected while SCREEN passes; give the proto an assignee sub-message and a server-streaming SubscribeTasks rpc, and regenerate the stubs. Finish with the comparison paragraph — which style fits the public team-tasks API and why — written next to the versioning policy from lesson three, because the peer review will read them together.
11. Review prompt
Without looking back: write the SDL for a Task type with an assignee and a cursor-paginated list query. Explain why naive resolvers cause N+1 queries and what a per-request batch changes. Name two guard rails a public GraphQL endpoint needs before it executes a query. State what identifies a field on a Protobuf wire, and what you must do when you delete one. Finally, for each of these — a public developer API, a screen-rich mobile app, internal service calls — name the style that fits and give one sentence why.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.