Lesson 30 of 59API design in depth
GraphQL and gRPC Services in Python
Build a GraphQL API with Strawberry and a gRPC service with grpc.aio: DataLoaders, query limits, protobuf evolution, deadlines and status codes.
Your company's REST API serves the website well, but two new requests land in the same week. The mobile team wants one call that returns an order with its items, the customer and the delivery slots, shaped exactly for one screen. And the platform team wants the pricing service to stop parsing JSON for 40,000 internal calls per second. The first is a job GraphQL was built for; the second is gRPC's home ground. API Design in the system design course covers when to pick each. This lesson is the how: a real Strawberry GraphQL API mounted in FastAPI, the N+1 problem and its fix, the production limits nobody mentions in tutorials, then a grpc.aio service with the rules that keep protobuf contracts and deadlines from biting you.
GraphQL with Strawberry
Strawberry builds a GraphQL schema from Python type hints and dataclass-like classes, so it feels close to Pydantic. Every @strawberry.type becomes a GraphQL object type, methods decorated with @strawberry.field become resolvers, and the schema is the contract that clients query against.
import strawberry
from strawberry.fastapi import BaseContext
from app.graphql.loaders import make_author_loader
from app.graphql.permissions import IsAuthenticated
class Context(BaseContext):
def __init__(self, session, user):
super().__init__()
self.session = session
self.user = user
self.author_loader = make_author_loader(session) # one per request
@strawberry.type
class Author:
id: strawberry.ID
name: str
@strawberry.type
class Book:
id: strawberry.ID
title: str
author_id: strawberry.Private[int] # used by resolvers, not exposed
@strawberry.field
async def author(self, info: strawberry.Info[Context, None]) -> Author | None:
return await info.context.author_loader.load(self.author_id)
@strawberry.field(permission_classes=[IsAuthenticated])
def stock(self) -> int:
return 3
@strawberry.input
class AddBookInput:
title: str
author_id: strawberry.ID
@strawberry.type
class Query:
@strawberry.field
async def books(self, info: strawberry.Info[Context, None], first: int = 10) -> list[Book]:
return await book_repo.list(info.context.session, limit=min(first, 100))
@strawberry.type
class Mutation:
@strawberry.mutation
async def add_book(self, info: strawberry.Info[Context, None], input: AddBookInput) -> Book:
return await book_repo.create(info.context.session, input.title, int(input.author_id))A few things to notice. Python's add_book and author_id become addBook and authorId in the schema, because Strawberry converts names to camelCase by default. Input arguments use @strawberry.input types rather than output types, which is a GraphQL rule. strawberry.Private keeps a field on the Python object without publishing it. And Author | None makes the field nullable, while int is non-null, which matters more than it looks (see the error section below).
Mounting it in FastAPI takes a router and a context getter, which is an ordinary FastAPI dependency. That means your existing database session and auth dependencies work unchanged:
from typing import Annotated
from fastapi import Depends, FastAPI
from strawberry.fastapi import GraphQLRouter
from app.deps import get_optional_user, get_session
from app.graphql.schema import Context, schema
async def get_context(
session: Annotated[AsyncSession, Depends(get_session)],
user: Annotated[User | None, Depends(get_optional_user)],
) -> Context:
return Context(session=session, user=user)
graphql_app = GraphQLRouter(schema, context_getter=get_context, graphql_ide=None)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")graphql_ide=None turns off the in-browser GraphiQL page; enable it in development only.
The N+1 problem and DataLoader
The query { books { title author { name } } } looks like one request. On the server it is one resolver for books, then one call to the author resolver per book. Written naively, each author resolver runs its own query: 1 query for the list plus N for the authors. Run this to watch the queries:
Press Run (⌘ Enter) to see what happens.The real strawberry.dataloader.DataLoader works the same way using asyncio. Each await loader.load(id) registers a key and returns a future. Strawberry runs sibling resolvers concurrently, so all five author resolvers register their keys before the event loop gets a chance to run the scheduled batch. Then your batch function receives [1, 2, 2, 3, 1] deduplicated to [1, 2, 3], runs one IN query, and every future resolves. Run against the Strawberry app in this lesson with a query log, the five-book query issued exactly two SQL statements.
from sqlalchemy import select
from strawberry.dataloader import DataLoader
def make_author_loader(session) -> DataLoader[int, "Author | None"]:
async def load_authors(ids: list[int]) -> list["Author | None"]:
rows = await session.scalars(select(AuthorRow).where(AuthorRow.id.in_(ids)))
by_id = {row.id: Author(id=row.id, name=row.name) for row in rows}
return [by_id.get(i) for i in ids] # same length and order as ids
return DataLoader(load_fn=load_authors)The contract for a batch function has two rules you must keep: return exactly one result per key, in the same order, and return None (or an exception object) for missing keys rather than skipping them. Getting the order wrong does not raise; it silently gives books the wrong authors. And create loaders per request, in the context getter, never at module level. A DataLoader caches what it has loaded, so a global one would serve stale data forever and leak one user's view of the data to another.
One query for the list. Five books come back.
GraphQL in production
Tutorials stop at the happy path. These are the things that bite real GraphQL services.
Unbounded queries. A client can nest and alias its way to an enormous query: books { author { books { author { ... } } } }, or the same expensive field under a hundred aliases. Put limits in the schema's extensions:
from strawberry.extensions import (
MaskErrors,
MaxAliasesLimiter,
MaxTokensLimiter,
QueryDepthLimiter,
)
schema = strawberry.Schema(
query=Query,
mutation=Mutation,
extensions=[
QueryDepthLimiter(max_depth=6),
MaxTokensLimiter(max_token_count=2000),
MaxAliasesLimiter(max_alias_count=15),
MaskErrors(),
],
)Also cap list sizes in resolvers (min(first, 100) above) and add a timeout. Depth limits do not stop a shallow query that asks for 100 items of 100 items; for public APIs, compute a cost per query and rate limit by cost, the way GitHub's GraphQL API does with points. For first-party apps, the strongest control is persisted queries: the build registers each query the app uses and the client sends a hash, so the server only executes queries it has seen. Support for this varies by server and gateway, so check the current Strawberry docs before choosing an approach.
Errors come back as 200. GraphQL returns HTTP 200 with an errors array alongside partial data. Your HTTP error-rate dashboards will show zero problems during an outage unless you also count GraphQL errors. And errors propagate through non-null fields: in the test app, an unauthorised user asking for books { stock } (where stock: int is non-null and the list items are non-null) got "data": null for the whole query, because the null bubbled up until it reached a nullable parent. Make fields nullable where partial failure is acceptable.
Error masking. By default, exception messages go to the client, including database errors. MaskErrors() replaces messages with "Unexpected error.", but by default it masks everything, including your deliberate "Not signed in". Pass should_mask_error to let a known class of user-facing errors through, and log the originals with a request id.
Introspection. Introspection lets anyone download your full schema. DisableIntrospection() turns it off. This is debated: it reduces casual reconnaissance, but it is not security (field suggestions in error messages leak names too, and the schema is in your public app bundle). Many teams disable it for private APIs and leave it on for public ones.
Auth at the field level. Every field is an entry point, so authorization belongs on fields and in resolvers (permission_classes=[...]), not only on the endpoint. Check object ownership in the resolver: being signed in does not mean you may see order 42.
Caching. Everything is a POST to one URL, so CDN and browser caching do not apply out of the box. Caching moves to the client (normalised caches in Apollo Client or urql) and to the server per resolver or per DataLoader.
DataLoader for authors at module level and reuses it for every request. What is the main problem?gRPC: the contract is a .proto file
gRPC turns remote calls into method calls on a generated stub. You describe services and messages in a .proto file, generate code for each language, and the calls travel as protobuf over HTTP/2.
syntax = "proto3";
package inventory.v1;
service InventoryService {
rpc GetItem(GetItemRequest) returns (Item); // unary
rpc WatchStock(WatchStockRequest) returns (stream StockLevel); // server streaming
}
message GetItemRequest {
string sku = 1;
}
message Item {
reserved 3; // was price_cents: never reuse this number
reserved "price_cents";
string sku = 1;
string name = 2;
int64 price_minor = 4;
optional string colour = 5; // optional gives you has-presence
}
message WatchStockRequest { string sku = 1; }
message StockLevel { string sku = 1; int32 on_hand = 2; }There are four call shapes: unary (one request, one response), server streaming (returns (stream X), such as live stock updates), client streaming ((stream X) returns, such as uploading sensor readings), and bidirectional streaming (both sides stream, such as a chat or a long-lived sync session). Put the version in the package (inventory.v1), so a future incompatible v2 can live alongside it.
Generate Python code with grpcio-tools (or with buf generate, which most teams prefer once they have several protos because it adds linting and breaking-change checks):
uv add grpcio protobufuv add --dev grpcio-toolsuv run python -m grpc_tools.protoc -I protos --python_out=gen --pyi_out=gen --grpc_python_out=gen protos/inventory/v1/inventory.protoYou get inventory_pb2.py (messages), inventory_pb2.pyi (type hints for your editor) and inventory_pb2_grpc.py (the stub and the servicer base class). The files land in gen/inventory/v1/, mirroring the proto's path under -I protos, and the generated _grpc module imports its sibling absolutely: from inventory.v1 import inventory_pb2. So gen/ itself must be a root on the import path (a source root in your packaging config, or PYTHONPATH). Importing it as gen.inventory.v1 fails with ModuleNotFoundError, which is the most common first gRPC error in Python. Fix the layout, or let buf manage it, rather than hand-editing generated imports. And remember protobuf is a separate runtime dependency: the generated code imports google.protobuf.
An async gRPC service
grpc.aio is the asyncio API, and it fits alongside FastAPI-style code. A servicer is a class with one async method per RPC. Streaming RPCs are async generators.
import asyncio
import grpc
from inventory.v1 import inventory_pb2 as pb # gen/ is on the import path
from inventory.v1 import inventory_pb2_grpc as pb_grpc
class Inventory(pb_grpc.InventoryServiceServicer):
async def GetItem(self, request, context):
item = await items.get(request.sku)
if item is None:
await context.abort(grpc.StatusCode.NOT_FOUND, f"no item {request.sku}")
return pb.Item(sku=item.sku, name=item.name, price_minor=item.price_minor)
async def WatchStock(self, request, context):
async for level in stock.subscribe(request.sku):
yield pb.StockLevel(sku=request.sku, on_hand=level)
async def serve() -> None:
server = grpc.aio.server()
pb_grpc.add_InventoryServiceServicer_to_server(Inventory(), server)
server.add_insecure_port("[::]:50051") # TLS or a mesh in production
await server.start()
await server.wait_for_termination()
if __name__ == "__main__":
asyncio.run(serve())And the client, with the one argument you must never forget:
async with grpc.aio.insecure_channel("inventory:50051") as channel:
stub = pb_grpc.InventoryServiceStub(channel)
try:
item = await stub.GetItem(pb.GetItemRequest(sku="KET-001"), timeout=0.3)
except grpc.aio.AioRpcError as err:
if err.code() == grpc.StatusCode.NOT_FOUND:
...
elif err.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
...Always set a deadline (timeout= in Python). A gRPC call without one can wait forever, and a slow dependency then holds every caller's resources until the whole chain falls over. Deadlines propagate: the server sees the remaining time in context.time_remaining() and should pass a shorter deadline to anything it calls. When the deadline passes mid-stream, the client gets DEADLINE_EXCEEDED after whatever messages already arrived; the test server above delivered two stock updates and then that error with a 0.15 second deadline.
gRPC has its own status codes, and the mapping to HTTP is worth knowing for interviews: NOT_FOUND is 404, INVALID_ARGUMENT is 400, UNAUTHENTICATED is 401, PERMISSION_DENIED is 403, ALREADY_EXISTS is 409, RESOURCE_EXHAUSTED is 429, UNAVAILABLE is 503 (and the one clients should retry with backoff), and DEADLINE_EXCEEDED is 504. Use abort with the precise code; never let every failure become UNKNOWN.
Protobuf evolution rules
On the wire, protobuf sends field numbers and values, not names. That one fact explains every evolution rule. Run this tiny encoder; it produces the same bytes as the real protobuf library for this message:
Press Run (⌘ Enter) to see what happens.From that, the rules:
- Adding a field is safe. Old readers skip unknown numbers; new readers see the default (
0,"",false) when it is absent. - Renaming is wire-safe (though it breaks generated code and JSON mappings, so treat it as a source change).
- Never reuse or change a field number. The last line shows the price silently read as stock, with no error anywhere. When you delete a field, add its number and name to
reservedso the compiler stops anyone reusing them. - Never change a field's type to an incompatible one. Some integer changes are compatible on the wire, but the rules are subtle; let a tool decide.
- proto3 has no
required. It was removed because a required field can never be safely removed. Validate presence in your code instead. Plain scalar fields cannot tell "absent" from "zero"; mark themoptionalwhen you need that difference (HasField("colour")).
Protobuf's newer Editions syntax (edition = "2023") replaces syntax = "proto3" with per-feature settings; most codebases still use proto3, and the wire rules are the same. Enforce all of this with buf breaking --against '.git#branch=main' in CI, the protobuf equivalent of the OpenAPI diff in OpenAPI, Generated Clients and Contract-First APIs.
Running gRPC in production
- Load balancing needs layer 7. gRPC multiplexes many calls over one long-lived HTTP/2 connection. A layer 4 load balancer balances connections, so one client pins all its traffic to one backend. Use an L7 proxy that understands HTTP/2 (Envoy, a service mesh, most cloud application load balancers with gRPC support) or client-side load balancing.
- Browsers cannot call gRPC directly. Use gRPC-Web through a proxy such as Envoy, or Connect, which speaks a browser-friendly protocol. Many teams keep a REST or GraphQL edge for browsers and use gRPC behind it.
- Debugging. You cannot
curlprotobuf. Enable server reflection (grpcio-reflection) in non-production environments and usegrpcurlor a GUI client to list services and call methods. Add the standard health service (grpcio-health-checking) so orchestrators can probe it. - Retries. Retry only
UNAVAILABLE(and sometimesRESOURCE_EXHAUSTED) with backoff, and only for idempotent methods, for the same reasons covered in Safe Retries with Idempotency Keys.
Choosing, in one table
| Situation | Usually pick | Why |
|---|---|---|
| Public API for third parties | REST + OpenAPI | Universal tooling, HTTP caching, easy to learn |
| Internal service-to-service, high call volume, many languages | gRPC | Compact binary, generated clients, streaming, deadlines |
| Several frontends with different data needs, or a backend-for-frontend | GraphQL | Clients choose the shape, one round trip per screen |
| Server pushing events to browsers | SSE or WebSockets | Covered in WebSockets in FastAPI |
Mixing is normal: a GraphQL or REST edge in front of gRPC services is a common architecture.
Match each gRPC status code to the HTTP status it corresponds to.
What does this print?
fields_v1 = {"sku": 1, "name": 2, "price_cents": 3}
fields_v3 = {"sku": 1, "name": 2, "stock": 3}
wire = {1: "KET-001", 2: "Kettle", 3: 2999} # number -> value
by_number = {n: name for name, n in fields_v3.items()}
decoded = {by_number[n]: v for n, v in wire.items()}
print(decoded.get("stock"), "price_cents" in decoded)- resolver
- The function that produces the value of one GraphQL field. Nested fields mean nested resolver calls.
- DataLoader
- A per-request helper that collects keys requested in one event loop tick and loads them with one batched query, caching the results for that request.
- persisted query
- A query registered ahead of time and sent by hash, so the server only runs queries it already knows.
- protobuf field number
- The integer that identifies a field on the wire. Names are not sent, so numbers must never be reused or changed.
- reserved
- A protobuf declaration that blocks deleted field numbers and names from being used again.
- deadline
- The absolute time by which a gRPC call must finish, set by the client and propagated to downstream calls.
- server streaming
- A gRPC call where the client sends one request and the server returns a stream of messages.