GraphQL & gRPC, the other API styles
GraphQL schemas, resolvers, the N+1 problem and DataLoader, field-level auth and query cost limits; gRPC with Protobuf, HTTP/2 streaming and when each beats REST.
GraphQL
The client asks for exactly the fields it needs, in one round trip:
query {
hostel(id: "h-1") {
name
rooms(available: true) { roomNumber capacity }
reviews(first: 3) { rating text author { name } }
}
}
With Spring for GraphQL:
# schema.graphqls
type Hostel { id: ID! name: String! rooms(available: Boolean): [Room!]! }
type Query { hostel(id: ID!): Hostel }
@Controller
class HostelGraphql {
@QueryMapping Hostel hostel(@Argument UUID id) { return hostels.find(id); }
@BatchMapping // DataLoader: ONE query for all hostels' rooms (solves GraphQL N+1)
Map<Hostel, List<Room>> rooms(List<Hostel> hostels) { return rooms.byHostels(hostels); }
}
Strengths: flexible clients (mobile and web need different shapes), a strongly typed schema with introspection, no endpoint explosion.
Challenges:
- N+1 across resolvers. Use DataLoader /
@BatchMapping. - HTTP caching is harder, since everything is a POST to
/graphql. Use persisted queries. - Auth per field.
- Malicious deep queries need depth and complexity limits.
- File uploads are awkward.
gRPC
A contract-first RPC framework using Protocol Buffers over HTTP/2:
syntax = "proto3";
service Ledger {
rpc Post (PostRequest) returns (PostReply);
rpc StreamBalances (BalanceQuery) returns (stream Balance); // server streaming
}
message PostRequest { string company_id = 1; repeated Line lines = 2; string idempotency_key = 3; }
message Line { string account_id = 1; int64 debit_minor = 2; int64 credit_minor = 3; }
Code generation produces typed clients and servers in many languages.
Strengths:
- A compact binary encoding, often 5–10× smaller and faster than JSON.
- Streaming in both directions, deadlines and cancellation.
- Strict contracts with backward-compatible evolution (field numbers).
Weaknesses: browsers need gRPC-Web or a proxy, payloads aren’t human-readable (debugging needs tools like grpcurl), and load balancing needs L7 awareness.
Choosing
| Need | Pick |
|---|---|
| Public API, simple clients, caching | REST |
| Many frontends with different data needs, aggregating several sources | GraphQL |
| Internal service-to-service, low latency, streaming, polyglot | gRPC |
| Real-time push | WebSocket / SSE (Module 5) |
Check yourself
1. GraphQL’s fix for resolver N+1?
2. gRPC runs over…