REST, gRPC, and GraphQL: Choosing an API Style by Caller
System Design series · Part 5 Service communication (1 of 5)
- REST, gRPC, and GraphQL: Choosing an API Style by Caller
- Message Queues: Decoupling, Peak Shaving, Retries, and Why Messages Will Be Duplicated
- Pub/Sub and Delivery Semantics: Kafka Partitions, Consumer Groups, and What Exactly-Once Really Guarantees
- Idempotency and Idempotency Keys: Making Retries Safe
- Real-Time Updates: Choosing Between Polling, Long Polling, SSE, and WebSocket, and Pushing from Many Servers
System Design series Part 5-1 | Previous: Distributed Locks and Fencing Tokens | Next: Message Queues | Series map
Read first: Part 2-2 Load Balancing in Depth.
Scenario and problem
Once the talk platform is split into sign-up, talk, and notification services, the API has three kinds of callers, and their needs are very different:
- Partners: corporate customers use the API to look up talks and sign up their employees. They might use any language and any tools; what they care about most is that it is easy to pick up, stable, and clearly documented
- The home screen of our own app: one screen shows talks, speakers, seats left, and my sign-up status. Different app versions and different screens want different fields, and every round trip over a mobile network is expensive
- Between services: on every sign-up, the sign-up service checks seats and times with the talk service, thousands of times a second at peak; the speaker dashboard also has to see new sign-ups in real time, which needs the server to push them
- PartnersCorporate customers use the API to look up talks and sign up their employees. They might use any language and any tools; what they care about most is that it is easy to pick up, stable, and clearly documented.
- The home screen of our own appOne screen shows talks, speakers, seats left, and my sign-up status. Different app versions and different screens want different fields, and every round trip over a mobile network is expensive.
- Between servicesOn every sign-up, the sign-up service checks seats and times with the talk service, thousands of times a second at peak, and every millisecond counts.
- Server pushThe speaker dashboard has to see new sign-ups in real time. It cannot keep asking, so the server has to push them.
The simplest approach and its limits
Use REST + JSON for everything:
- App home screen: it takes 4 or 5 API calls to put one screen together. A dedicated API for the home screen solves that, but then every screen and every app version needs one, and the number of APIs keeps growing; sharing one API instead returns lots of fields nobody uses
- Between services: every call serializes and parses JSON; a renamed field or a changed type only shows up at runtime; and there is no built-in way to pass “how much longer the caller is willing to wait” downstream
- Real-time push: HTTP’s one-request, one-response model is a poor fit for long-lived streams
This does not mean REST is bad. Different callers suit different tools.
Core mechanism
REST: use the semantics of HTTP itself
REST is centered on resources and expresses operations with HTTP methods. Its biggest advantage is that it can use the whole HTTP ecosystem directly: browsers, curl, CDNs, reverse proxies, and caches all understand it.
The HTTP specification (RFC 9110) gives each method clear semantics, and these semantics affect caching and retries:
| Method | Safe (does not change state) | Idempotent (same result when run many times) | Use |
|---|---|---|---|
| GET, HEAD | Yes | Yes | Reads; cacheable, and can be retried directly on failure |
| PUT | No | Yes | Replace the whole resource |
| DELETE | No | Yes | Delete |
| POST | No | No | Create, or any other operation that does not fit the semantics above |
| PATCH | No | Not necessarily | Partial update |
POST is not idempotent, so a retry after a network timeout may create two records. A POST that creates something should support Idempotency-Key; the idempotency post in Part 5 covers this in detail.
Conditional requests are a REST capability that often gets overlooked:
ETag+If-None-Match: the client asks with the version it got last time; if the content has not changed, the server returns304 Not Modifiedwithout the content, saving bandwidth and serializationIf-Match: an update carries the version, and a mismatch returns412 Precondition Failed. This puts optimistic locking into the API contract, so that when two people edit at the same time, the later write does not silently overwrite the earlier one
Other points of REST design:
- Put the version in the path (
/v1/lectures), and bump it only for incompatible changes; adding a field or an optional parameter does not count - Use cursor pagination for large data sets: the cursor encodes “the sort column’s value + the primary key”, not an offset under another name
- One error format: standard Problem Details (RFC 9457) or a format your team defines both work. What matters is that every API is consistent and carries an error code for programs to check. HTTP status codes still have to be correct
- Describe the contract with OpenAPI (springdoc-openapi)
gRPC: define the contract first, then generate code
gRPC defines services and messages in a .proto file, then uses tools to generate client and server code in many languages.
- Protocol Buffers is a binary format: smaller than JSON and faster to parse; fields are identified by number, not by name
- Runs on HTTP/2: one connection can carry many calls at once, and it supports four call types: one request, one response (unary), server streaming, client streaming, and bidirectional streaming
- Deadlines are first-class: the client specifies “the latest time it needs the result by”, and the server can see how much time is left. gRPC has no deadline by default; a client that does not set one may wait forever. gRPC for Java automatically propagates the deadline it received to downstream calls, converted to the time remaining, so clock skew between the two machines does not affect it
- Status codes:
DEADLINE_EXCEEDED,UNAVAILABLE,NOT_FOUND,RESOURCE_EXHAUSTED, and so on, closer to RPC semantics than HTTP status codes
What it costs:
- Browsers cannot call it directly: you need gRPC-Web and a proxy (such as Envoy), or a translation to REST at the edge
- Not a human-readable format: debugging takes a tool like grpcurl, and depends on the server enabling reflection or on having the
.protoat hand - Long-lived connections defeat L4 load balancing: once a connection is established, every call on it goes to the same server (Load Balancing post), so you need L7 or client-side load balancing
- Messages are limited to 4 MiB by default (grpc-java); anything larger fails with
RESOURCE_EXHAUSTED
Rules for schema evolution: the field number is the field’s identity. Add a new field with a new number, and old clients ignore fields they do not recognize; when you delete a field, mark its number reserved, and never reuse it. A reused number makes old and new versions read the same bytes as different things, and nothing reports an error.
GraphQL: let the client decide what it wants
GraphQL has a single endpoint. The server publishes a typed schema, and in one request the client describes which fields it wants and which relationships to expand:
query HomePage {
upcomingLectures(first: 10) {
title
startsAt
remainingSeats
speaker { name }
}
}The app home screen gets the data it needs in one request, no more and no less. A new screen only needs a changed query; the server does not need a new API.
What it costs:
- N+1 queries: each field is fetched by its own resolver. A naive implementation first queries 10 talks, then queries the speaker once for each talk, 11 queries in total. The fix is DataLoader: within one request, first collect all the speaker IDs to look up, then fetch them in one batch query
- HTTP caching does not help: queries are usually sent by POST to the same URL, so CDNs and browser caches have nothing to cache. The usual approach is persisted queries: register the allowed queries in advance, and the client sends only the query’s ID, which can then go over GET and be cached
- Errors are often 200: when some fields fail, the response is still HTTP 200, with the errors in the response’s
errorsarray alongside the data that did succeed. Monitoring that looks only at HTTP status codes misses the errors - The client decides what a query costs: one query can expand very deep and ask for a lot of data, so the server has to limit depth and complexity (see Security)
Comparison
| REST | gRPC | GraphQL | |
|---|---|---|---|
| Contract | OpenAPI (optional) | .proto (required) |
Schema (required) |
| Encoding | JSON, human-readable | Protobuf binary | JSON |
| Transport | HTTP/1.1 or HTTP/2 | HTTP/2 | HTTP; subscriptions often use WebSocket |
| HTTP caching | Works directly | Not applicable | Needs persisted queries |
| Browser | Calls it directly | Needs gRPC-Web and a proxy | Calls it directly |
| Streaming | Handled separately (SSE, WebSocket) | Four built-in modes | Subscriptions |
| Debugging | curl is enough | Needs grpcurl and reflection | Tools such as GraphiQL |
| Best-fit callers | Public APIs, partners, simple CRUD | Internal services, many languages, high frequency, streaming | Many frontends, changing screens, deeply related data |
Comparing options
The talk platform’s choices:
| Caller | Choice | Reason |
|---|---|---|
| Partners | REST + OpenAPI | Any language can call it, HTTP caching works, the most mature docs and tools |
| Our own app | GraphQL, or a REST BFF designed around screens | Screens change fast; one request gathers all the data |
| Sign-up service → talk service | gRPC | High-frequency calls, strongly typed contract, deadline propagation |
| Live sign-ups on the speaker dashboard | gRPC server streaming (internal); SSE or WebSocket for browsers | Server push |
Mixing them in one system is common: gRPC inside, REST or GraphQL at the edge, with a BFF or an API gateway translating between them.
The simplest option is always worth considering first: with only one frontend and a small team, REST for everything, plus one BFF API for each of a few complex screens, usually costs less than bringing in the toolchain and operating cost of GraphQL or gRPC.
In Java
1. REST: conditional GET and If-Match
@RestController
@RequestMapping("/v1/lectures")
public class LectureController {
private final LectureService lectureService;
public LectureController(LectureService lectureService) {
this.lectureService = lectureService;
}
@GetMapping("/{id}")
public ResponseEntity<LectureView> get(@PathVariable long id) {
Lecture lecture = lectureService.find(id);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(Duration.ofSeconds(30)))
.eTag(Long.toString(lecture.version())) // when If-None-Match matches, Spring returns 304 automatically
.body(LectureView.from(lecture));
}
@PutMapping("/{id}")
public ResponseEntity<LectureView> replace(@PathVariable long id,
@RequestHeader(HttpHeaders.IF_MATCH) String ifMatch,
@Valid @RequestBody LectureUpdate body) {
long expectedVersion = Long.parseLong(ifMatch.replace("\"", ""));
Lecture updated = lectureService.replace(id, expectedVersion, body); // throws on a version mismatch, mapped to 412
return ResponseEntity.ok()
.eTag(Long.toString(updated.version()))
.body(LectureView.from(updated));
}
}- It returns a
LectureView, not the entity, and accepts aLectureUpdate, not the entity, so the shape of the API is decoupled from the table (this also matters for security) - The version number is JPA’s
@Versionfield;replacecompares versions on update and throws an exception on a mismatch, which an@ExceptionHandlerturns into 412
2. gRPC: the internal seat lookup and sign-up stream
syntax = "proto3";
package lecture.v1;
option java_package = "com.example.lecture.v1";
option java_multiple_files = true;
service LectureService {
rpc GetSeats(GetSeatsRequest) returns (Seats);
rpc WatchRegistrations(WatchRegistrationsRequest) returns (stream RegistrationEvent);
}
message GetSeatsRequest {
int64 lecture_id = 1;
}
message Seats {
int64 lecture_id = 1;
int32 capacity = 2;
int32 remaining = 3;
reserved 4; // the deleted waitlist_size; this number can never be reused
reserved "waitlist_size";
}
message WatchRegistrationsRequest {
int64 lecture_id = 1;
}
message RegistrationEvent {
int64 member_id = 1;
string status = 2;
}On the server, extend the generated ImplBase:
public class LectureGrpcService extends LectureServiceGrpc.LectureServiceImplBase {
private final SeatRepository seatRepository;
private final RegistrationEvents registrationEvents;
public LectureGrpcService(SeatRepository seatRepository, RegistrationEvents registrationEvents) {
this.seatRepository = seatRepository;
this.registrationEvents = registrationEvents;
}
@Override
public void getSeats(GetSeatsRequest request, StreamObserver<Seats> responseObserver) {
Optional<SeatCount> count = seatRepository.find(request.getLectureId());
if (count.isEmpty()) {
responseObserver.onError(Status.NOT_FOUND
.withDescription("lecture " + request.getLectureId())
.asRuntimeException());
return;
}
responseObserver.onNext(Seats.newBuilder()
.setLectureId(request.getLectureId())
.setCapacity(count.get().capacity())
.setRemaining(count.get().remaining())
.build());
responseObserver.onCompleted();
}
@Override
public void watchRegistrations(WatchRegistrationsRequest request,
StreamObserver<RegistrationEvent> responseObserver) {
ServerCallStreamObserver<RegistrationEvent> observer =
(ServerCallStreamObserver<RegistrationEvent>) responseObserver;
Subscription subscription = registrationEvents.subscribe(request.getLectureId(),
event -> observer.onNext(RegistrationEvent.newBuilder()
.setMemberId(event.memberId())
.setStatus(event.status())
.build()));
observer.setOnCancelHandler(subscription::cancel); // stop pushing when the client disconnects or the deadline expires
}
}On the client, the channel is a long-lived object, and the whole application shares one; set a deadline on every call:
ManagedChannel channel = ManagedChannelBuilder.forTarget("dns:///lecture-service:9090")
.defaultLoadBalancingPolicy("round_robin") // the default pick_first connects to only one server
.useTransportSecurity()
.build();
LectureServiceGrpc.LectureServiceBlockingStub stub = LectureServiceGrpc.newBlockingStub(channel);
try {
Seats seats = stub.withDeadlineAfter(300, TimeUnit.MILLISECONDS)
.getSeats(GetSeatsRequest.newBuilder().setLectureId(lectureId).build());
// ...
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.Code.DEADLINE_EXCEEDED) {
// the talk service is too slow: report "cannot confirm seats right now" instead of waiting forever
}
throw e;
}With dns:/// and round_robin, DNS has to return the address of every server. On Kubernetes that means a headless Service; a regular Service returns only one virtual IP, and client-side load balancing stops working.
3. GraphQL: the app home screen
type Query {
upcomingLectures(first: Int = 20): [Lecture!]!
}
type Lecture {
id: ID!
title: String!
startsAt: String!
remainingSeats: Int!
speaker: Speaker!
}
type Speaker {
id: ID!
name: String!
}@Controller
public class HomeGraphQlController {
private final LectureService lectureService;
private final SpeakerService speakerService;
public HomeGraphQlController(LectureService lectureService, SpeakerService speakerService) {
this.lectureService = lectureService;
this.speakerService = speakerService;
}
@QueryMapping
public List<Lecture> upcomingLectures(@Argument int first) {
return lectureService.upcoming(Math.min(first, 50)); // the server decides the upper limit
}
/** Loads the speakers of this whole batch of talks at once, instead of one query per talk. */
@BatchMapping
public Map<Lecture, Speaker> speaker(List<Lecture> lectures) {
Set<Long> speakerIds = lectures.stream().map(Lecture::speakerId).collect(Collectors.toSet());
Map<Long, Speaker> byId = speakerService.findAllById(speakerIds);
return lectures.stream().collect(Collectors.toMap(l -> l, l -> byId.get(l.speakerId())));
}
}@BatchMapping registers a DataLoader that merges the speaker field of every talk in one request into a single call. Lecture is used as a Map key, so it must implement equals and hashCode correctly; a record is the simplest way to get that.
Limit query depth and complexity, and turn off introspection in production:
@Configuration(proxyBeanMethods = false)
public class GraphQlLimits {
@Bean
public MaxQueryDepthInstrumentation maxQueryDepth() {
return new MaxQueryDepthInstrumentation(8);
}
@Bean
public MaxQueryComplexityInstrumentation maxQueryComplexity() {
return new MaxQueryComplexityInstrumentation(200);
}
}spring.graphql.schema.introspection.enabled=falseSpring Boot registers Instrumentation beans with the GraphQL engine automatically.
The code above is written from the official documentation of Spring Framework, Spring for GraphQL, Spring Boot, grpc-java, and GraphQL Java; it has not been compiled or run.
Pitfalls and gotchas
- PATCH treated as a full overwrite: PATCH should update only the fields that appear in the request. To replace the whole resource, use PUT
- Pagination without ordering: without an explicit
ORDER BY, the order of the data is unstable from page to page, and rows get repeated or skipped - No deadline on gRPC: when a downstream service hangs, the upstream threads and connections are held along with it, and the whole call chain locks up (Timeouts and Retries in Part 6)
- A new gRPC channel for every call: a channel holds a connection pool and name resolution, so it is expensive to create and should be shared
- A streaming
StreamObserveris not thread-safe: several threads callingonNextat the same time breaks it, so make sure only one thread pushes at a time. When the client reads slowly, the messages the server pushes pile up in memory; useisReady()andsetOnReadyHandlerfor flow control - Reused Protobuf field numbers: an older version of a service reads the new field with the old meaning; nothing reports an error, it just produces wrong data
- N+1 in GraphQL: check every relationship field for batch loading, or one query may fire hundreds of database queries
- Taking a GraphQL 200 as success: monitoring and alerts have to look at
errorsin the response
Security
- Object-level authorization (BOLA):
GET /v1/lectures/{id}/registrationschecks only that you are “logged in”, not that “this talk is yours”, so changing the ID shows someone else’s sign-up list. It is the same in all three styles: check ownership on every object access (covered in detail in Part 8) - Mass assignment: binding the request body straight to an entity lets an attacker send one extra
"status": "APPROVED"or"role": "ADMIN"and have it written to the database. Always use dedicated DTOs for requests and responses - Query cost attacks on GraphQL: types that refer to each other (talk → speaker → the speaker’s talks → …) let an attacker build a very deep query that exhausts the server’s resources in a single request. Limit depth and complexity; a public API in production should ideally accept only persisted queries
- GraphQL aliases and batching get around rate limits: one request uses aliases to call the same mutation a hundred times (for example, to try a hundred discount codes), and a rate limit that counts requests counts it only once. Rate limits have to count per operation or per field
- Field-level authorization in GraphQL: put authorization on each resolver or on the service method it calls (for example
@PreAuthorize), not only at the entry point. A client can reach a sensitive field from any entry query - Introspection and gRPC reflection: both expose the full structure of the API, which helps attackers find hidden operations. Turn them off in public production environments; enable them internally as needed
- Internal gRPC needs encryption and authentication too: “it is on the internal network” is no reason to trust it. Use mTLS between services, and have the server authorize by the caller’s identity (service identity in Part 8)
- Error messages that leak internal details: keep stack traces, SQL errors, and internal hostnames out of responses, including GraphQL
errorsand gRPC status descriptions
When to use it, and when not to
- REST: public APIs, partners, when you need HTTP caching, when the team does not want to bring in an extra toolchain
- gRPC: between internal services, many languages, high-frequency calls, when you need streaming and deadline propagation; not suited to direct use by browsers or third parties
- GraphQL: many frontends, fast-changing screens, deeply related data; not suited to simple CRUD, to public content that needs a lot of HTTP caching, or to a team not yet ready to deal with N+1 and query cost limits
References
- RFC 9110, “HTTP Semantics”, 2022: https://www.rfc-editor.org/rfc/rfc9110
- RFC 9457, “Problem Details for HTTP APIs”, 2023: https://www.rfc-editor.org/rfc/rfc9457
- Roy T. Fielding, “Architectural Styles and the Design of Network-based Software Architectures”, Ph.D. dissertation, UC Irvine, 2000
- gRPC — Deadlines: https://grpc.io/docs/guides/deadlines/
- gRPC — Reflection: https://grpc.io/docs/guides/reflection/
- gRPC — Error handling: https://grpc.io/docs/guides/error/
- Protocol Buffers — Language Guide (proto 3): https://protobuf.dev/programming-guides/proto3/
- GraphQL Specification: https://spec.graphql.org/
- GraphQL Java — Instrumentation: https://www.graphql-java.com/documentation/instrumentation
- Spring for GraphQL — Controllers (Batch Mapping): https://docs.spring.io/spring-graphql/reference/controllers.html
- Spring Framework — HTTP Caching: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-caching.html
- OWASP API Security Top 10 (2023): https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments