AlgoViz

GraphQL

medium 27 min

GraphQL is a query language for APIs with a typed schema.

See it run

How a selection becomes an answer, and how the server keeps control of the work.

Operations

Answer one query

A phone asks for a name, three post titles and a points total.

Step 1 of 5

One request

Our systemPhone appGatewaytoken, limitGraphQL serverresolversLoadersone per requestPostgreSQLPoints service

One request

POST /graphql with the query and its variables. The gateway checks the token.

Step 1: One request

request = {"query": TEXT, "variables": {"id": "7"}}document = parse(request["query"])errors = validate(schema, document)if errors or cost(document) > LIMIT:    return refuse(errors)data, errors = execute(document, variables, context)return {"data": data, "errors": errors}
Calls
1 request
Guards against
Round trips
Fixed endpoints
3 requests

GraphQL does not store data. It is a typed layer in front of what you have.

In the real world

The same graphql doing real jobs. Pick one and step through it.

The points service fails while the phone asks for a whole screen.

Step 1 of 4

The service stops

Our systemPhone appGatewaytoken, limitGraphQL serverresolversLoadersone per requestPostgreSQLPoints service

One field will fail

The points service does not answer. User and posts are fine.

Step 1: The service stops

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A query in every resolver

    critical

    A page of 20 becomes 21 queries, and each nested list multiplies it.

    Wrong
    author = lambda post: db.user(post.author_id)
    Right
    author = lambda post: loaders.user.load(post.author_id)
  • One loader for the whole server

    critical

    Its cache keeps old values, and gives one user what was loaded for another.

    Wrong
    loaders = create_loaders()   # at start
    Right
    def context(request):    return {"loaders": create_loaders()}
  • Rate limit by requests only

    major

    One request can ask for a million nodes.

    Wrong
    allow(client, 1)
    Right
    allow(client, cost(query))
  • Access checks at the entrance only

    critical

    A private object can be reached through a comment, a list or a search.

    Wrong
    if path == "me": check(user)
    Right
    def load_post(id, viewer):    post = db.post(id)    return post if may_see(viewer, post) else None

Interview tips

  • How to explain it

    • A typed schema.
    • The client selects fields.
    • The answer has the same shape.
  • Say in an interview

    • Loader per request.
    • Pages, depth, cost.
    • Authorize where you load.
  • Reach for it when

    • Screens differ a lot.
    • Round trips are slow.
    • Several services feed one app.
  • Look elsewhere when

    • Simple CRUD.
    • Public cached reads.
    • Files, or calls between services.