REST, GraphQL, gRPC: one screen, four ways

A profile screen needs a name, an avatar, three post titles and a comment count for each. Load it with REST, with an endpoint made for the screen, with GraphQL and with gRPC, and count the requests, the round trips and the bytes.

Level: IntermediateWatch: 10 steps · ~1 minuteFour ways, three networksRecall: 3 questions · 8 cardsCompare 4 waysTypeScript · protobuf

What you'll take away

  • Count the requests and round trips one screen takes in REST, GraphQL and gRPC
  • Explain why round trips, more than bytes, decide how long a phone waits
  • Spot overfetching, underfetching and GraphQL's N+1, and fix N+1 by batching
  • Pick REST, GraphQL or gRPC by caching, browser support and who is calling

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
REST: the user and their posts4G: an 80 ms round trip
↗ GET /users/42 + GET /users/42/posts2 × GET
80 ms a trip
REST APIREST
database
the profile screen
t = 0 ms (model)
GET /users/42 + /users/42/posts → …2 × GET → …
Step 1 / 10 · step by step
…waited so far (model)
0 · 0requests · round trips
…bytes, measured

The picture: you hold the phone on its plaza, its screen the profile being loaded, grey until an answer fills that part. The long street is the mobile network and the API server stands at its far end, its database next door. Violet lights are requests going up, blue ones answers coming back; an amber ring means the answer carries fields the screen never shows. A gRPC call travels in a glass tube, one HTTP/2 connection; GraphQL's lookups run to the database and light its roof. One step is one round trip. Requests, round trips and bytes were measured by the code below; the time is a model built on them, and the server's 5 ms is drawn slower so you can see it.

Step 4 · Every option at once, on one clock

Compare them all: REST, GraphQL, gRPC

The same profile screen: a name, an avatar, the three latest posts and their comment counts, on Wi-Fi, 4G and a weak signal. Each bar is the time to the whole screen; below, the requests, round trips and bytes measured by the real code.

1/3 · Office Wi-Fi: a 10 ms round trip
REST by resourcea URL per resource, answered whole5 requests · 2 round trips · 3.4 KB

Use it when Public APIs: easy to read, try with curl or a browser, and a GET can be cached by browsers and CDNs by its URL

Skip it when Screens that join many resources: many requests, rounds that wait on each other, and fields nobody shows

Bytes and round trips are measured by the code below (no TLS, no compression); the times are a model built on them. Press any tile to see it large above, with when it fits.

Which suits what

StyleOne screen (measured)HTTP cachingFrom a browserSuits
REST by resource5 requests, 2 round trips, 3,402 bytesa GET, by its URLyespublic APIs, data worth caching
REST, an endpoint per screen1 request, 1 round trip, 608 bytesa GET, by its URLyesa busy screen, a mobile app's own backend
GraphQL1 request, 1 round trip, 816 bytesnot for a POST; a GET or a persisted query can beyesmany kinds of client, one graph
gRPC5 calls, 2 round trips, about 1,700 bytesnoonly through gRPC-Web and a proxyservices talking to each other

Round trips decide on a phone

For a small screen the bytes hardly matter on a good network; each round trip costs the whole way there and back. A second round that waits for the first doubles the wait. One request that carries everything, from a screen endpoint or a GraphQL query, halves it, and on a weak signal the bytes start to count too.

Caching

A REST GET is cached by its URL in the browser and on a CDN. GraphQL runs on one endpoint, usually /graphql, and must take POST; it may take GET for queries, which can then be cached at the edge, and persisted queries send a short id instead of the query text (GraphQL: serving over HTTP). With no URL per object, clients often cache by each object's id instead (GraphQL: caching).

gRPC in a browser

No browser API gives enough control over an HTTP/2 request to speak gRPC, so a page uses gRPC-Web, and a proxy in front of the server translates (gRPC: the state of gRPC in the browser); gRPC's own guide uses Envoy (gRPC-Web basics). By default gRPC sets no deadline, so a call can wait for ever: set one, and the client fails it with DEADLINE_EXCEEDED (gRPC: deadlines).

The joins move to the server

One GraphQL request can still make many lookups: a plain resolver per item is the N+1 problem, usually fixed by batching the keys of one tick into one lookup, as DataLoader does (GraphQL: performance).

Contracts and tools

REST's contract is optional: OpenAPI describes an HTTP API in a standard, language-agnostic way (OpenAPI Specification). A GraphQL schema is always there, typed, and can be asked about itself, which documentation and IDE tools use (GraphQL: introspection). gRPC starts from a .proto file, and protoc generates client and server code in many languages (gRPC: introduction).

In real code

rest.ts
// REST: one URL per resource, each answered with the whole resource. The profile screen needs the user, the user's
// three latest posts, and each post's comments (to count them): 5 requests, and the comments can only be asked for
// once the posts have come back. Then the same screen from one endpoint made for it (a "backend for frontend").
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import assert from "node:assert/strict";
import { comments, EXPECTED, fmt, latestPosts, roundTrips, users, wire, type Comment, type Post, type Screen, type User } from "./wire.ts";

let requests = 0;
const routes: [RegExp, (m: RegExpMatchArray, url: URL) => unknown][] = [
  [/^\/users\/(\d+)$/, (m) => users.find((u) => u.id === Number(m[1]))],
  [/^\/users\/(\d+)\/posts$/, (m, url) => latestPosts(Number(m[1]), Number(url.searchParams.get("limit") ?? 10))],
  [/^\/posts\/(\d+)\/comments$/, (m) => comments.filter((c) => c.postId === Number(m[1]))],
  // The screen endpoint: the server joins it all and sends only what the screen shows.
  [/^\/screens\/profile\/(\d+)$/, (m) => {
    const u = users.find((x) => x.id === Number(m[1]))!;
    return { name: u.name, avatar: u.avatar, posts: latestPosts(u.id, 3).map((p) => ({ title: p.title, comments: comments.filter((c) => c.postId === p.id).length })) };
  }],
];
const api = createServer((req: IncomingMessage, res: ServerResponse) => {
  requests++;
  const url = new URL(req.url ?? "/", "http://api");
  for (const [re, answer] of routes) {
    const m = url.pathname.match(re);
    if (m && req.method === "GET") {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify(answer(m, url)));
    }
  }
  res.writeHead(404).end();
});
await new Promise<void>((ok) => api.listen(0, "127.0.0.1", ok));
const net = await wire((api.address() as AddressInfo).port);
const base = `http://127.0.0.1:${net.port}`;
const get = async <T>(path: string): Promise<T> => (await fetch(base + path)).json() as Promise<T>;

async function profileByResource(id: number): Promise<Screen> {
  // Round trip 1: the user and the posts at once. Round trip 2: each post's comments, now that we know the posts.
  const [user, latest] = await Promise.all([get<User>(`/users/${id}`), get<Post[]>(`/users/${id}/posts?limit=3`)]);
  const lists = await Promise.all(latest.map((p) => get<Comment[]>(`/posts/${p.id}/comments`)));
  return { name: user.name, avatar: user.avatar, posts: latest.map((p, i) => ({ title: p.title, comments: lists[i].length })) };
}

await get(`/users/42`); // open a connection first: what follows is measured on a connection already open
net.reset(); requests = 0;
const byResource = await roundTrips(() => profileByResource(42));
const [restBytes, restRequests] = [net.total(), requests];

net.reset(); requests = 0;
const byScreen = await roundTrips(() => get<Screen>(`/screens/profile/42`));
const [screenBytes, screenRequests] = [net.total(), requests];

assert.deepEqual(byResource.value, EXPECTED);
assert.deepEqual(byScreen.value, EXPECTED);
assert.equal(restRequests, 5);
assert.equal(byResource.trips, 2);
assert.equal(screenRequests, 1);
assert.equal(byScreen.trips, 1);
assert.ok(screenBytes < restBytes / 3);
console.log(`REST, one profile screen: ${restRequests} requests in ${byResource.trips} round trips, ${fmt(restBytes)} bytes on the wire · from one endpoint made for the screen: ${screenRequests} request in ${byScreen.trips} round trip, ${fmt(screenBytes)} bytes`);
await net.close();
api.closeAllConnections();
api.close();
Run: npm install, then node rest.ts (package.json pins exact versions · on Node 22 add --experimental-strip-types)It printed: REST, one profile screen: 5 requests in 2 round trips, 3,402 bytes on the wire · from one endpoint made for the screen: 1 request in 1 round trip, 608 bytes

A node:http server with a URL per resource, and the screen loaded the usual way: the user and the posts at once, then each post's comments. Then one endpoint made for the screen. Bytes counted by wire.ts on a connection already open, round trips from the time. It really runs.

Common questions

What's the difference between REST, GraphQL and gRPC?

REST gives each resource a URL and answers it whole. GraphQL has one endpoint where the client writes a query naming the fields it needs. gRPC calls methods from a .proto file, sending protobuf (binary) over HTTP/2. All three can fetch the same data; they differ in round trips, size, and who does the extra work.

Is GraphQL faster than REST?

Not by itself. It helps when a screen needs many resources: one round trip and no extra fields. A REST endpoint made for the screen gets one round trip too, and the server still has to find every piece either way.

What are overfetching and underfetching?

Overfetching: an answer holds fields you don't use, like asking for a user's name and getting their email, bio and follower count too. Underfetching: one answer isn't enough and you ask again, like getting the posts and then asking for each one's comments, often in another round trip.

Why is GraphQL hard to cache over HTTP?

Every request goes to one URL, mostly as a POST, while HTTP caches and CDNs key answers on a GET's URL. GraphQL allows queries over GET, and persisted queries send a short id instead of the query text; clients often keep their own cache by object id.

Can a browser call gRPC?

Not directly: no browser API gives enough control over HTTP/2 requests. It takes gRPC-Web and a proxy (Envoy, say) translating between gRPC-Web and gRPC. So gRPC is common between services, with browsers talking REST or GraphQL.

Why does gRPC send fewer bytes?

Protobuf sends each field as a number and a binary value, not its name every time as JSON does; HTTP/2 compresses the headers with HPACK, and every call shares one connection. In this lesson's code, the same screen is about 1,700 bytes against REST's 3,402.

What's GraphQL's N+1 problem?

A plain resolver fetches each item's data on its own: the posts once, then comments once per post. The client sent one request, but the database gets asked many times. Batching fixes it: collect the keys asked for in one tick and look them up at once, as DataLoader does.

Which should I pick?

For public APIs and data worth caching, REST: easy to read and cached by URL. For many kinds of client wanting different data, GraphQL. For services talking to each other that want shared types, small messages and deadlines, gRPC. Real systems often use more than one.

Next lesson

Reverse proxy, API gateway and BFFLevel: Intermediate

An endpoint made for one screen is a BFF; next, it goes behind the front door with a reverse proxy and a gateway.