Networking

REST vs gRPC vs GraphQL

The design idea behind each API style, what each costs, how pagination, versioning and idempotency work across them, and how to choose one for a given product.

Lesson14 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A team ships a REST API and then builds a mobile screen that shows a user’s last ten orders with their items. The app calls GET /users/42, then GET /users/42/orders, then GET /orders/{id}/items once for each order. That is twelve requests over a mobile network, and each response carries dozens of fields the screen never shows. The backend team adds a special /mobile/order-history endpoint. Then one for the next screen. A year later the API is a pile of screen-shaped endpoints that nobody dares change.

Meanwhile, inside the same company, services call each other with JSON over HTTP using hand-written clients. Someone renames a field. Nothing fails at build time. A consumer breaks in production.

These are two different problems, and the three main API styles answer them differently. REST was described by Roy Fielding in his 2000 dissertation as the architecture of the web itself. Facebook built GraphQL in 2012 for its mobile apps and published it in 2015. Google open-sourced gRPC in 2015, as a successor to its internal RPC system, Stubby.

REST

REST models the system as resources, each with a URL, manipulated through the standard HTTP methods. Requests are stateless, responses say whether they can be cached, and status codes carry the outcome.

Method Idempotent Typical use
GET Yes (and safe: it changes nothing) Read a resource
PUT Yes Replace a resource at a known URL
DELETE Yes Remove a resource
POST No Create a resource, or trigger an action
PATCH Not guaranteed Partial update

Idempotency matters because networks lose responses and clients retry. Repeating a PUT leaves the same state. Repeating a POST may create two orders. For creation that must be retried safely, the client sends an idempotency key and the server remembers the result for that key. See idempotency.

Strengths. Every language, proxy, browser and CDN speaks it. GET responses are cacheable by URL. You can debug it with curl. Clients and servers are loosely coupled.

Costs. Fixed response shapes cause over-fetching and under-fetching, which was the twelve-request problem. There is no enforced contract unless you add one with OpenAPI. There is no standard streaming.

gRPC

gRPC starts from a schema. You describe services and messages in Protocol Buffers, and a compiler generates client and server code in each language.

service Orders {
  rpc GetOrder(GetOrderRequest) returns (Order);
  rpc WatchOrder(GetOrderRequest) returns (stream OrderEvent);
}

Calls travel over HTTP/2 as compact binary messages. There are four call types: unary, server streaming, client streaming and bidirectional streaming. Deadlines and cancellation are part of the protocol, so a caller’s timeout can propagate down a chain of services.

Strengths. A renamed field is a compile error, not a production incident. Messages are smaller and cheaper to parse than JSON. Streaming is built in.

Costs. Browsers cannot make native gRPC calls, so web clients need gRPC-Web and a translating proxy. Payloads are not human-readable. Everything is a POST, so HTTP caching does not apply. And because calls share long-lived HTTP/2 connections, you need an L7 load balancer or client-side balancing, or one backend gets all the traffic.

GraphQL

GraphQL exposes one endpoint and a typed schema. The client sends a query that names exactly the fields it wants, across related objects, and gets that shape back.

query {
  user(id: 42) {
    name
    orders(first: 10) { id total items { name quantity } }
  }
}

That is the twelve-request screen in one round trip, with no unused fields. On the server, each field has a resolver function, and the server walks the query calling them.

Strengths. One request per screen. Front-end teams add fields to a query without waiting for a new endpoint. The schema is introspectable, which gives good tooling.

Costs. The flexibility moves work to the server, in three ways.

The N+1 problem in GraphQL resolvers and the batching fix4 components: Client, GraphQL server, Batch loader, Database. Connections: Client to GraphQL server (one query); GraphQL server to Database (naive resolvers); GraphQL server to Batch loader (load(authorId)); Batch loader to Database (one batched query).ClientGraphQL serverone resolver per fieldBatch loadercollects keys per requestDatabaseone querynaive resolversload(authorId)one batched query

Step 1 of 7

The client asks for the 20 latest posts and the name of each post's author, in one GraphQL query. From the client's side this is the whole appeal, a single round trip for a nested screen.

Read the steps as text
  1. The client asks for the 20 latest posts and the name of each post's author, in one GraphQL query. From the client's side this is the whole appeal, a single round trip for a nested screen.
  2. The server runs the resolver for the posts field. That is one database query, and it returns 20 rows.
  3. Now the author resolver runs once for each post. Each call knows only its own post, so each one issues its own query. Twenty posts mean twenty more queries, one after another.
  4. This is the N plus one problem. The client made one request, but the database saw 21. Ask for each author's avatar as well and it grows again. Nothing in the query warned anyone.
  5. The usual fix is a batch loader. Each author resolver hands its key to the loader and gets a promise back, instead of querying. The loader waits until the resolvers at that level have all asked.
  6. Then the loader removes duplicates and issues a single query for all the authors at once. It hands each resolver its own row, and remembers the rows for the rest of this request.
  7. The client still made one request, and the database now sees two queries however many posts there are. GraphQL moves the N plus one problem from the client to the server, where you have to solve it on purpose.
The N+1 problem in GraphQL resolvers and the batching fix
  • N+1 queries. Resolvers run per item, so a list of N posts with authors costs 1 + N database queries unless you batch them, as shown above.
  • Caching. Queries normally arrive as POST requests to one URL, so CDNs and HTTP caches cannot key on them. The workarounds are persisted queries sent as GET, caches inside the client, and caching in the resolvers.
  • Cost control. A client can write a deeply nested query that is very expensive. Counting requests is not enough for rate limiting. You need depth limits, query cost analysis, or an allow-list of known queries.

Errors also behave differently. A GraphQL response is commonly HTTP 200 with an errors array, so dashboards that count 5xx responses miss failures.

Pagination and versioning

These apply to all three styles.

Pagination. offset and limit are simple and let a user jump to page 50, but the database must read and discard every skipped row, and rows inserted meanwhile cause duplicates or gaps. Cursor pagination returns an opaque token that encodes the last item’s sort key, and the next page is “items after this”. It uses an index, stays stable under inserts, and cannot jump to an arbitrary page. Use cursors for feeds and anything large. REST returns a next link or token, gRPC uses a page_token field by convention, and GraphQL has the connection pattern with edges and cursor.

Versioning. The cheapest version is the one you never make: add fields, and do not remove or change them.

Style Usual approach to change
REST A version in the path (/v1/) or a header. Old versions run until clients migrate
gRPC Add fields with new numbers. Never reuse or renumber. A new package (orders.v2) for breaking changes
GraphQL One evolving schema. Add fields, mark old ones @deprecated, remove them when usage reaches zero

When to choose each

Situation Choose Why
Public API for third-party developers REST Universal, cacheable, no special tooling
Simple CRUD, with reads served through a CDN REST URLs map directly to cache keys
Calls between internal services gRPC Typed contracts, efficiency, deadlines
Streaming between services gRPC Streaming is part of the protocol
Many client types, nested data from several backends GraphQL Each client fetches its own shape in one round trip
Browser to server, small team, one client REST Least machinery

And when not to. Do not choose gRPC for a public browser API. Do not choose GraphQL for a simple service with one client, or when CDN caching is central to your design: you take on resolvers, batching and query cost analysis for little gain. Do not stay with chatty REST calls from a mobile client when a backend for frontend or GraphQL would collapse them into one.

In the interview

In the API step of a design, name the style and give one reason tied to the product: “public REST API, because third parties integrate with it and reads are cacheable”, or “gRPC between services for typed contracts and deadlines”.

Then show the details that mark a senior answer. Make create calls retry-safe with an idempotency key. Paginate lists with cursors. Evolve by adding fields. If you propose GraphQL, raise N+1 batching and query cost limits before the interviewer does. If you propose gRPC, mention how browsers reach it and how connections are balanced.

Key takeaways

  • REST models resources with URLs and standard HTTP methods. It is universal, cacheable and easy to debug, but can need many round trips.
  • gRPC defines services in a schema, generates clients, and sends compact binary messages over HTTP/2, with streaming built in. Browsers cannot call it natively.
  • GraphQL lets the client ask for exactly the fields it needs in one request. It moves the N+1 problem to the server and makes HTTP caching and cost control harder.
  • GET, PUT and DELETE are idempotent. POST is not, so creation that may be retried needs an idempotency key.
  • Prefer cursor pagination for large or changing lists, and additive changes over new versions in every style.
  • A common mix is REST for public APIs, gRPC between internal services, and GraphQL as a backend for frontend.

Check yourself

1. A mobile client sends POST /orders, the response is lost to a timeout, and the client retries. The customer is charged twice. What is the standard fix?
2. A GraphQL query asks for 50 posts and each post's author. The database log shows 51 queries. What is the usual remedy?
3. Why is a typical GraphQL API harder to cache at a CDN than a REST API?
4. Which change to a protobuf message is safe for existing gRPC clients and servers?
5. A list endpoint uses offset and limit. Deep pages are slow, and users see duplicate items while new rows are being inserted. What should replace it?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Which HTTP methods are idempotent, and why does it matter?

GET, PUT and DELETE (and HEAD) are idempotent, so repeating them leaves the same state. POST is not, and PATCH is not guaranteed to be. It matters because clients and proxies retry after timeouts.

What are gRPC's four call types?

Unary (one request, one response), server streaming, client streaming and bidirectional streaming, all carried as HTTP/2 streams.

What is the N+1 problem in GraphQL?

A resolver for a nested field runs once per parent item and issues its own query, so a list of N items costs 1 + N database queries. Batch loaders fix it.

Offset versus cursor pagination?

Offset is simple and allows jumping to a page, but is slow at depth and unstable when rows are inserted. Cursor pagination seeks from the last item seen, so it is fast and stable, but only moves forward or back.

How does each style handle versioning?

REST commonly puts a version in the path or a header. Protobuf evolves by adding numbered fields and never reusing numbers. GraphQL evolves one schema by adding fields and deprecating old ones.

When would you choose each style?

REST for public and browser-facing APIs. gRPC for internal service-to-service calls and streaming. GraphQL when many clients need different shapes of nested data from several backends.

Review the deck