Bitpath

Lesson 2 · Unit 04

What GraphQL costs

N+1 resolvers, caching without URLs, errors inside a 200, and when REST or RPC fits better

13 exercisesabout 3 min

What you practise

  • A resolver per field and the N+1 it causes, caching without URLs, errors inside a 200, when REST or RPC is the better fit

Try a question from this lesson

Pick one

A public product catalogue is the same for every visitor and changes about hourly. The team wants a CDN to answer most requests. Which design gets that with least work?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

One resolver per field

A GraphQL server fills in each field with a small function, a resolver. The resolver for customer gets one order and returns its customer.

That is simple to write and it composes, but the function runs once per order and knows nothing of the other 49. The result is the N+1 problem: 1 query for the list, N more for its rows.

{
  orders(first: 50) {    1 query
    total
    customer { name }    + 50 queries
  }
}

Concept

Caching without URLs

HTTP caches, in browsers and in CDNs, store replies by method and URL. A REST resource has its own URL, so a GET for it can be cached by machinery that already exists everywhere.

GraphQL sends every query to one URL, usually as a POST with the query in the body. Shared caches see nothing to key on. GraphQL clients cache inside the app instead, object by object, using type and id.

GET /products/9     key: the URL

POST /graphql       same URL for
  { product(id: "9") { name } }
POST /graphql       every query
  { user(id: "7") { email } }

Concept

RPC: call a function over there

Remote procedure call is the oldest shape: a named function, typed arguments, a typed result. Frameworks such as gRPC keep the calls in a schema file and generate client and server code from it, with compact binary messages.

It suits calls between services you run yourself, where both ends are built from the same schema. It is a poor fit for browsers and for strangers.

service Orders {
  rpc GetOrder (OrderRequest)
      returns (Order);
}

9 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 3× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy