System Design · 04. Communication · 10 min · Beginner
REST, RPC & GraphQL
Three ways for a client and a server to talk, and what each one costs.
In short
The same screen cost 2 trips and 12 KB with fixed REST endpoints, and 1 trip and about 1 KB with a tailored RPC call or a GraphQL query.
REST names resources and uses status codes. RPC and gRPC call actions with compact messages. GraphQL lets the client pick fields, but needs care with N+1 queries.
Key ideas
- REST, RPC and GraphQL are three styles for shaping that request and response. All three usually travel over HTTP. (step 1)
- Pick by who calls you. Strangers and browsers: REST. Your own services: gRPC. Many different screens: GraphQL. (step 9)
Good to know
- REST is easy to guess, easy to test with a browser or curl, and easy to cache. That is why most public APIs use it. (step 2)
- gRPC is a good fit between your own services: fast, typed, and streams. Browsers cannot call it directly without a helper. (step 6)
- GraphQL suits many different clients (phone, web, watch) that each need a different slice of the same data. (step 7)
Watch out
- Do not return 200 with an error hidden in the body. Monitoring and caches look at the status code. (step 3)
- Fixed endpoints return a fixed shape. Every screen that wants a different shape either wastes data or makes extra calls. (step 4)
- The price: one method per screen. When the screen changes, the server method changes too. (step 5)
- The client sees one fast request, but the database pays for the hidden loop. Watch query counts, and limit how deep a query may go. (step 8)
Key numbers
- Round trips
- 1
- Data received
- 1 KB
- Screen time
- 80 ms
Terms
- Round trip
- One request and its response; on a mobile network each one costs tens of milliseconds.
- REST
- An API style where each thing is a resource with a URL and HTTP methods say what to do with it.
- HTTP status code
- A number at the start of every response: 2xx success, 4xx client mistake, 5xx server failure.
- Over-fetching
- Receiving more data than the screen needs because the endpoint has a fixed shape.
- Under-fetching
- Needing extra calls because one endpoint did not return everything the screen needs.
- RPC
- Calling a named action on a server as if it were a local function.
- gRPC
- An RPC system that uses typed .proto files, binary Protocol Buffers and HTTP/2, with streaming.
- GraphQL
- A query language where the client names the exact fields it wants from one endpoint.
- Resolver
- The small function that fills in one GraphQL field.
- N+1 problem
- One query for a list plus one more per item, which a batched lookup (DataLoader) avoids.