Skip to the page

Designing HTTP APIs · mid

GraphQL basics and the N+1 problem

GraphQL exposes one endpoint and a typed schema, the client asks for exactly the fields it needs, and resolvers fetch each field, which makes naive resolvers run one database query per item (N+1) unless you batch them with a DataLoader.

The notes

What you must know

  • Schema (types, fields), queries (read), mutations (write), subscriptions (real-time). One endpoint, usually POST /graphql.
  • Pros: no over- or under-fetching, one round trip for nested data, strong types for clients and codegen. Cons: HTTP caching is harder, complex queries can be expensive, errors often come back as 200 with an errors array.
  • Resolvers run per field. Fetching author for each of 50 posts = 1 + 50 queries (N+1).
  • DataLoader: collects all load(id) calls made in the same tick, calls a batch function once with all ids (WHERE id IN (...)), and caches per request. Create one loader per request so users never share cached data.
  • Protect the server: query depth and complexity limits, persisted queries (only allow known queries), timeouts, and authorization in resolvers.
  • Choose GraphQL for many clients with different data needs; REST for simple resources, public APIs and heavy HTTP caching. A BFF can be REST or GraphQL.

The red pen

Common traps: mistake → fix

  • Mistake: GraphQL is always faster than REST

    Fix: it saves round trips, but naive resolvers and expensive queries can be slower.

  • Mistake: A shared DataLoader for the whole app is fine

    Fix: its cache would leak data between users; create one per request.

  • Mistake: GraphQL removes the need for authorization checks

    Fix: every resolver that returns sensitive data must check access.

Easy to hard

Questions interviewers ask, easy to hard

  1. When would you choose GraphQL over REST?
  2. What is the N+1 problem in GraphQL and how does DataLoader fix it?
  3. How do you cache GraphQL responses?
  4. How do you protect a GraphQL server from very expensive queries?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview