AlgoViz

REST, GraphQL and gRPC

medium 26 min

Three ways to offer an API.

Video lesson · Chapter 1 of 6

REST and separate resources

0:00 / 4:05

REST vs GraphQL vs gRPC

1:19Reel

Theory

Read or listen first. About 2 min.

What it is

REST is an architectural style. The server offers resources at addresses, the client uses HTTP methods on them, and the server decides what each answer contains.

GraphQL is a query language with a typed schema. The client sends one query that names the fields it wants, and the answer has exactly that shape.

gRPC is a framework for remote procedure calls. You describe methods and messages in a file, a tool writes the client and server code, and the messages travel as binary Protocol Buffers over HTTP/2.

Why it exists

The three answer different problems. REST answers: how can strangers use my system with tools they already have? GraphQL answers: how can many different screens get different data without a new endpoint each time? gRPC answers: how can my own services call each other quickly, with types checked on both sides?

Choosing badly costs round trips, unneeded data or difficult integrations. Choosing well starts with the caller, not with fashion.

A short history

  1. 2000

    Roy Fielding's thesis describes REST as the architectural style behind the web.

  2. July 2008

    Google releases Protocol Buffers, its binary message format, as open source.

  3. 2012

    Facebook creates GraphQL while rebuilding its native mobile apps, whose screens needed nested data in few requests.

  4. February 2015

    Google announces gRPC as an open source framework on HTTP/2, following its internal system Stubby.

  5. 2015

    Facebook publishes GraphQL as an open specification.

  6. August 2016

    gRPC 1.0 is declared ready for production. It joins the Cloud Native Computing Foundation in March 2017.

  7. 2019

    The GraphQL Foundation is formed as a neutral home for the project.

Words to know

Over-fetching
Receiving more fields than needed.
Under-fetching
Receiving too little, so more requests follow.
Schema
The written list of types, fields and operations.
Resolver
The function that produces one field in a GraphQL server.
N+1 problem
One query for a list, then one more for each item.
Protocol Buffers
A binary message format with numbered fields.
Stub
Generated client code that looks like a local function.
Multiplexing
Many requests sharing one connection at the same time.

How it works

Step through the idea, or press Play.

Step 1 of 3

Who calls it?. Strangers, our own screens, or our own services

Understand it

Start here

The stationery shop

Imagine you need three things from a stationery shop. There are three ways to be served.

One list, three ways to shop
1 pencil1 ruler1 eraserSTATIONERYThree things

Boxes for everyone, a list for those who know what they want, a tube for the staff.

  • REST

    The web's own style. Simple, cacheable, stateless. GET /users/123/orders

  • GraphQL

    Ask for exactly what you need. One endpoint, typed schema. { user(id: 123) { name } }

  • gRPC

    Typed calls in binary over HTTP/2, with streams and generated code. users.GetUser(123)

REST

REST: resources with addresses

Standard HTTP methods act on resources named by URLs. How that works is told in API design introduction.

Text
GET /api/v1/users/123/orders HTTP/1.1Host: api.shopeasy.exampleAuthorization: Bearer fake-tokenAccept: application/jsonHTTP/1.1 200 OKContent-Type: application/json{ "orders": [ { "id": "ORD-001", "total": 99.99 },              { "id": "ORD-002", "total": 149.99 } ] }

Over-fetching: the screen only shows the name

Field in GET /users/123Needed
id: 123No
name: Asha RaoYes
email: asha@example.comNo
phone, address, preferencesNo
created_at, last_loginNo
A REST API can offer ?fields=name. Then the server must build and document that.

Under-fetching: one screen, four requests

Four requests, but two waves: the product ids are known only after the orders arrive. One after another it would be four round trips.

REST strengths

  • Simple and intuitive
  • HTTP caching works as it is
  • Stateless, so easy to scale out
  • Tools everywhere: curl, Postman, OpenAPI
  • Works in every browser
  • Most developers know it

REST weak spots

  • Over-fetching
  • Under-fetching, several requests
  • No built-in push
  • Versioning needs a plan
  • No single standard for filters and paging
  • Types and docs are extra work (OpenAPI helps)

GraphQL

GraphQL: ask for what you need

Text
POST /graphqlquery { user(id: 123) {    name    orders(limit: 3) { id total items { product { name } } }} }200 OK{ "data": { "user": {    "name": "Asha Rao",    "orders": [      { "id": "ORD-001", "total": 99.99,        "items": [ { "product": { "name": "Headphones" } } ] } ] } } }
The answer has the shape of the question. The four REST requests above became one.

Three operations

OperationPurposeExample
QueryRead, like GETquery { products { name price } }
MutationWrite, like POST, PUT or DELETEmutation { createOrder(input: {...}) { id } }
SubscriptionUpdates pushed as they happensubscription { orderUpdated { status } }
Subscriptions need a long-lived connection: Real-time APIs.

How a server answers one query

GraphQL strengths

  • No over-fetching, fewer requests
  • One endpoint
  • Strong types in a schema
  • Self-describing (introspection)
  • Subscriptions in the language
  • Can grow without versions: add fields, deprecate old ones

GraphQL weak spots

  • More to learn
  • HTTP caching is harder
  • Resolvers need batching
  • Clients can write expensive queries
  • Needs its own tools and permissions per field
  • Too much for a simple API

The N+1 problem

1⏟user+1⏟orders+3⏟items+6⏟products=11 queries;⟶;1+1+1+1=4\underbrace{1}_{user} + \underbrace{1}_{orders} + \underbrace{3}_{items} + \underbrace{6}_{products} = 11 \text{ queries} ;\longrightarrow; 1 + 1 + 1 + 1 = 4
Three orders with two items each. A batching loader collects the ids of one level and fetches them together, so there is one database query per level.

gRPC

gRPC: call a method on another machine

Text
// user.proto: the shared contractsyntax = "proto3";service UserService {  rpc GetUser(GetUserRequest) returns (User);  rpc ListOrders(ListOrdersRequest) returns (stream Order);}message GetUserRequest   { int32 user_id = 1; }message ListOrdersRequest { int32 user_id = 1; }message User  { int32 id = 1; string name = 2; string email = 3; }message Order { string id = 1; int64 total_cents = 2; }# Python client, using generated code (no TLS: local test only)channel = grpc.insecure_channel("localhost:50051")client = user_pb2_grpc.UserServiceStub(channel)user = client.GetUser(user_pb2.GetUserRequest(user_id=123), timeout=0.5)print(user.name)          # Asha Rao
It looks like a local call. It is still a network call: give it a deadline and expect failure. See RPC.

Four kinds of call

KindMessagesGood for
Unaryone request, one responseOrdinary calls
Server streamingone request, many responsesA live feed, a long list
Client streamingmany requests, one responseUploading in parts
Bidirectionalboth sides, any timeChat, games

Unary, then server streaming, on one connection

The client can use the first order before the last one has been read from the database.

Why it is efficient

  • Binary messages

    Field numbers instead of names, numbers as bytes. Smaller, and quick to read.

  • HTTP/2

    Many calls share one connection at the same time.

  • Generated code

    Client and server are written by a tool from the same file. Parsing still happens, but is quick and typed.

One user, counted in bytes

JSON: 55 BProtobuf: 1+1⏟id+2+8⏟name+2+16⏟email=30 B\text{JSON: } 55\text{ B} \qquad \text{Protobuf: } \underbrace{1{+}1}_{id} + \underbrace{2{+}8}_{name} + \underbrace{2{+}16}_{email} = 30\text{ B}
The user is id 123, name Asha Rao, email asha@example.com. About 45% smaller here, not ten times. Text stays text; numbers and long field names shrink most, and compression narrows the gap.

gRPC strengths

  • Compact and fast
  • Multiplexing over HTTP/2
  • Streams in both directions
  • Generated clients and servers
  • Types enforced by the .proto file
  • Many languages

gRPC weak spots

  • Browsers need gRPC-Web and a translating proxy or server
  • Binary, not readable by eye
  • More to learn
  • Fewer everyday tools than REST
  • Harder to debug by hand
  • Long connections need a balancer that understands HTTP/2

Compare

Side by side

Features

RESTGraphQLgRPC
TransportAny HTTP versionUsually HTTPHTTP/2
FormatUsually JSONJSONProtobuf (binary)
EndpointsMany URLsOneMany methods
TypesOptional (OpenAPI)Schema.proto file
CachingHTTP, built inIn the client, or GET with saved queriesYour own
Real timePolling, SSE, WebSocket beside itSubscriptionsStreams
BrowserNativeNative (it is HTTP)gRPC-Web and a translator
To learnLittleSomeMore
Best forPublic APIsScreens with mixed dataService to service

If you need

NeedRESTGraphQLgRPC
Public APIvery goodpossiblerare
Complex screenspossiblevery goodweak
Microservicespossiblepossiblevery good
HTTP cachingvery goodweakweak
Real timeweak alonegoodvery good
Browser without extrasvery goodgoodweak

Which one?

Numbers

Count round trips, not slogans

The profile screen needs the user, three orders and the product names. Assume a 100 ms round trip on mobile, an open connection, and 20 ms of server work per wave.

WayWavesTime
REST, one after another44 x 120 = 480 ms
REST, parallel where possible22 x 120 = 240 ms
REST, one endpoint for this screen1about 120 ms
GraphQL, one query1about 120 ms
gRPC, one method for this screen1about 120 ms
A model with stated assumptions, not a measurement. What saves time is asking once. The format matters most inside the data centre, where a round trip is under a millisecond and calls are many.

Time for a screen

T=waves×(RTT+Tserver)4×120=480,2×120=240,1×120=120 msT = \text{waves} \times (RTT + T_{\text{server}}) \qquad 4 \times 120 = 480, \quad 2 \times 120 = 240, \quad 1 \times 120 = 120\text{ ms}

Together

Use more than one

Three styles in one system

Partners call a REST API with JSON. Our apps send one query to a GraphQL server. Both call the products service and the orders service over gRPC, and each service has its own database.
Each boundary gets the style its callers need. The services are written once.
  • REST at the edge for partners, with keys and caching.
  • GraphQL for our apps, as a thin layer that combines services.
  • gRPC inside, with deadlines and generated clients.
  • A gateway can translate JSON to gRPC, so one service serves both: API gateway.

Change

How each one evolves

AddRemoveDanger
RESTNew optional fields and endpointsNew version, or a long deprecationClients that reject unknown fields
GraphQLNew fields and types@deprecated, watch usage, then removeForgetting that unknown clients remain
gRPCNew fields with new numbersReserve the old number and nameReusing a field number: old clients misread it
The full story: API versioning.

Operate

What breaks in production

  1. 1

    REST: chatty clients

    A list view calls the item endpoint for every row. Fix: include the needed fields, or one endpoint per screen.

  2. 2

    GraphQL: one slow field

    One field makes a whole query slow. Fix: trace per resolver, timeouts, batching.

  3. 3

    gRPC: uneven load

    A long connection sticks to one server, so a new server stays idle. Fix: balance per request, or limit connection age.

  4. 4

    All: no deadline

    Calls wait forever and pile up. Fix: timeouts.

Summary

The whole topic in one minute.

REST: addresses, methods and HTTP caching, understood by everyone. GraphQL: one query with exactly the fields you want, and a server that must protect itself from expensive queries. gRPC: typed methods, small binary messages and streams, best between services you control.

Compare them by the caller, the shape of the data, caching, and what the team can operate. Count round trips instead of quoting speed claims. A system may use REST at the public edge, GraphQL for its own apps and gRPC inside.

  • REST for public APIs: simple, HTTP caching, known by everyone.
  • GraphQL for screens with mixed data: exactly the fields, one request.
  • gRPC between services: typed, compact, streams in both directions.
  • REST can over-fetch and under-fetch. GraphQL moves the work to the server.
  • Protobuf is binary: smaller, but not readable by eye.
  • Use several styles in one system, each at its boundary.

Sources