GraphQL: Schema, Resolvers, N+1, When It Wins
"GraphQL is a query language designed to build client applications by providing an intuitive and flexible syntax and system for describing their data requirements and interactions." — GraphQL specification, October 2021 edition, Overview
Summary: GraphQL is an API style in which the server publishes a typed schema and the client sends a query that names exactly the fields it wants; the server runs one resolver function per requested field and returns JSON that mirrors the query. It trades the simplicity and cacheability of many URLs for one flexible endpoint, and it moves the hard problems (N+1 queries, query cost, authorization per field) from the client into your resolvers. Focus: SDL and the type system (scalars, enums, interfaces, unions, input types, non-null), queries, mutations and subscriptions, resolvers and the execution algorithm, introspection, the N+1 problem and DataLoader batching, Relay cursor connections, partial data and the errors array, persisted queries and APQ, depth and complexity limits, authorization, deprecation, federation and stitching, graphql-ws, file uploads, and the decision against REST and gRPC, with Go (gqlgen) and Laravel (Lighthouse) code. Learning goal: Design a schema that can evolve without versions, write resolvers that cost a constant number of database queries per level of the query tree, put limits in front of the executor so one query cannot take the service down, authorize at the object and not only at the endpoint, and decide with numbers when GraphQL is worth running instead of REST or gRPC.
This chapter sits in the Networking & Protocols group after REST API Design and before gRPC & Protocol Buffers, which closes the REST vs GraphQL vs gRPC comparison. Adjacent pages: API Versioning & Evolution for the general rules, Caching and CDN for what GraphQL gives up, Real-Time Communication for WebSocket scaling, API Idempotency for mutation retries, Authorization for the policy models, and API Gateway, BFF & Service Mesh for where a GraphQL server sits at the edge. Database mechanics behind the N+1 fix are in ORM Pitfalls and keyset paging is in Pagination.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| What problem GraphQL solves and what it costs | Why it exists |
| Facebook 2012, the spec, the Foundation | Where it comes from |
| SDL, types, scalars, enums, interfaces, unions, input types | Schema and SDL, Type kinds |
!, [T!]!, null propagation | Nullability |
| Query, mutation, subscription, variables, fragments | Operations |
| What happens between the HTTP body and the JSON answer | Resolvers and execution |
__schema, __type, tooling | Introspection |
| One query becomes 101 SQL statements | N+1 and DataLoader |
first, after, edges, pageInfo | Relay cursor connections |
data plus errors, extensions, userErrors | Errors and partial data |
| GET, persisted queries, APQ, normalised caches | Caching |
| Depth, complexity, cost analysis, rate limiting | Security limits |
| Authorization in resolvers or directives | Authorization |
@deprecated, additive evolution | Evolution without versions |
| Apollo Federation, supergraph, stitching, Mesh | Federation and stitching |
| graphql-ws, subscriptions at scale | Subscriptions |
| Multipart upload spec | File uploads |
| GraphQL as a BFF | BFF |
| HTTP details, status codes, algorithm | Mechanics |
| gqlgen and Lighthouse code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| REST, gRPC or GraphQL | Choosing |
| Monolith to federated graph | In architecture |
| Numbers you can reproduce | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary.
| Element | In plain words | Tiny example (SDL) | Main trap |
|---|---|---|---|
| Object type | A named shape with fields | type Order { id: ID! total: Int! } | Every field is a function call |
| Scalar | A leaf value: Int, Float, String, Boolean, ID, or your own | scalar DateTime | Custom scalars need serialise and parse code on both sides |
| Enum | A closed set of names | enum OrderStatus { PLACED PAID } | Adding a value can break clients that switch on it |
| Interface | A set of fields many types promise | interface Node { id: ID! } | Clients must handle every implementing type |
| Union | One of several types, no shared fields | union SearchResult = Order | Customer | Needs ... on Type and __typename |
| Input type | An argument object | input PlaceOrderInput { customerId: ID! } | Cannot be reused as an output type |
| Non-null and list | ! forbids null, [T] is a list | lines: [OrderLine!]! | One failing non-null field nulls its parent |
| Operation | query, mutation, subscription | mutation { placeOrder(input: $in) { order { id } } } | Mutations run top-level fields one after another |
| Directive | Annotation that changes behaviour | @deprecated(reason: "..."), @skip(if: $x) | Server-specific directives lock you to a library |
What goes wrong and what fixes it.
| Problem | Symptom | Fix | Where |
|---|---|---|---|
| N+1 queries | 1 list query plus N child queries; latency grows with rows | DataLoader batching per request | N+1 |
| Unbounded list | orders returns 1 million rows | first with a hard cap, Relay connection | Pagination |
| Hostile query | Deep or wide query pins the CPU | Depth and complexity limits, timeouts, rate limit | Security |
| Leaky field | A user reads another user's data through a nested path | Authorization in the domain layer, per object | Authorization |
| Everything is HTTP 200 | Dashboards show no errors while clients fail | Count errors in metrics and logs | Errors |
| No CDN hit | All traffic is POST to one URL | Persisted queries plus GET, or cache at the edge by hash | Caching |
| Breaking change | Removing a field breaks an old app | Deprecate, measure usage, remove later | Evolution |
| One team owns the whole graph | Release bottleneck | Federation with subgraphs per team | Federation |
| Introspection leaks the schema | Attackers map every field | Disable on public endpoints, allow-list operations | Security |
| Large upload in JSON | Base64 files blow memory | Multipart request spec or a pre-signed URL | Uploads |
GraphQL, REST and gRPC side by side.
| Axis | REST | GraphQL | gRPC |
|---|---|---|---|
| Shape of the contract | Many URLs plus OpenAPI | One typed schema (SDL) | .proto files |
| Who picks the fields | Server (per endpoint) | Client (per query) | Server (per message) |
| Transport | HTTP/1.1, 2, 3 | Usually HTTP POST; GET possible; WebSocket for subscriptions | HTTP/2 only |
| Payload | JSON (usually) | JSON | Protobuf binary |
| HTTP caching | Native: URL + validators | Hard: needs GET or persisted queries | None by default |
| Over- and under-fetching | Common | Designed away | Per-method messages |
| Streaming | SSE, WebSocket | Subscriptions | Native 4 call types |
| Typical home | Public APIs, CRUD | UIs with many clients, aggregation | Service to service |
The picture shows the central cost model. Left: every resolver is independent, so ten orders cost ten customer lookups. Right: a per-request loader collects the ten keys that arrive in the same tick and asks the database once.
Why it exists
A mobile app screen needs an order, its customer name and the title of each product. With REST you either call GET /orders/42, then GET /customers/7, then GET /products/... once per line (many round trips over a slow radio), or the backend team builds GET /orders/42?expand=customer,lines.product, and then another variant for the web, one more for the watch app. The first is under-fetching, the second grows into over-fetching: each endpoint returns the union of what every client ever needed. GraphQL moves the choice of fields to the client and the work of joining to the server, behind one typed contract.
| Without GraphQL | With GraphQL |
|---|---|
| Endpoint per screen or per client type, or many round trips | One endpoint; the query names the fields |
| Payload fixed by the server (over-fetch) | Payload equals the selection set |
| Contract is prose plus OpenAPI; clients guess | Schema is the contract; introspection and codegen come for free |
Versions (/v1, /v2) to remove a field | Additive evolution plus @deprecated |
| Caching works through URLs and validators | Caching needs extra work (GET, persisted queries, client cache) |
| Cost per request is roughly known by the route | Cost depends on the query; you must measure and limit it |
| Errors map to HTTP status codes | Usually HTTP 200 with an errors array; partial results |
An everyday picture. REST is a set menu with a fixed list of dishes: the kitchen decides what is on each plate, and a vegetarian still receives the side of meat unless the restaurant prints another menu. GraphQL is the à la carte order: the guest writes exactly what they want, and the kitchen must be ready for any combination, including the order that asks for forty dishes at once. The kitchen needs a limit on the size of an order, and it must not cook each dish in a separate trip to the pantry. That is the rest of this page.
Three common misunderstandings, up front
| Belief | Reality |
|---|---|
| "GraphQL is a database query language" | It is an API query language. The resolvers behind a field may call SQL, REST, gRPC, a cache or a function |
| "GraphQL solves performance" | It removes round trips and payload bytes between client and server; it can multiply database queries (N+1) unless you batch |
| "GraphQL replaces REST everywhere" | It wins for many clients and aggregation; for public cacheable resources, webhooks and service-to-service calls REST or gRPC is simpler and cheaper |
Where it comes from
The specification's own introduction gives the dates: GraphQL is "a query language and execution engine originally created at Facebook in 2012", "the development of this open standard started in 2015", the specification "was licensed under OWFa 1.0 in 2017", and "the GraphQL Foundation was formed in 2019". OWASP's cheat sheet repeats the 2012 origin. The edition this page uses is October 2021.
| Year | Event | Source |
|---|---|---|
| 2012 | Created at Facebook for client-server applications (the spec only says "created at Facebook") | GraphQL spec introduction |
| 2015 | Development of the open standard starts; Copyright line "2015-2018, Facebook, Inc." | GraphQL spec |
| n/a | Relay's cursor connections specification defines the connection pattern (the page I read gives no date) | Relay cursor connections spec |
| 2017 | Spec licensed under OWFa 1.0 | GraphQL spec |
| 2019 | GraphQL Foundation formed; spec project moved under the Joint Development Foundation | GraphQL spec |
| 2021 | October 2021 edition (the one this page cites) | spec.graphql.org/October2021 |
Two ideas shaped everything after: the schema as the contract (strongly typed, introspectable) and the client-driven selection set. The Relay connection model, the global object identification pattern (node(id:)) and the multipart upload request are community specifications layered on top, not part of the core spec.
The concept catalogue
Schema and SDL Must-know
In plain words: The schema is the list of everything a client may ask for, written in a small language called SDL (Schema Definition Language). It names the types, their fields, the arguments of each field and the three entry points: Query, Mutation, Subscription.
Common misunderstanding: "The schema is the database schema." It is the shape of the API. Order.totalCents can be computed from lines, Order.customer can come from another service, and a column can be absent from the schema entirely.
Definition: A GraphQL schema is a set of named types plus root operation types. A field has a name, optional arguments and a return type. The type system is checked before execution: a query that asks for a field that does not exist never reaches a resolver (validation error, HTTP 422 in gqlgen).
Client Server
1 POST /graphql { order(id:"o001") { idd } }
2 parse -> ok
3 validate: Order has no field "idd"
4 <- 422 {"errors":[{"message":"Cannot query field \"idd\" on type \"Order\". Did you mean \"id\"?",
5 "extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]} (no resolver ran)Real scenarios: A typo in a mobile client is caught by codegen at build time rather than in production. A back-office tool and a public app share one schema but see different fields through authorization. The schema file is reviewed in pull requests like any API contract, and a schema registry (Apollo GraphOS, GraphQL Hive) runs a "will this break clients" check in CI.
| Approach | Meaning | Example product |
|---|---|---|
| Schema-first | You write SDL, a generator produces resolver stubs | gqlgen, Lighthouse, Apollo Server with SDL |
| Code-first | Types are built in code, SDL is generated | graphql-go/graphql, graphql-php (webonyx) code API |
Fix / how to use it: keep the SDL in version control, generate server stubs and client types from it, and run a breaking-change check in CI. The Go and Laravel schemas in this chapter are in Go and Laravel.
Type kinds: scalar, enum, interface, union, input Must-know
In plain words: Scalars are leaves (numbers, strings, dates), enums are fixed lists of names, interfaces say "these types share these fields", unions say "one of these, with nothing in common", and input types are bundles of arguments.
Common misunderstanding: "An input type is just an object type used for arguments, so I can return it." Input types and output types are separate worlds in the spec: input fields cannot have arguments or interface types, and an object type cannot be an argument.
Definition: The built-in scalars are Int (32-bit signed), Float, String, Boolean and ID (serialised as a string). Custom scalars (DateTime, Upload, Decimal) declare how to serialise to JSON and parse from JSON or literals. An interface with fields can be implemented by object types; a union has member types only.
query Search($t: String!) response
1 search(term: $t) { [
2 __typename {"__typename":"Product","title":"Keyboard"},
3 ... on Product { title } {"__typename":"Order","id":"o001"}
4 ... on Order { id } ]
5 }Real scenarios: Node interface for global lookups; SearchResult union across orders, customers and products; DateTime scalar to avoid shipping epoch integers; OrderStatus enum to stop free-text statuses; PlaceOrderInput to keep mutations to one argument and let you add fields later.
| Kind | Go (gqlgen) | PHP (Lighthouse) |
|---|---|---|
| Scalar | models: DateTime: model: graphql.Time in gqlgen.yml | scalar DateTime @scalar(class: "...\\DateTime") |
| Enum | Generated string-typed enum with String() and MarshalGQL | Native PHP enum or string mapping via @enum |
| Interface | Generated Go interface (Node with IsNode() and GetID()) | interface Node @interface(resolveType: ...) |
| Union | Marker interface (IsSearchResult()) on each member | union SearchResult @union(resolveType: ...) |
| Input | Generated struct (model.PlaceOrderInput) | Array of arguments, optional @spread |
Fix / how to use it: prefer one input object per mutation (input:), prefer enums over strings for closed sets, and treat adding an enum value as potentially breaking for clients that exhaustively switch.
Nullability and list shapes Must-know
In plain words: In GraphQL every field may be null unless you add !. [Order!]! means "a list that is never null and never contains null".
Common misunderstanding: "Non-null is a free guarantee, so mark everything !." If a non-null field fails (a resolver error, a timeout), the null cannot be represented, so it propagates upward to the nearest nullable parent; one broken field can erase a whole branch.
Definition (spec execution rule): If a non-null field resolves to null or errors, the error is added to errors and the parent field becomes null; if the parent is also non-null, propagation continues to the root, where data becomes null.
Query: { node(id:"c2") { ... on Customer { name orders { totalCount } } } } viewer = c1
1 resolve node("c2") -> Customer{c2} node: nullable
2 resolve Customer.orders -> authorization error orders: OrderConnection! (non-null)
3 null cannot be stored in a non-null field -> parent becomes null
4 {"data":{"node":null},"errors":[{"message":"not allowed to see this order","path":["node","orders"]}]}Real scenarios: A product page where recommendations are [Product!] (nullable list) degrades to an empty section when the recommendation service is down, while title: String! stays strict. A payment status field is non-null because a wrong guess is worse than a failure.
| Shape | Allows | Use when |
|---|---|---|
String | null or a string | Optional or may fail independently |
String! | string only | Always present and cheap, failure should fail the parent |
[T] | null, or list with null items | Rare; hides failures per item |
[T!] | null, or list of non-null | Whole list may be unavailable |
[T!]! | list of non-null | List is a core part of the parent |
Fix / how to use it: make fields from other services nullable, keep identifiers and core attributes non-null, and test the failure path (see TestNonNullErrorBubblesToNullableParent in the Go snippet).
Operations: query, mutation, subscription Must-know
In plain words: A query reads, a mutation writes, a subscription keeps a connection open and pushes results when something happens. Variables carry the dynamic values; fragments reuse selections.
Common misunderstanding: "A query is GET and a mutation is POST." Operation type is part of the document, not the HTTP method. Queries are often sent as POST; mutations must never be sent as GET.
Definition: An operation document has an operation type, optional name, variable definitions, directives and a selection set. Fields of a query may be executed in any order and in parallel; top-level mutation fields are executed serially, in the order written. The server executes exactly one operation per request (selected by operationName).
Client Server
1 mutation Place($in: PlaceOrderInput!) {
2 a: placeOrder(input: $in) { order { id } } run a, wait for it to finish
3 b: placeOrder(input: $in2) { order { id } } then run b
4 }
5 query Q { orders(first:10) { edges { node { id } } } } run the fields of Q in parallelReal scenarios: The checkout screen sends one mutation and asks for the updated cart in the same document, saving a round trip. Variables stop clients from string-concatenating queries (injection into the document, and cache keys that differ by value). A persisted operationName makes logs readable.
| Operation | HTTP | Execution | Idempotency |
|---|---|---|---|
query | POST or GET | Fields may run in parallel | Must be side-effect free |
mutation | POST only | Top-level fields run serially | Not guaranteed; add an idempotency key |
subscription | WebSocket (graphql-ws) or SSE | Source stream per event | Event delivery semantics are yours |
Fix / how to use it: give every operation a name, always use variables, return the changed object from the mutation, and put an idempotencyKey in the input of any mutation a client might retry (see API Idempotency).
Resolvers and the execution model Must-know
In plain words: The server walks the query like a tree. For each field it calls the resolver function for that field, passing the parent value, the arguments and a context (current user, loaders, request). Whatever the function returns becomes the parent for the fields below.
Common misunderstanding: "GraphQL executes one big query against my database." There is no database in the spec; execution is a recursive call to hundreds of small functions. That is why N+1 exists and why batching must be added.
Definition: Execution has four phases: parse, validate, coerce variables, execute. During execute the engine collects fields, calls each resolver, completes the value (scalar coercion, list iteration, object recursion) and merges errors. If a resolver is not written, a "trivial resolver" reads the same-named property of the parent.
POST /graphql { orders(first:2){ edges{ node{ id customer{ name } } } } }
1 parse + validate against schema (before any resolver)
2 Query.orders(first:2) -> OrderConnection (1 DB query)
3 for each edge: Order.id -> trivial resolver (field of the struct)
4 for each edge: Order.customer -> resolver (loader.Load(customerId)) x2
5 for each customer: Customer.name -> trivial resolver
6 merge into {"data":{"orders":{"edges":[...]}}}Real scenarios: A resolver that calls another microservice over gRPC; a resolver that reads from Redis; a computed field totalCents. Each resolver can be unit-tested alone, and each one is a place where latency hides, so tracing per resolver (OpenTelemetry spans, Apollo tracing) is standard.
| Resolver argument | Meaning | Go (gqlgen) | PHP (Lighthouse) |
|---|---|---|---|
| Parent / root | The object the field belongs to | obj *model.Order | $root |
| Arguments | The field's arguments | typed params (first *int) | $args array |
| Context | Per-request services | ctx context.Context | GraphQLContext $context |
| Info | Field name, path, selection | graphql.CollectAllFields(ctx) | ResolveInfo $resolveInfo |
Fix / how to use it: keep resolvers thin (call a service or loader), never open a connection in a resolver, and put per-request state (viewer, loaders) in the context.
Introspection Important
In plain words: A GraphQL server can answer questions about its own schema through special fields: __schema, __type, and __typename. Tools such as GraphiQL, code generators and IDE plugins use it.
Common misunderstanding: "Disabling introspection secures the API." It hides the map, not the territory: field suggestions in error messages ("Did you mean ...") and leaked client bundles can reveal the schema, and authorization is still required on every field.
Definition: Introspection is part of the spec (section 4): the schema must expose __Schema, __Type, __Field, __InputValue, __EnumValue, __Directive. OWASP's guidance: "Disable introspection queries system-wide in any production or publicly accessible environments."
Request Response (introspection disabled in gqlgen)
1 { __schema { queryType { name } } } {"errors":[{"message":"introspection disabled",
2 "path":["__schema"]}],"data":null}Real scenarios: Introspection stays on in staging for tooling and off on the public edge; internal tools use a schema file from the repository instead of a live query; the schema registry holds the source of truth.
| Server | Switch |
|---|---|
| gqlgen | Add extension.Introspection{} to enable; omit it to disable |
| Lighthouse | security.disable_introspection (DisableIntrospection::ENABLED) in config/lighthouse.php |
| webonyx/graphql-php | DisableIntrospection validation rule |
Fix / how to use it: turn it off on public endpoints, publish the schema to partners as a file, and combine it with an operation allow-list so unknown queries are rejected anyway.
The N+1 problem and DataLoader Must-know
In plain words: Fetch a list with one query, then for each item fetch something related with another query: 1 + N queries. DataLoader waits a moment, collects all the "give me customer X" requests, and sends them as one query.
Common misunderstanding: "An ORM or a database cache fixes N+1." A per-row query is still a round trip even if cached, and with GraphQL the resolver for Order.customer does not know its siblings exist. Eager loading in the first query (SELECT ... JOIN) helps only when the parent resolver knows what the children will ask for.
Definition: The DataLoader pattern, from the graphql/dataloader README: "DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching." Loads made within one tick (or one batching window) are coalesced into one batch function call that receives an array of keys and must return values in the same order; "DataLoader is intended to be used as a per-request cache."
T (ms) Resolver Loader / database
0.0 orders resolver SELECT ... FROM orders LIMIT 10 (1 query)
0.1 orders[0].customer -> Load("c1") queue ["c1"]
0.1 orders[1].customer -> Load("c2") queue ["c1","c2"]
0.1 ... orders[9].customer -> Load("c5") queue 10 keys, 5 unique
2.0 window closes SELECT ... WHERE id = ANY(['c1'..'c5']) (1 query)
2.1 each Load returns its value done: 2 queries, not 11Real scenarios: Order.customer, OrderLine.product, Post.author, Comment.likes count. A batch size cap (WithBatchCapacity) keeps IN (...) lists sensible; a mapped loader returns "not found" per key instead of failing the whole batch.
| Aspect | Rule | Why |
|---|---|---|
| Lifetime | Create loaders per request | The cache is keyed by id; a global loader leaks one user's data and goes stale |
| Order | Return results in key order (or use a mapped loader) | The loader pairs values to keys by position |
| Window | A few milliseconds (gqlgen dataloadgen.WithWait) or one event-loop tick (Node) | Longer waits add latency to every request |
| Keys | De-duplicate | One query per unique key |
| Writes | Clear or prime the cache after a mutation | Otherwise a read after write returns the old value |
| Stack | Batching mechanism |
|---|---|
| Node.js | dataloader package, one tick |
| Go (gqlgen) | github.com/vikstrous/dataloadgen (the gqlgen docs' example), per-request via middleware |
| Laravel (Lighthouse) | @belongsTo, @hasMany batch automatically ("Lighthouse will batch the relationship queries together in a single database query"); custom BatchLoaderRegistry for non-Eloquent sources |
| Apollo Federation | entities lookups are batched by the router per subgraph |
Fix / how to use it: SQL, Go and Laravel below.
-- Naive: one statement per order row (N of these)
SELECT id, name, email FROM customers WHERE id = $1;
-- Batched: one statement for every customer id seen in the same window
SELECT id, name, email FROM customers WHERE id = ANY($1::text[]);The Go resolver is two lines; the saving is in the loader (see Go):
if r.Naive {
// One database round trip per order row: the classic N+1.
return r.Store.Customer(ctx, obj.CustomerID)
}// All Load calls made in the same ~2 ms window become ONE query.
return loaders.For(ctx).Customer.Load(ctx, obj.CustomerID)In Laravel the same effect comes from declaring the relation in the schema (customer: Customer! @belongsTo), which makes Lighthouse eager-load for the whole list; Eloquent's Model::preventLazyLoading(! $this->app->isProduction()) turns any remaining lazy load into an exception in development.
Pagination: Relay cursor connections Must-know
In plain words: Never return a bare list that can grow. Return a connection: a page of edges, each with a node and a cursor, plus pageInfo that tells the client whether another page exists and where it ended.
Common misunderstanding: "A cursor is the page number or the row id I can compute." The Relay specification says the cursor "is an opaque string"; clients must not parse it, so the server can change it (offset, keyset, encrypted) without breaking anyone. Also: Lighthouse's @paginate(type: CONNECTION) is Relay-shaped, but its docs state that it "does not support actual cursor-based pagination as of now"; the cursor decodes to a page offset.
Definition: The Relay cursor connections specification defines four features: slicing (first/last), pagination (after/before with a cursor), a cursor per edge, and pageInfo (hasNextPage, hasPreviousPage, startCursor, endCursor). edges { cursor node } allows per-edge metadata. A totalCount field is a common extension, not part of the spec.
Client Server (keyset)
1 orders(first:3) SELECT ... WHERE id > '' ORDER BY id LIMIT 4
2 <- edges o001,o002,o003 hasNextPage:true (fetched limit+1 to learn hasNextPage)
3 endCursor = base64("o:o003")
4 orders(first:3, after:<endCursor>) SELECT ... WHERE id > 'o003' ORDER BY id LIMIT 4
5 <- edges o004,o005,o006 hasNextPage:trueReal scenarios: Infinite scroll in a feed; admin tables; the "load more" button; a mobile client that must resume after the app was killed (a cursor survives, a page number does not when rows are inserted).
| Strategy | Stable under inserts | Cost at depth | Random access | Product |
|---|---|---|---|---|
Offset (page) | No (rows shift) | Grows with offset | Yes | Lighthouse PAGINATOR/SIMPLE |
| Relay connection over offset | No | Grows | No | Lighthouse CONNECTION |
| Keyset cursor | Yes | Constant (index seek) | No | The gqlgen snippet in this chapter; see Pagination |
Fix / how to use it: cap first on the server (the snippet clamps to 50), fetch limit + 1 rows to compute hasNextPage without a count, and make totalCount optional because COUNT(*) is expensive.
Errors: partial data, the errors array, extensions Must-know
In plain words: A GraphQL response can carry both data and errors. If one field fails, the others still come back and the failed one is null. The status code is usually 200 even when the client has an error to handle.
Common misunderstanding: "HTTP 200 means success." In GraphQL over HTTP, 200 means "the server executed the request"; success lives in the body. Monitoring that only counts 5xx will miss every resolver failure.
Definition: The spec says: "If an error was raised during the execution that prevented a valid response, the data entry in the response should be null", "if the data entry in the response is not present, the errors entry in the response must not be empty", and if data is present the errors entry may contain field errors. Each error has message, optional locations, path and extensions. extensions is the place for machine-readable codes (FORBIDDEN, BAD_USER_INPUT, DEPTH_LIMIT_EXCEEDED).
POST { mine: order(id:"o001"){id} theirs: order(id:"o002"){id} } viewer = c1
200 {"data":{"mine":{"id":"o001"},"theirs":null},
"errors":[{"message":"not allowed to see this order","path":["theirs"],
"extensions":{"code":"FORBIDDEN"}}]}Real scenarios: A dashboard with twelve widgets renders eleven when one backend fails. A validation problem in a form ("quantity must be at least 1") belongs in the payload as data (userErrors), where the client can show it next to the input, while an unexpected exception belongs in errors. That is the "errors as data" convention used by large public schemas.
| Kind | Where | HTTP status (gqlgen) | Example |
|---|---|---|---|
| Syntax or validation error | errors, data null or absent | 422 | unknown field |
| Operation rejected by limit | errors, extensions code | 200 in the tested version | depth, complexity |
| Resolver error | errors plus partial data | 200 | FORBIDDEN, upstream timeout |
| Business validation | data.placeOrder.userErrors | 200 | quantity 0 |
| Transport failure | none (HTTP error) | 4xx/5xx | gateway down |
Fix / how to use it: return domain failures as typed payload fields, reserve errors for the unexpected, add a stable extensions.code, never return stack traces (OWASP: "Don't Return Excessive Errors"), and alert on the rate of responses with a non-empty errors. The Go mutation shows both channels; the Laravel exception implements ClientAware and ProvidesExtensions.
Caching: GET, persisted queries, APQ, normalised client caches Important
In plain words: REST uses the URL as a cache key. GraphQL has one URL and a body, so you must create a cache key yourself: a hash of the query (persisted query), a GET request, or a client-side cache keyed by object id.
Common misunderstanding: "GraphQL cannot be cached." It can: CDNs cache GET requests keyed by a persisted-query hash plus variables; clients such as Apollo Client and Relay keep a normalised cache; servers cache resolver results (Lighthouse @cache). What you lose is automatic, free, URL-level caching.
Definition: graphql.org says: "In GraphQL, there’s no URL-like primitive that provides this globally unique identifier for a given object", so expose a globally unique id (and often the Node interface with node(id:)) so clients can build a normalised cache, flattening results into Type:id entries. A persisted query is "a query string that's cached on the server side, along with its unique identifier (always its SHA-256 hash)" (Apollo docs); Automatic Persisted Queries (APQ) register the hash on first use.
Client Server
1 GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"ab12.."}}
2 <- {"errors":[{"message":"PersistedQueryNotFound","extensions":{"code":"PERSISTED_QUERY_NOT_FOUND"}}]}
3 POST /graphql {"query":"{ search(...) {...} }","extensions":{"persistedQuery":{...,"sha256Hash":"ab12.."}}}
4 <- 200 {"data":...} server stores hash -> query text
5 GET /graphql?extensions={...ab12..}&variables=... CDN may now cache by URL
6 <- 200 {"data":...} small request, cacheable GETReal scenarios: A mobile app on a slow network sends a 64-byte hash instead of a 2 KB query. A public read-only catalogue puts a CDN in front with Cache-Control: public, max-age=60 on GET responses with no errors. A feed screen re-renders instantly from the normalised cache after a mutation returns { id, status } for an order the cache already holds.
| Layer | Mechanism | Key | Products |
|---|---|---|---|
| Browser/CDN | HTTP GET + persisted query hash | URL | Cloudflare, Fastly, AWS CloudFront (cache on GET), Apollo Router |
| Server | Resolver or response cache | Field + args + user scope | Redis, Lighthouse @cache, Apollo cache control |
| Client | Normalised store | __typename:id | Apollo Client, Relay, urql (graphcache) |
| Loader | Per-request memoisation | Loader key | DataLoader / dataloadgen |
| Persisted-query style | Who registers | Safety |
|---|---|---|
| APQ | Any client, at runtime | Saves bytes; does not stop arbitrary queries |
| Safelist / trusted documents | Build pipeline | Server rejects anything not in the list; also a security control |
Fix / how to use it: expose stable ids, send queries by hash with GET for public reads, mark responses with errors as no-store, and use APQ for bandwidth but a build-time safelist for security. The gqlgen snippet registers extension.AutomaticPersistedQuery with an LRU, and its test walks the three-step handshake.
Security limits: depth, complexity, cost analysis, rate limiting Must-know
In plain words: Because the client composes the query, a client can compose an expensive one. You need limits that run before any resolver: how deep, how costly, how long, how often.
Common misunderstanding: "Rate limiting requests per minute protects me." One request can cost a million rows. Count cost, not requests.
Definition: OWASP's GraphQL cheat sheet lists the defences: query limiting (depth and amount), timeouts, query cost analysis, rate limiting, server-side batching and caching, and disabled introspection in production. Depth limit counts nesting levels of the selection set. Complexity assigns a cost per field and multiplies list fields by the requested page size. Cost analysis estimates the cost before execution and rejects over the budget. Rate limiting by cost subtracts that cost from a token bucket per client.
{ orders(first:50) { edges { node { customer { orders(first:50) { edges { node { id } } } } } } } }
1 depth = orders(1) edges(2) node(3) customer(4) orders(5) edges(6) node(7) id(8) -> 8
2 cost = 50 x (edges + node + customer + 50 x (edges + node + id)) = 7650
3 limit MaxComplexity=200 -> rejected before any resolver:
4 {"errors":[{"message":"operation has complexity 7650, which exceeds the limit of 200",
5 "extensions":{"code":"COMPLEXITY_LIMIT_EXCEEDED"}}]}Real scenarios: A scraper requests first: 100000; a competitor nests friends { friends { friends ... } }; an alias flood (a1: expensive a2: expensive ...) multiplies one field a thousand times; a batched request array sends 1000 login mutations in one HTTP call to dodge per-request rate limits (OWASP "Batching Attacks").
| Defence | gqlgen | Lighthouse |
|---|---|---|
| Depth | Custom OperationContextMutator (the snippet's limits.MaxDepth) | security.max_query_depth |
| Complexity | extension.FixedComplexityLimit(n) + ComplexityRoot functions | security.max_query_complexity, @complexity, @paginate(complexityResolver:) |
| Page-size cap | clamp first in the resolver | pagination.max_count or maxCount: |
| Timeout | context.WithTimeout per request | PHP max_execution_time, HTTP middleware |
| Alias and batch limits | custom (count aliases; disable array batching) | custom validation rule |
| Introspection | omit extension.Introspection{} | security.disable_introspection |
Fix / how to use it: turn on all of them: depth around 8–12, a complexity budget calibrated from real queries, a hard first cap, a per-request timeout, and rate limiting by cost per API key. Lighthouse's shipped config has max_query_complexity and max_query_depth set to DISABLED by default; you must enable them. See Rate limiter algorithms for the token bucket.
Authorization: in resolvers or in the schema Must-know
In plain words: Authentication says who you are; authorization says what you may see. With GraphQL the same object can be reached by many paths (order, customer.orders, node, search), so a check at the front door is not enough.
Common misunderstanding: "I protect the /graphql endpoint with a JWT, so authorization is done." That is authentication. Without per-field or per-object checks any signed-in user can ask for any id.
Definition: graphql.org: "Delegate authorization logic to the business logic layer"; GraphQL execution should begin after authentication middleware confirms the user's identity. There are two homes for the rule: in the resolver or the domain service it calls (portable, testable, one place per object) and in the schema through directives (@auth, Lighthouse @guard and the @can* family, @canResolved), which is declarative but ties the rule to a library.
Request: { order(id:"o002") { id customer { email } } } viewer = c1 (o002 belongs to c2)
1 Query.order resolver loads o002
2 authorizeCustomer(viewer c1, order.customerID c2) -> FORBIDDEN
3 data.order = null; errors[0].extensions.code = FORBIDDEN
4 Order.customer never runs (parent is null)Real scenarios: An admin sees Customer.email, a user sees only their own; Query.orders (all orders) is admin-only; node(id:) must apply the same rule as order(id:); search must filter by viewer; a mutation checks that the customerId belongs to the caller.
| Place | Strength | Weakness |
|---|---|---|
| Gateway or edge (JWT validation, coarse scopes) | Rejects anonymous traffic early | Knows nothing about objects |
Resolver (Go authorizeCustomer) | Per object, full context | Easy to forget on a new path |
| Domain service the resolver calls | One rule for REST, GraphQL, jobs | Needs discipline |
Schema directive (@guard, @canResolved, @canModel) | Visible in SDL, hard to forget | Library-specific; runs after the field is resolved in @canResolved |
| Database row-level security | Cannot be bypassed by a new resolver | Needs the viewer passed to the connection |
Fix / how to use it: put the check in the service layer, make new entry points inherit it (central authorizeCustomer), add one test per object type that asks as another user, and use Laravel policies through @canResolved(ability: "view"). See Authorization: RBAC, ABAC & Zero Trust.
Evolution without versions: @deprecated Important
In plain words: Do not ship /v2. Add new fields, mark the old ones deprecated, watch who still uses them, and remove them when the count reaches zero.
Common misunderstanding: "A deprecated field is a removed field." Deprecation is only a hint; the field keeps working. It also is not enough for mobile apps that cannot be force-updated: you need usage data before you remove anything.
Definition: The spec defines @deprecated(reason: String) on fields, arguments, input fields and enum values. Introspection exposes isDeprecated and deprecationReason, and tooling strikes through deprecated fields. Adding a field, an optional argument or a type is non-breaking; removing or renaming a field, making an argument required, changing a return type or making a nullable field non-null are breaking.
Day 0 price: Float! priceCents: Int! added; price marked @deprecated(reason: "Use priceCents; floats cannot represent money.")
Day 30 schema registry shows price still used by app 4.2 (11% of traffic)
Day 90 app 4.2 below 0.5% -> announce date
Day 120 remove price; registry check passes because no operation uses itReal scenarios: Replacing a float price with integer cents; splitting name into firstName and lastName; renaming an enum value; retiring a field that leaked data.
| Change | Breaking? | Technique |
|---|---|---|
| Add field, type, optional argument | No | Just ship |
| Add enum value | Maybe (clients with exhaustive switch) | Document an "unknown" fallback in clients |
| Make a nullable field non-null | Yes for inputs, no for outputs | Prefer additive new field |
| Remove or rename a field | Yes | @deprecated, monitor, then remove |
| Change a field's type | Yes | New field name |
Fix / how to use it: run schema checks in CI (a schema registry such as Apollo GraphOS or GraphQL Hive), log operation names and fields per client version, and read API Versioning & Evolution for the general policy. The Go and Laravel schemas both carry a deprecated price.
Federation and schema stitching Important
In plain words: When many teams own parts of the graph, one server becomes a bottleneck. Federation lets each team run its own GraphQL service (subgraph) for its types, and a router presents them as one graph (supergraph).
Common misunderstanding: "Federation is just a gateway that proxies requests." The router builds a query plan across subgraphs, resolves entities by key, and merges the results; and the supergraph schema must compose without conflicts. It also adds a hop and a new place to debug.
Definition: Apollo's docs define the terms: "When combining multiple GraphQL APIs, the single, federated graph is called a supergraph. In a supergraph, the constituent APIs are called subgraphs." A subgraph declares an entity with @key (type Product @key(fields: "id")) and others extend it; the router sends keys to the owning subgraph's _entities field. Schema composition (Rover, a registry) produces the supergraph schema. Schema stitching (The Guild's schema stitching) merges remote schemas imperatively at the gateway with type merging; GraphQL Mesh (The Guild, tagline "Anything to GraphQL") puts a GraphQL API on top of sources that are not GraphQL.
Client { order(id:"o1") { id totalCents customer { name } } }
1 Router: plan = [Orders.order(id) -> {id, totalCents, customerId}] then [Customers._entities(keys)]
2 Router -> Orders subgraph: order(id:"o1") returns Order with customer {id:"c2"}
3 Router -> Customers subgraph: _entities([{__typename:"Customer",id:"c2"}]) (batched for N orders)
4 Router merges: {"order":{"id":"o1","totalCents":9000,"customer":{"name":"Customer c2"}}}Real scenarios: Orders, Customers and Catalog teams each deploy their subgraph; a single Product type has fields contributed by Catalog (title), Pricing (price) and Reviews (rating). A legacy REST service is wrapped into a subgraph or through Mesh.
| Approach | Where schema is merged | Strengths | Costs |
|---|---|---|---|
| Monolithic graph | Inside one codebase | Simplest; one deploy | Team coupling |
| Schema stitching | Gateway code at runtime | Flexible, imperative | Each merge rule is custom code |
| Apollo Federation (router + subgraphs) | Composition step in CI/registry | Declarative @key, ownership by team, query planner | Extra hop, composition errors, learning curve |
| GraphQL Mesh | Generated from non-GraphQL sources | Wraps REST/gRPC/DB quickly | Another layer to operate |
| BFF per client (plain GraphQL) | One server per client type | Client-shaped | Duplication |
Fix / how to use it: start with one graph; split into subgraphs along team and data ownership (see Service Boundaries), keep entity keys stable, batch _entities lookups with DataLoader, and run composition checks before deploy.
Subscriptions over WebSockets (graphql-ws) Important
In plain words: A subscription is a query that never finishes: the client opens a WebSocket, sends the operation once, and the server pushes a new result whenever the event happens.
Common misunderstanding: "Subscriptions are free real-time." Each one is a long-lived connection plus server state; you must scale connections, authenticate the socket, and decide what happens to a slow consumer or a missed event.
Definition: The graphql-ws protocol (enisdenjo/graphql-ws) uses the WebSocket sub-protocol graphql-transport-ws with JSON messages that carry a type. Messages: ConnectionInit (client), ConnectionAck (server), Ping/Pong, Subscribe (client, with an id and the operation), Next (server, one result), Error, Complete. Per the protocol, executing operations is allowed "only after the server has acknowledged the connection through the ConnectionAck message"; otherwise the socket closes with 4401: Unauthorized, and a duplicate id closes with 4409. The library README states that graphql-ws and this protocol "are not cross-compatible with the deprecated subscriptions-transport-ws", so both ends must speak the same one.
Client Server
1 open WebSocket (subprotocol graphql-transport-ws)
2 ConnectionInit {payload:{token}} -----> authenticate the token
3 <----- ConnectionAck
4 Subscribe {id:"1", payload:{query:"subscription { orderStatusChanged(orderId:\"o001\") { status } }"}}
5 <----- Next {id:"1", payload:{data:{orderStatusChanged:{status:"SHIPPED"}}}}
6 <----- Next {id:"1", ...}
7 Complete {id:"1"} -----> stop the source, free the resourcesReal scenarios: Order status tracking; chat messages; a live auction price; collaborative cursors. Where updates are infrequent, an SSE or polling query is cheaper (see Real-Time Communication).
| Product | How subscriptions are served |
|---|---|
| gqlgen | transport.Websocket{}; the resolver returns a Go channel, closed when ctx is cancelled |
| Lighthouse | @subscription classes broadcast through the Pusher or Laravel Echo driver; the response contains the channel in extensions |
Fix / how to use it: authenticate in ConnectionInit, set a keep-alive ping (the snippet uses 10 seconds), publish events from a message bus (see Event-Driven Architecture) so any instance can serve any subscriber, and drop events for slow subscribers instead of blocking the writer (the snippet's publish).
File uploads Good to know
In plain words: JSON cannot carry a file, so GraphQL clients use a multipart HTTP request with the query, a map of where the files go, and the file parts. Often it is simpler to avoid it: ask GraphQL for a pre-signed URL and upload to object storage directly.
Common misunderstanding: "GraphQL has an upload feature." It does not. File upload is a community convention: the GraphQL multipart request specification (jaydenseric). Servers must implement it, and the upload still goes through your server's memory and disk.
Definition: The multipart request has three kinds of fields in a fixed order: operations (JSON operation with null where a file belongs), map (JSON object from field name to the operation paths, for example { "0": ["variables.file"] }) and one part per file. The Upload scalar represents the file in the schema.
curl localhost:8080/graphql \
-F operations='{ "query": "mutation ($file: Upload!) { singleUpload(file: $file) { id } }", "variables": { "file": null } }' \
-F map='{ "0": ["variables.file"] }' \
-F 0=@a.txtReal scenarios: Avatar upload on a small app; document attachments in an internal tool. For large media use a createUpload mutation that returns a pre-signed URL (S3, GCS), upload directly, then a second mutation registers the object.
| Option | Server load | Resumable | Use when |
|---|---|---|---|
Multipart request spec (Upload) | High (file passes through) | No | Small files, internal tools |
| Pre-signed URL from a mutation | None for the bytes | Yes (multipart/resumable on S3/GCS) | User media, large files |
| Separate REST endpoint | Normal | Possible | When your gateway already has upload handling |
| Product | Support |
|---|---|
| gqlgen | transport.MultipartForm{} plus graphql.Upload |
| Lighthouse | scalar Upload and @upload(disk:, path:, public:) directive |
Fix / how to use it: limit size (MaxUploadSize, upload_max_filesize), check the content type and scan the file, and prefer pre-signed URLs for anything over a few megabytes.
BFF, over-fetching and under-fetching Important
In plain words: A Backend for Frontend (BFF) is a server built for one kind of client. GraphQL is a convenient way to build one, because the client chooses fields and the server aggregates several backends.
Common misunderstanding: "GraphQL replaces the API gateway." A gateway also handles TLS, authentication, rate limiting and routing, which a GraphQL server does not do for non-GraphQL traffic. The GraphQL server sits behind the gateway or is the gateway for client-facing reads.
Definition: Over-fetching returns more fields than the screen needs; under-fetching needs several round trips to build one screen. A GraphQL BFF removes both for its clients, at the cost of owning resolvers and loaders for every backend.
Mobile app GraphQL BFF Backends
1 { me { name orders(first:3) { edges { node { status lines { product { title } } } } } } }
2 Users service: GET /users/7 (1)
3 Orders service: GET /orders?user=7&limit=3 (1)
4 Catalog service: POST /products:batchGet [ids] (1, batched)
5 <- one JSON, 3 backend calls, one mobile round tripReal scenarios: A home screen that needs six backends; a TV app and a phone app with different density; a partner API where you cannot predict the fields they need.
| Pattern | Who owns the shape | Where aggregation lives |
|---|---|---|
REST with ?fields=, ?expand= | Server | Server code per endpoint |
| REST BFF per client | Client team | The BFF |
| GraphQL BFF | Client (query) | Resolvers and loaders in the BFF |
| Federation | Domain teams | Router plus subgraphs |
Fix / how to use it: one BFF per experience, not per team; keep business rules in services behind it; enforce limits and authorization in the BFF. See API Gateway, BFF & Service Mesh and Service Communication.
Mechanics
GraphQL over HTTP
| Item | Detail |
|---|---|
| Endpoint | One path, typically /graphql |
| Request body (POST) | JSON { "query": "...", "operationName": "...", "variables": {...}, "extensions": {...} }, Content-Type: application/json |
| GET | query, operationName, variables, extensions as URL parameters; only queries (never mutations); enables CDN caching |
| Response type | application/json, or application/graphql-response+json when the client sends it in Accept |
| Multipart | multipart/form-data for uploads |
| Subscriptions | WebSocket with sub-protocol graphql-transport-ws (graphql-ws), or SSE |
| Status codes (gqlgen observed in the snippet tests) | 200 for resolver errors and rejected limits, 422 for validation errors |
The execution algorithm in five steps
| Step | What happens | Error behaviour |
|---|---|---|
| 1 Parse | Text to AST | Syntax error: no data, errors only |
| 2 Validate | Fields exist, types match, fragments valid, variables used | Validation error: no data |
| 3 Pre-execution guards | Depth, complexity, APQ, introspection checks (extension hooks) | Rejected with extension code |
| 4 Coerce variables | Variable values to input types | Error before any resolver |
| 5 Execute | Collect fields, call resolvers, complete values, null propagation | Field errors in errors, partial data |
Queries are executed with parallelism allowed; "the resolution of fields other than top-level mutation fields must always be side effect-free and idempotent, the execution order must not affect the result" (spec, Normal and Serial Execution).
Complexity arithmetic
With a cost of 1 per field and a list field multiplied by its page size, orders(first: 50) { edges { node { id } } } costs 50 x 3 = 150. gqlgen's ComplexityRoot function for Query.orders receives childComplexity (3 here) and returns pageSize x childComplexity. A nested page (customer { orders(first: 50) { ... } }) multiplies again: the inner page costs 50 x 3 = 150, customer costs 151, node 152, edges 153, and the outer page 50 x 153 = 7,650, so a limit of 200 rejects it at planning time, before any SQL runs.
| Query | Depth | Complexity |
|---|---|---|
{ order(id:"o1") { id } } | 2 | 2 |
orders(first:10){edges{node{id}}} | 4 | 30 |
orders(first:50){edges{node{id}}} | 4 | 150 |
orders(first:50){edges{node{customer{orders(first:50){edges{node{id}}}}}}} | 8 | 7,650 |
Messages and codes you will actually see
| Where | Message or code | Meaning |
|---|---|---|
| gqlgen | introspection disabled | __schema or __type blocked |
| gqlgen | operation has complexity 150, which exceeds the limit of 20 (COMPLEXITY_LIMIT_EXCEEDED) | Cost over budget |
| snippet | operation has depth 5, which exceeds the limit of 3 (DEPTH_LIMIT_EXCEEDED) | Too deeply nested |
| APQ | PersistedQueryNotFound (PERSISTED_QUERY_NOT_FOUND) | Hash unknown; resend with the query text |
| validation | Cannot query field "idd" on type "Order". Did you mean "id"? (GRAPHQL_VALIDATION_FAILED) | Unknown field |
| Lighthouse | Maximum number of 50 requested items exceeded, got 5000. Fetch smaller chunks. | first over max_count |
| graphql-ws | close 4401: Unauthorized | Subscribe before ConnectionAck |
| graphql-ws | close 4409: Subscriber for <unique-operation-id> already exists | Duplicate operation id |
Go
The Go module (academy/graphql, go 1.26 because the current gqlgen v0.17.98 dependency tree requires it) is a schema-first gqlgen server. Generated code (graph/generated, graph/model/models_gen.go) is committed so go vet and go test work without running code generation; regenerate with go tool gqlgen generate. Everything else is hand-written.
Before
The first version of Order.customer queries once per row. Resolver.Naive keeps that behaviour available so the test can count the damage:
if r.Naive {
// One database round trip per order row: the classic N+1.
return r.Store.Customer(ctx, obj.CustomerID)
}After
The schema (SDL, with a union, interface, enum, input types, a custom scalar and @deprecated):
"""An instant in time, RFC 3339 string on the wire."""
scalar DateTime
interface Node {
id: ID!
}
enum OrderStatus {
PLACED
PAID
SHIPPED
CANCELLED
}
type Customer implements Node {
id: ID!
name: String!
email: String!
orders(first: Int = 10, after: String): OrderConnection!
}
type Product implements Node {
id: ID!
title: String!
priceCents: Int!
"Replaced by priceCents; kept so old clients keep working."
price: Float! @deprecated(reason: "Use priceCents; floats cannot represent money.")
}
type OrderLine {
product: Product!
quantity: Int!
}
type Order implements Node {
id: ID!
status: OrderStatus!
placedAt: DateTime!
customer: Customer!
lines: [OrderLine!]!
totalCents: Int!
}
union SearchResult = Order | Customer | Product
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type OrderEdge {
cursor: String!
node: Order!
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
input PlaceOrderInput {
customerId: ID!
lines: [OrderLineInput!]!
"Client-chosen key that makes the mutation safe to retry."
idempotencyKey: String!
}
input OrderLineInput {
productId: ID!
quantity: Int!
}
type PlaceOrderPayload {
order: Order
userErrors: [UserError!]!
}
type UserError {
field: [String!]
code: String!
message: String!
}
type Query {
node(id: ID!): Node
order(id: ID!): Order
orders(first: Int = 10, after: String): OrderConnection!
search(term: String!): [SearchResult!]!
}
type Mutation {
placeOrder(input: PlaceOrderInput!): PlaceOrderPayload!
}
type Subscription {
orderStatusChanged(orderId: ID!): Order!
}Configuration (binds the SDL to hand-written structs, so fields without a struct member become resolvers):
schema:
- graph/*.graphqls
exec:
filename: graph/generated/generated.go
package: generated
model:
filename: graph/model/models_gen.go
package: model
resolver:
layout: follow-schema
dir: graph
package: graph
filename_template: "{name}.resolvers.go"
autobind:
- academy/graphql/graph/model
models:
ID:
model:
- github.com/99designs/gqlgen/graphql.ID
DateTime:
model: github.com/99designs/gqlgen/graphql.TimeDomain structs the schema binds to:
// Package model holds the hand-written domain structs that gqlgen binds to.
// Fields that are NOT present here (Order.customer, OrderLine.product,
// Customer.orders) become resolver methods in generated code.
package model
import "time"
type Customer struct {
ID string
Name string
Email string
}
func (Customer) IsNode() {}
func (Customer) IsSearchResult() {}
type Product struct {
ID string
Title string
PriceCents int
}
func (Product) IsNode() {}
func (Product) IsSearchResult() {}
// Price is the deprecated float field kept for old clients.
func (p Product) Price() float64 { return float64(p.PriceCents) / 100 }
type OrderLine struct {
ProductID string
Quantity int
}
type Order struct {
ID string
CustomerID string
Status OrderStatus
PlacedAt time.Time
Lines []*OrderLine
}
func (Order) IsNode() {}
func (Order) IsSearchResult() {}
func (c Customer) GetID() string { return c.ID }
func (p Product) GetID() string { return p.ID }
func (o Order) GetID() string { return o.ID }The in-memory store. Each method counts as one round trip, so tests can assert exactly how many queries a request caused:
// Package store is an in-memory stand-in for a database. Every method counts
// as ONE round trip, so tests can assert how many queries a GraphQL request
// really caused.
package store
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
"academy/graphql/graph/model"
)
type Store struct {
mu sync.RWMutex
customers map[string]*model.Customer
products map[string]*model.Product
orders []*model.Order // sorted by ID, which is also the keyset order
// Round-trip counters, one per kind of query.
CustomerQueries atomic.Int64
ProductQueries atomic.Int64
OrderQueries atomic.Int64
}
// Seed builds n customers (c1..cn), 3 products and 2n orders (o001..), where
// order i belongs to customer ((i-1) mod n)+1.
func Seed(n int) *Store {
s := &Store{customers: map[string]*model.Customer{}, products: map[string]*model.Product{}}
for i := 1; i <= n; i++ {
id := fmt.Sprintf("c%d", i)
s.customers[id] = &model.Customer{ID: id, Name: "Customer " + id, Email: id + "@example.test"}
}
for i, p := range []struct {
title string
cents int
}{{"Keyboard", 4500}, {"Mouse", 2500}, {"Monitor", 18900}} {
id := fmt.Sprintf("p%d", i+1)
s.products[id] = &model.Product{ID: id, Title: p.title, PriceCents: p.cents}
}
base := time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)
for i := 1; i <= 2*n; i++ {
s.orders = append(s.orders, &model.Order{
ID: fmt.Sprintf("o%03d", i),
CustomerID: fmt.Sprintf("c%d", (i-1)%n+1),
Status: model.OrderStatusPlaced,
PlacedAt: base.Add(time.Duration(i) * time.Hour),
Lines: []*model.OrderLine{
{ProductID: "p1", Quantity: 1},
{ProductID: fmt.Sprintf("p%d", i%3+1), Quantity: 2},
},
})
}
return s
}
// Customer is "SELECT ... WHERE id = $1": one round trip per call.
func (s *Store) Customer(_ context.Context, id string) (*model.Customer, error) {
s.CustomerQueries.Add(1)
s.mu.RLock()
defer s.mu.RUnlock()
c, ok := s.customers[id]
if !ok {
return nil, fmt.Errorf("customer %q not found", id)
}
return c, nil
}
// CustomersByIDs is "SELECT ... WHERE id = ANY($1)": one round trip for any
// number of keys. Missing ids are simply absent from the map.
func (s *Store) CustomersByIDs(_ context.Context, ids []string) (map[string]*model.Customer, error) {
s.CustomerQueries.Add(1)
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]*model.Customer, len(ids))
for _, id := range ids {
if c, ok := s.customers[id]; ok {
out[id] = c
}
}
return out, nil
}
func (s *Store) ProductsByIDs(_ context.Context, ids []string) (map[string]*model.Product, error) {
s.ProductQueries.Add(1)
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]*model.Product, len(ids))
for _, id := range ids {
if p, ok := s.products[id]; ok {
out[id] = p
}
}
return out, nil
}
func (s *Store) Order(_ context.Context, id string) (*model.Order, bool) {
s.OrderQueries.Add(1)
s.mu.RLock()
defer s.mu.RUnlock()
for _, o := range s.orders {
if o.ID == id {
return o, true
}
}
return nil, false
}
// OrdersAfter is keyset pagination: WHERE id > $after [AND customer_id = $c]
// ORDER BY id LIMIT $limit+1. It returns up to limit orders plus the total
// count, and whether more rows exist after the page.
func (s *Store) OrdersAfter(_ context.Context, customerID, afterID string, limit int) (page []*model.Order, total int, more bool) {
s.OrderQueries.Add(1)
s.mu.RLock()
defer s.mu.RUnlock()
for _, o := range s.orders {
if customerID != "" && o.CustomerID != customerID {
continue
}
total++
if o.ID <= afterID {
continue
}
if len(page) < limit {
page = append(page, o)
} else {
more = true
}
}
return page, total, more
}
// Insert stores a new order and assigns the next id.
func (s *Store) Insert(_ context.Context, customerID string, lines []*model.OrderLine) *model.Order {
s.mu.Lock()
defer s.mu.Unlock()
o := &model.Order{
ID: fmt.Sprintf("o%03d", len(s.orders)+1),
CustomerID: customerID,
Status: model.OrderStatusPlaced,
PlacedAt: time.Now().UTC(),
Lines: lines,
}
s.orders = append(s.orders, o)
sort.Slice(s.orders, func(i, j int) bool { return s.orders[i].ID < s.orders[j].ID })
return o
}
// Search is a toy full scan used to show a union return type.
func (s *Store) Search(_ context.Context, term string) (orders []*model.Order, customers []*model.Customer, products []*model.Product) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, o := range s.orders {
if o.ID == term {
orders = append(orders, o)
}
}
for _, c := range s.customers {
if c.Name == term {
customers = append(customers, c)
}
}
for _, p := range s.products {
if p.Title == term {
products = append(products, p)
}
}
return
}
// Product returns one product, used by totals.
func (s *Store) Product(id string) (*model.Product, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
p, ok := s.products[id]
return p, ok
}Per-request DataLoaders with dataloadgen, a 2 ms batching window and a middleware that creates fresh loaders for every request:
// Package loaders batches and caches key lookups for ONE request.
package loaders
import (
"context"
"net/http"
"time"
"github.com/vikstrous/dataloadgen"
"academy/graphql/graph/model"
"academy/graphql/store"
)
type ctxKey struct{}
type Loaders struct {
Customer *dataloadgen.Loader[string, *model.Customer]
Product *dataloadgen.Loader[string, *model.Product]
}
// New builds a fresh set of loaders. They MUST be created per request:
// a loader caches by key, so a process-wide loader would serve one user's
// data (and stale data) to everyone.
func New(s *store.Store) *Loaders {
wait := dataloadgen.WithWait(2 * time.Millisecond) // batching window
return &Loaders{
Customer: dataloadgen.NewMappedLoader(s.CustomersByIDs, wait),
Product: dataloadgen.NewMappedLoader(s.ProductsByIDs, wait),
}
}
// Middleware attaches per-request loaders to the context.
func Middleware(s *store.Store, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ctxKey{}, New(s))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// For returns the loaders of the current request.
func For(ctx context.Context) *Loaders {
return ctx.Value(ctxKey{}).(*Loaders)
}Resolvers, wired to the loaders, the connection helper and the authorization check:
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98
import (
"context"
"strings"
"academy/graphql/graph/generated"
"academy/graphql/graph/model"
"academy/graphql/loaders"
)
// Orders is the resolver for the orders field.
func (r *customerResolver) Orders(ctx context.Context, obj *model.Customer, first *int, after *string) (*model.OrderConnection, error) {
if err := authorizeCustomer(ctx, obj.ID); err != nil {
return nil, err
}
return r.connection(ctx, obj.ID, first, after)
}
// PlaceOrder is the resolver for the placeOrder field.
func (r *mutationResolver) PlaceOrder(ctx context.Context, input model.PlaceOrderInput) (*model.PlaceOrderPayload, error) {
return r.placeOrder(ctx, input)
}
// Customer is the resolver for the customer field.
func (r *orderResolver) Customer(ctx context.Context, obj *model.Order) (*model.Customer, error) {
// #region n-plus-one-before
if r.Naive {
// One database round trip per order row: the classic N+1.
return r.Store.Customer(ctx, obj.CustomerID)
}
// #endregion n-plus-one-before
// #region n-plus-one-after
// All Load calls made in the same ~2 ms window become ONE query.
return loaders.For(ctx).Customer.Load(ctx, obj.CustomerID)
// #endregion n-plus-one-after
}
// TotalCents is the resolver for the totalCents field.
func (r *orderResolver) TotalCents(ctx context.Context, obj *model.Order) (int, error) {
total := 0
for _, l := range obj.Lines {
if p, ok := r.Store.Product(l.ProductID); ok {
total += p.PriceCents * l.Quantity
}
}
return total, nil
}
// Product is the resolver for the product field.
func (r *orderLineResolver) Product(ctx context.Context, obj *model.OrderLine) (*model.Product, error) {
return loaders.For(ctx).Product.Load(ctx, obj.ProductID)
}
// Node is the resolver for the node field.
func (r *queryResolver) Node(ctx context.Context, id string) (model.Node, error) {
switch {
case strings.HasPrefix(id, "o"):
o, err := r.Order(ctx, id)
if o == nil {
return nil, err
}
return o, err
case strings.HasPrefix(id, "c"):
return loaders.For(ctx).Customer.Load(ctx, id)
case strings.HasPrefix(id, "p"):
return loaders.For(ctx).Product.Load(ctx, id)
}
return nil, nil
}
// Order is the resolver for the order field.
func (r *queryResolver) Order(ctx context.Context, id string) (*model.Order, error) {
o, ok := r.Store.Order(ctx, id)
if !ok {
return nil, nil // nullable field: unknown id is null, not an error
}
if err := authorizeCustomer(ctx, o.CustomerID); err != nil {
return nil, err // partial data: order is null, errors[0] explains why
}
return o, nil
}
// Orders is the resolver for the orders field.
func (r *queryResolver) Orders(ctx context.Context, first *int, after *string) (*model.OrderConnection, error) {
if !viewerFrom(ctx).Admin {
return nil, authorizeCustomer(ctx, "") // only admins list every order
}
return r.connection(ctx, "", first, after)
}
// Search is the resolver for the search field.
func (r *queryResolver) Search(ctx context.Context, term string) ([]model.SearchResult, error) {
orders, customers, products := r.Store.Search(ctx, term)
var out []model.SearchResult
for _, o := range orders {
if authorizeCustomer(ctx, o.CustomerID) == nil {
out = append(out, o)
}
}
for _, c := range customers {
out = append(out, c)
}
for _, p := range products {
out = append(out, p)
}
return out, nil
}
// OrderStatusChanged is the resolver for the orderStatusChanged field.
func (r *subscriptionResolver) OrderStatusChanged(ctx context.Context, orderID string) (<-chan *model.Order, error) {
return r.subscribe(ctx, orderID)
}
// Customer returns generated.CustomerResolver implementation.
func (r *Resolver) Customer() generated.CustomerResolver { return &customerResolver{r} }
// Mutation returns generated.MutationResolver implementation.
func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} }
// Order returns generated.OrderResolver implementation.
func (r *Resolver) Order() generated.OrderResolver { return &orderResolver{r} }
// OrderLine returns generated.OrderLineResolver implementation.
func (r *Resolver) OrderLine() generated.OrderLineResolver { return &orderLineResolver{r} }
// Query returns generated.QueryResolver implementation.
func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} }
// Subscription returns generated.SubscriptionResolver implementation.
func (r *Resolver) Subscription() generated.SubscriptionResolver { return &subscriptionResolver{r} }
type (
customerResolver struct{ *Resolver }
mutationResolver struct{ *Resolver }
orderResolver struct{ *Resolver }
orderLineResolver struct{ *Resolver }
queryResolver struct{ *Resolver }
subscriptionResolver struct{ *Resolver }
)package graph
import (
"sync"
"academy/graphql/graph/model"
"academy/graphql/store"
)
// Resolver is the dependency-injection root. Nothing here is global: tests
// build their own Resolver with their own Store.
type Resolver struct {
Store *store.Store
// Naive switches Order.customer to one query per row. It exists only to
// demonstrate and test the N+1 problem; production wiring leaves it false.
Naive bool
mu sync.Mutex
byKey map[string]*model.Order // idempotency key -> order
subs map[string][]chan *model.Order // order id -> subscribers
}
func NewResolver(s *store.Store) *Resolver {
return &Resolver{Store: s, byKey: map[string]*model.Order{}, subs: map[string][]chan *model.Order{}}
}Relay-style keyset pagination (opaque cursor, first clamped to 50, limit + 1 to find hasNextPage):
package graph
import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/vektah/gqlparser/v2/gqlerror"
"academy/graphql/graph/model"
)
const (
defaultPage = 10
maxPage = 50
)
// Cursors are opaque to clients: base64("o:" + id). Clients must never parse
// them; the server may change the format at any time.
func encodeCursor(id string) string { return base64.StdEncoding.EncodeToString([]byte("o:" + id)) }
func decodeCursor(c string) (string, error) {
raw, err := base64.StdEncoding.DecodeString(c)
if err != nil || !strings.HasPrefix(string(raw), "o:") {
return "", fmt.Errorf("invalid cursor")
}
return strings.TrimPrefix(string(raw), "o:"), nil
}
// connection implements a Relay-style forward cursor connection. first is
// clamped to maxPage so a client cannot ask for the whole table.
func (r *Resolver) connection(ctx context.Context, customerID string, first *int, after *string) (*model.OrderConnection, error) {
limit := defaultPage
if first != nil {
limit = *first
}
if limit < 0 {
return nil, &gqlerror.Error{Message: "first must not be negative", Extensions: map[string]any{"code": "BAD_USER_INPUT"}}
}
if limit > maxPage {
limit = maxPage
}
afterID := ""
if after != nil && *after != "" {
id, err := decodeCursor(*after)
if err != nil {
return nil, &gqlerror.Error{Message: err.Error(), Extensions: map[string]any{"code": "BAD_USER_INPUT"}}
}
afterID = id
}
page, total, more := r.Store.OrdersAfter(ctx, customerID, afterID, limit)
conn := &model.OrderConnection{
TotalCount: total,
PageInfo: &model.PageInfo{HasNextPage: more, HasPreviousPage: afterID != ""},
}
for _, o := range page {
conn.Edges = append(conn.Edges, &model.OrderEdge{Cursor: encodeCursor(o.ID), Node: o})
}
if n := len(conn.Edges); n > 0 {
start, end := conn.Edges[0].Cursor, conn.Edges[n-1].Cursor
conn.PageInfo.StartCursor, conn.PageInfo.EndCursor = &start, &end
}
return conn, nil
}Authorization in the service layer and a viewer taken from the request:
package graph
import (
"context"
"net/http"
"strings"
"github.com/vektah/gqlparser/v2/gqlerror"
)
type viewerKey struct{}
// Viewer is who is calling. A real service fills it from a verified token;
// this demo trusts "Authorization: Bearer <customer id>" or "admin".
type Viewer struct {
CustomerID string
Admin bool
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
v := Viewer{CustomerID: tok, Admin: tok == "admin"}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey{}, v)))
})
}
func viewerFrom(ctx context.Context) Viewer {
v, _ := ctx.Value(viewerKey{}).(Viewer)
return v
}
// authorizeCustomer is the per-object check. It lives in the resolver layer
// (really: in the domain/service layer the resolver calls) so that every path
// to an order, whether Query.order, node(id) or search, can reuse it.
func authorizeCustomer(ctx context.Context, customerID string) error {
v := viewerFrom(ctx)
if v.Admin || (v.CustomerID != "" && v.CustomerID == customerID) {
return nil
}
code := "FORBIDDEN"
if v.CustomerID == "" {
code = "UNAUTHENTICATED"
}
return &gqlerror.Error{Message: "not allowed to see this order", Extensions: map[string]any{"code": code}}
}A mutation with user errors and an idempotency key, and a subscription source that never blocks the publisher:
package graph
import (
"context"
"strconv"
"academy/graphql/graph/model"
)
// placeOrder shows the two error channels of GraphQL. Validation problems the
// client can fix are returned as DATA (userErrors) on an ok response; broken
// plumbing is returned as an error and ends up in the top-level errors array.
func (r *Resolver) placeOrder(ctx context.Context, in model.PlaceOrderInput) (*model.PlaceOrderPayload, error) {
r.mu.Lock()
if prior, ok := r.byKey[in.IdempotencyKey]; ok { // retry of the same intent
r.mu.Unlock()
return &model.PlaceOrderPayload{Order: prior, UserErrors: []*model.UserError{}}, nil
}
r.mu.Unlock()
var userErrors []*model.UserError
var lines []*model.OrderLine
for i, l := range in.Lines {
if l.Quantity <= 0 {
userErrors = append(userErrors, &model.UserError{
Field: []string{"input", "lines", strconv.Itoa(i), "quantity"},
Code: "QUANTITY_MUST_BE_POSITIVE",
Message: "quantity must be at least 1",
})
continue
}
lines = append(lines, &model.OrderLine{ProductID: l.ProductID, Quantity: l.Quantity})
}
if len(userErrors) > 0 {
return &model.PlaceOrderPayload{UserErrors: userErrors}, nil
}
if err := authorizeCustomer(ctx, in.CustomerID); err != nil {
return nil, err
}
o := r.Store.Insert(ctx, in.CustomerID, lines)
r.mu.Lock()
r.byKey[in.IdempotencyKey] = o
r.mu.Unlock()
r.publish(o)
return &model.PlaceOrderPayload{Order: o, UserErrors: []*model.UserError{}}, nil
}package graph
import (
"context"
"academy/graphql/graph/model"
)
// subscribe returns a channel that receives the order every time publish is
// called for it. gqlgen runs this once per subscription and streams each
// value to the client over the transport (graphql-ws on a WebSocket). When
// the client disconnects, ctx is cancelled and we unregister.
func (r *Resolver) subscribe(ctx context.Context, orderID string) (<-chan *model.Order, error) {
ch := make(chan *model.Order, 8)
r.mu.Lock()
r.subs[orderID] = append(r.subs[orderID], ch)
r.mu.Unlock()
go func() {
<-ctx.Done()
r.mu.Lock()
defer r.mu.Unlock()
subs := r.subs[orderID]
for i, c := range subs {
if c == ch {
r.subs[orderID] = append(subs[:i], subs[i+1:]...)
break
}
}
}()
return ch, nil
}
// publish never blocks the writer: a slow subscriber drops events (it can
// re-query the order), which is the safe choice for status updates.
func (r *Resolver) publish(o *model.Order) {
r.mu.Lock()
defer r.mu.Unlock()
for _, ch := range r.subs[o.ID] {
select {
case ch <- o:
default:
}
}
}
// SetStatus changes an order status and notifies subscribers.
func (r *Resolver) SetStatus(o *model.Order, st model.OrderStatus) {
o.Status = st
r.publish(o)
}Depth limit, a custom gqlgen extension that runs before any resolver:
// Package limits holds query-shape guards that run before any resolver.
package limits
import (
"context"
"fmt"
"github.com/99designs/gqlgen/graphql"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
)
// MaxDepth rejects operations whose selection sets nest deeper than Limit.
// Introspection fields count like any other field.
type MaxDepth struct{ Limit int }
var _ interface {
graphql.OperationContextMutator
graphql.HandlerExtension
} = MaxDepth{}
func (MaxDepth) ExtensionName() string { return "MaxDepth" }
func (MaxDepth) Validate(_ graphql.ExecutableSchema) error { return nil }
func (m MaxDepth) MutateOperationContext(_ context.Context, rc *graphql.OperationContext) *gqlerror.Error {
op := rc.Doc.Operations.ForName(rc.OperationName)
if op == nil {
return nil
}
if d := Depth(op.SelectionSet, rc.Doc.Fragments); d > m.Limit {
err := gqlerror.Errorf("operation has depth %d, which exceeds the limit of %d", d, m.Limit)
err.Extensions = map[string]any{"code": "DEPTH_LIMIT_EXCEEDED"}
return err
}
return nil
}
// Depth is the longest chain of fields in a selection set. Fragment spreads
// are followed; the validator has already rejected fragment cycles.
func Depth(set ast.SelectionSet, frags ast.FragmentDefinitionList) int {
max := 0
for _, sel := range set {
d := 0
switch s := sel.(type) {
case *ast.Field:
d = 1 + Depth(s.SelectionSet, frags)
case *ast.InlineFragment:
d = Depth(s.SelectionSet, frags)
case *ast.FragmentSpread:
if def := frags.ForName(s.Name); def != nil {
d = Depth(def.SelectionSet, frags)
}
default:
panic(fmt.Sprintf("unknown selection %T", sel))
}
if d > max {
max = d
}
}
return max
}Wiring: transports (POST, GET, WebSocket), APQ, complexity and depth limits, introspection policy:
// Package app wires the gqlgen executable schema with the production guards:
// transports, APQ, complexity and depth limits, introspection policy.
package app
import (
"net/http"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/lru"
"github.com/99designs/gqlgen/graphql/handler/transport"
"academy/graphql/graph"
"academy/graphql/graph/generated"
"academy/graphql/limits"
"academy/graphql/loaders"
"academy/graphql/store"
)
type Config struct {
Store *store.Store
Naive bool // demo only: disable batching to show N+1
Introspection bool // false in production for public endpoints
MaxComplexity int
MaxDepth int
}
func New(cfg Config) (http.Handler, *graph.Resolver) {
res := graph.NewResolver(cfg.Store)
res.Naive = cfg.Naive
gcfg := generated.Config{Resolvers: res}
// Complexity: a list field costs (page size x cost of one child).
gcfg.Complexity.Query.Orders = func(child int, first *int, _ *string) int { return pageSize(first) * child }
gcfg.Complexity.Customer.Orders = func(child int, first *int, _ *string) int { return pageSize(first) * child }
srv := handler.New(generated.NewExecutableSchema(gcfg))
srv.AddTransport(transport.Options{})
srv.AddTransport(transport.GET{}) // enables GET for queries (CDN/APQ friendly)
srv.AddTransport(transport.POST{})
srv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10_000_000_000}) // 10 s, graphql-ws and legacy
srv.Use(extension.AutomaticPersistedQuery{Cache: lru.New[string](1000)})
srv.Use(extension.FixedComplexityLimit(cfg.MaxComplexity))
srv.Use(limits.MaxDepth{Limit: cfg.MaxDepth})
if cfg.Introspection {
srv.Use(extension.Introspection{})
}
srv.SetErrorPresenter(graphql.DefaultErrorPresenter)
// Order matters: viewer first, then per-request loaders, then GraphQL.
var h http.Handler = srv
h = loaders.Middleware(cfg.Store, h)
h = graph.AuthMiddleware(h)
return h, res
}
func pageSize(first *int) int {
if first == nil {
return 10
}
if *first > 50 {
return 50
}
return *first
}package main
import (
"log"
"net/http"
"os"
"time"
"academy/graphql/app"
"academy/graphql/store"
)
func main() {
h, _ := app.New(app.Config{
Store: store.Seed(5),
Introspection: os.Getenv("GRAPHQL_INTROSPECTION") == "1", // off unless asked
MaxComplexity: 200,
MaxDepth: 8,
})
mux := http.NewServeMux()
mux.Handle("/graphql", h)
log.Println("listening on :8080 (POST /graphql)")
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())
}Tests (14, all pass with go test ./...): N+1 count with and without the loader, nested batching, cursor walk, partial data, null propagation, depth and complexity rejection, introspection, APQ handshake, idempotent mutation, union, subscription.
package app_test
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"academy/graphql/app"
"academy/graphql/graph/model"
"academy/graphql/store"
)
type gqlResponse struct {
Data map[string]any `json:"data"`
Errors []struct {
Message string `json:"message"`
Extensions map[string]any `json:"extensions"`
} `json:"errors"`
}
func newServer(t *testing.T, mutate func(*app.Config)) (http.Handler, *store.Store) {
t.Helper()
st := store.Seed(5) // 5 customers, 10 orders
cfg := app.Config{Store: st, Introspection: false, MaxComplexity: 300, MaxDepth: 8}
if mutate != nil {
mutate(&cfg)
}
h, _ := app.New(cfg)
return h, st
}
func post(t *testing.T, h http.Handler, viewer, body string) (int, gqlResponse) {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/graphql", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if viewer != "" {
req.Header.Set("Authorization", "Bearer "+viewer)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
var out gqlResponse
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("bad json %q: %v", rec.Body.String(), err)
}
return rec.Code, out
}
func q(query string) string {
b, _ := json.Marshal(map[string]string{"query": query})
return string(b)
}
const ordersWithCustomers = `{ orders(first: 10) { edges { node { id customer { name } } } } }`
// The N+1 problem: 1 query for the list + N for the customers.
func TestNaiveResolverCausesNPlusOne(t *testing.T) {
h, st := newServer(t, func(c *app.Config) { c.Naive = true })
_, resp := post(t, h, "admin", q(ordersWithCustomers))
if len(resp.Errors) > 0 {
t.Fatalf("errors: %+v", resp.Errors)
}
if got := st.CustomerQueries.Load(); got != 10 {
t.Fatalf("naive customer queries = %d, want 10 (one per order)", got)
}
}
// The DataLoader fix: the same request needs exactly one customer query.
func TestDataLoaderBatchesCustomerLookups(t *testing.T) {
h, st := newServer(t, nil)
_, resp := post(t, h, "admin", q(ordersWithCustomers))
if len(resp.Errors) > 0 {
t.Fatalf("errors: %+v", resp.Errors)
}
if got := st.CustomerQueries.Load(); got != 1 {
t.Fatalf("batched customer queries = %d, want 1", got)
}
if got := st.OrderQueries.Load(); got != 1 {
t.Fatalf("order list queries = %d, want 1", got)
}
}
// Two levels of fan-out (orders -> lines -> product) still cost one query each.
func TestNestedBatching(t *testing.T) {
h, st := newServer(t, nil)
query := `{ orders(first: 10) { edges { node { customer { name } lines { quantity product { title } } totalCents } } } }`
_, resp := post(t, h, "admin", q(query))
if len(resp.Errors) > 0 {
t.Fatalf("errors: %+v", resp.Errors)
}
if st.CustomerQueries.Load() != 1 || st.ProductQueries.Load() != 1 {
t.Fatalf("customer=%d product=%d, want 1 and 1", st.CustomerQueries.Load(), st.ProductQueries.Load())
}
}
func TestCursorPaginationWalksEveryOrderOnce(t *testing.T) {
h, _ := newServer(t, nil)
seen := []string{}
after := ""
for page := 0; page < 10; page++ {
arg := `first: 3`
if after != "" {
arg += `, after: "` + after + `"`
}
_, resp := post(t, h, "admin", q(`{ orders(`+arg+`) { totalCount pageInfo { hasNextPage endCursor } edges { cursor node { id } } } }`))
if len(resp.Errors) > 0 {
t.Fatalf("errors: %+v", resp.Errors)
}
conn := resp.Data["orders"].(map[string]any)
for _, e := range conn["edges"].([]any) {
seen = append(seen, e.(map[string]any)["node"].(map[string]any)["id"].(string))
}
info := conn["pageInfo"].(map[string]any)
if !info["hasNextPage"].(bool) {
break
}
after = info["endCursor"].(string)
}
if len(seen) != 10 || seen[0] != "o001" || seen[9] != "o010" {
t.Fatalf("seen = %v", seen)
}
}
func TestBadCursorIsAUserInputError(t *testing.T) {
h, _ := newServer(t, nil)
_, resp := post(t, h, "admin", q(`{ orders(first: 1, after: "not-a-cursor") { totalCount } }`))
if len(resp.Errors) != 1 || resp.Errors[0].Extensions["code"] != "BAD_USER_INPUT" {
t.Fatalf("errors = %+v", resp.Errors)
}
}
// Partial data: HTTP 200, one field null, one field fine, errors[] explains.
func TestPartialDataAndErrorExtensions(t *testing.T) {
h, _ := newServer(t, nil)
code, resp := post(t, h, "c1", q(`{ mine: order(id: "o001") { id } theirs: order(id: "o002") { id } }`))
if code != http.StatusOK {
t.Fatalf("status = %d, want 200 for a partial result", code)
}
if resp.Data["mine"] == nil || resp.Data["theirs"] != nil {
t.Fatalf("data = %+v", resp.Data)
}
if len(resp.Errors) != 1 || resp.Errors[0].Extensions["code"] != "FORBIDDEN" {
t.Fatalf("errors = %+v", resp.Errors)
}
}
func TestNonNullErrorBubblesToNullableParent(t *testing.T) {
h, _ := newServer(t, nil)
// c1 may read order o001, but not the other orders under customer c1... all
// are c1's. Ask as c1 for c2's orders: Customer.orders fails, and because
// orders is non-null the null propagates to the nullable node(id) result.
_, resp := post(t, h, "c1", q(`{ node(id: "c2") { ... on Customer { name orders { totalCount } } } }`))
if len(resp.Errors) == 0 || resp.Data["node"] != nil {
t.Fatalf("data=%+v errors=%+v", resp.Data, resp.Errors)
}
}
func TestDepthLimitRejectsBeforeResolvers(t *testing.T) {
h, st := newServer(t, func(c *app.Config) { c.MaxDepth = 5 })
deep := `{ orders(first: 1) { edges { node { customer { orders(first: 1) { edges { node { customer { name } } } } } } } } }`
_, resp := post(t, h, "admin", q(deep))
if len(resp.Errors) != 1 || resp.Errors[0].Extensions["code"] != "DEPTH_LIMIT_EXCEEDED" {
t.Fatalf("errors = %+v", resp.Errors)
}
if st.OrderQueries.Load() != 0 {
t.Fatal("resolvers ran although the operation was rejected")
}
}
func TestComplexityLimitCountsPageSizes(t *testing.T) {
h, _ := newServer(t, func(c *app.Config) { c.MaxComplexity = 100 })
// 50 orders x (customer + 50 orders each) is far above 100.
big := `{ orders(first: 50) { edges { node { customer { orders(first: 50) { edges { node { id } } } } } } } }`
_, resp := post(t, h, "admin", q(big))
if len(resp.Errors) != 1 || !strings.Contains(resp.Errors[0].Message, "exceeds the limit of 100") {
t.Fatalf("errors = %+v", resp.Errors)
}
_, ok := post(t, h, "admin", q(`{ orders(first: 2) { edges { node { id } } } }`))
if len(ok.Errors) > 0 {
t.Fatalf("small query rejected: %+v", ok.Errors)
}
}
func TestIntrospectionOffByDefaultOnWhenEnabled(t *testing.T) {
off, _ := newServer(t, nil)
_, resp := post(t, off, "", q(`{ __schema { queryType { name } } }`))
if len(resp.Errors) == 0 {
t.Fatal("introspection should be rejected when disabled")
}
on, _ := newServer(t, func(c *app.Config) { c.Introspection = true })
_, resp = post(t, on, "", q(`{ __schema { queryType { name } } }`))
if len(resp.Errors) > 0 || resp.Data["__schema"] == nil {
t.Fatalf("introspection failed: %+v", resp.Errors)
}
}
func TestAutomaticPersistedQueryHandshake(t *testing.T) {
h, _ := newServer(t, nil)
query := `{ search(term: "Keyboard") { __typename ... on Product { title } } }`
sum := sha256.Sum256([]byte(query))
hash := hex.EncodeToString(sum[:])
ext := `"extensions":{"persistedQuery":{"version":1,"sha256Hash":"` + hash + `"}}`
// 1. hash only, server has never seen it
_, resp := post(t, h, "", `{`+ext+`}`)
if len(resp.Errors) != 1 || resp.Errors[0].Message != "PersistedQueryNotFound" {
t.Fatalf("step 1 errors = %+v", resp.Errors)
}
// 2. hash plus full text: server stores it and answers
body, _ := json.Marshal(map[string]string{"query": query})
withText := strings.TrimSuffix(string(body), "}") + `,` + ext + `}`
_, resp = post(t, h, "", withText)
if len(resp.Errors) > 0 {
t.Fatalf("step 2 errors = %+v", resp.Errors)
}
// 3. hash only again: a small GET works now, so a CDN can cache it
u := "/graphql?extensions=" + url.QueryEscape(`{"persistedQuery":{"version":1,"sha256Hash":"`+hash+`"}}`)
req := httptest.NewRequest(http.MethodGet, u, nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"title":"Keyboard"`) {
t.Fatalf("step 3: %d %s", rec.Code, rec.Body.String())
}
}
func TestMutationUserErrorsAndIdempotency(t *testing.T) {
h, st := newServer(t, nil)
bad := `mutation { placeOrder(input: {customerId: "c1", idempotencyKey: "k0", lines: [{productId: "p1", quantity: 0}]}) { order { id } userErrors { field code } } }`
_, resp := post(t, h, "c1", q(bad))
if len(resp.Errors) > 0 {
t.Fatalf("validation problems must be data, not errors: %+v", resp.Errors)
}
ue := resp.Data["placeOrder"].(map[string]any)["userErrors"].([]any)
if len(ue) != 1 || ue[0].(map[string]any)["code"] != "QUANTITY_MUST_BE_POSITIVE" {
t.Fatalf("userErrors = %+v", ue)
}
good := `mutation { placeOrder(input: {customerId: "c1", idempotencyKey: "k1", lines: [{productId: "p1", quantity: 2}]}) { order { id totalCents } } }`
_, first := post(t, h, "c1", q(good))
_, second := post(t, h, "c1", q(good)) // client retry after a timeout
id1 := first.Data["placeOrder"].(map[string]any)["order"].(map[string]any)["id"]
id2 := second.Data["placeOrder"].(map[string]any)["order"].(map[string]any)["id"]
if id1 != id2 || id1 != "o011" {
t.Fatalf("ids = %v and %v, want the same o011", id1, id2)
}
if _, total, _ := st.OrdersAfter(context.Background(), "", "", 1); total != 11 {
t.Fatalf("store has %d orders, want 11 (one insert for two requests)", total)
}
}
func TestUnionAndDeprecatedField(t *testing.T) {
h, _ := newServer(t, nil)
_, resp := post(t, h, "", q(`{ search(term: "Keyboard") { __typename ... on Product { title priceCents price } } }`))
if len(resp.Errors) > 0 {
t.Fatalf("errors: %+v", resp.Errors)
}
item := resp.Data["search"].([]any)[0].(map[string]any)
if item["__typename"] != "Product" || item["priceCents"].(float64) != 4500 || item["price"].(float64) != 45 {
t.Fatalf("item = %+v", item)
}
}
func TestSubscriptionDeliversStatusChanges(t *testing.T) {
st := store.Seed(2)
_, res := app.New(app.Config{Store: st, MaxComplexity: 100, MaxDepth: 5})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch, err := res.Subscription().OrderStatusChanged(ctx, "o001")
if err != nil {
t.Fatal(err)
}
o, _ := st.Order(ctx, "o001")
res.SetStatus(o, model.OrderStatusShipped)
select {
case got := <-ch:
if got.Status != model.OrderStatusShipped {
t.Fatalf("status = %s", got.Status)
}
case <-time.After(time.Second):
t.Fatal("no event received")
}
}The Go angle
| Go feature or package | Use here | Note |
|---|---|---|
github.com/99designs/gqlgen | Schema-first generator and runtime | go get -tool github.com/99designs/gqlgen, then go tool gqlgen generate |
graphql/handler | handler.New(...) plus AddTransport and Use extensions | Transports: POST, GET, Options, Websocket, MultipartForm |
github.com/vikstrous/dataloadgen | Generic batching loader | Used by the gqlgen docs' dataloader recipe |
context.Context | Carries the viewer and the loaders | Cancelled when the client disconnects |
net/http/httptest | In-process tests of the whole handler | No port, no network |
| Interfaces in generated code | generated.QueryResolver, OrderResolver, ... | The compiler tells you which resolver is missing |
sync/atomic counters | Count queries in the store | Makes N+1 a failing test |
| Channels | Subscription sources | Close or stop writing when ctx.Done() |
Laravel
Laravel has no built-in GraphQL. The standard package is nuwave/lighthouse; the snippet targets version 6.x, whose composer.json requires illuminate/support ^9 || ^10 || ^11 || ^12 || ^13. Lighthouse reads an SDL file (graphql/schema.graphql) and maps directives to Eloquent.
Before
A hand-written resolver that returns models without eager loading is the Laravel flavour of N+1: each customer access lazy-loads.
<?php
declare(strict_types=1);
namespace App\GraphQL\Queries;
use App\Models\Order;
/**
* BEFORE: a hand-written resolver that returns models without eager loading.
* Selecting orders { customer { name } } runs 1 query for the orders and then
* one lazy-load query per order for its customer (N+1).
*/
final class NaiveOrders
{
/** @return iterable<Order> */
public function __invoke(): iterable
{
return Order::query()->limit(10)->get(); // customer is lazy-loaded later, per row
}
}After
The schema. @belongsTo and @hasMany batch the relation queries; @paginate(type: CONNECTION, maxCount: 50) creates the Relay types; @canModel and @canResolved call Laravel policies; @guard requires authentication:
scalar DateTime
@scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
enum OrderStatus {
PLACED
PAID
SHIPPED
CANCELLED
}
type Customer {
id: ID!
name: String!
email: String!
# @hasMany with CONNECTION gives first/after, edges, pageInfo, and batches
# the relation query across all customers in the result.
orders: [Order!]! @hasMany(type: CONNECTION, maxCount: 50)
}
type Product {
id: ID!
title: String!
priceCents: Int! @rename(attribute: "price_cents")
price: Float! @deprecated(reason: "Use priceCents; floats cannot represent money.")
}
type OrderLine {
quantity: Int!
product: Product! @belongsTo
}
type Order {
id: ID!
status: OrderStatus!
placedAt: DateTime! @rename(attribute: "placed_at")
customer: Customer! @belongsTo
lines: [OrderLine!]! @hasMany
totalCents: Int! @field(resolver: "App\\GraphQL\\Queries\\OrderTotal")
}
type Query {
# Only admins list every order; Relay-style connection, hard cap of 50.
orders: [Order!]!
@canModel(ability: "viewAny", model: "App\\Models\\Order")
@paginate(
type: CONNECTION
defaultCount: 10
maxCount: 50
complexityResolver: "App\\GraphQL\\Security\\ListComplexity@__invoke"
)
# Per-object authorization runs after the row is found.
order(id: ID! @whereKey): Order @find @canResolved(ability: "view")
}
input OrderLineInput {
productId: ID!
quantity: Int!
}
input PlaceOrderInput {
customerId: ID!
lines: [OrderLineInput!]!
idempotencyKey: String!
}
type UserError {
field: [String!]
code: String!
message: String!
}
type PlaceOrderPayload {
order: Order
userErrors: [UserError!]!
}
type Mutation {
placeOrder(input: PlaceOrderInput!): PlaceOrderPayload! @guard
}Models (relations are what the directives load):
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Customer extends Model
{
protected $fillable = ['name', 'email'];
/** @return HasMany<Order, $this> */
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
}<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Order extends Model
{
protected $fillable = ['customer_id', 'status', 'placed_at', 'idempotency_key'];
protected function casts(): array
{
return ['placed_at' => 'datetime'];
}
/** @return BelongsTo<Customer, $this> */
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
/** @return HasMany<OrderLine, $this> */
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
}<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class OrderLine extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity'];
/** @return BelongsTo<Product, $this> */
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
final class Product extends Model
{
protected $fillable = ['title', 'price_cents'];
/** Backs the deprecated GraphQL field Product.price. */
protected function price(): Attribute
{
return Attribute::get(fn (): float => $this->price_cents / 100);
}
}Policy used by @canModel (list) and @canResolved (single object):
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
final class OrderPolicy
{
public function viewAny(User $user): bool
{
return $user->is_admin;
}
/** Called by @canResolved after the Order row has been loaded. */
public function view(User $user, Order $order): bool
{
return $user->is_admin || $user->customer_id === $order->customer_id;
}
}Security configuration (the shipped default is complexity and depth disabled):
<?php
declare(strict_types=1);
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
// Excerpt of config/lighthouse.php (nuwave/lighthouse 6.x). The shipped
// defaults are QueryComplexity::DISABLED, QueryDepth::DISABLED and
// introspection allowed, so you must turn the guards on yourself.
return [
'security' => [
'max_query_complexity' => 200,
'max_query_depth' => 8,
'disable_introspection' => env('APP_ENV') === 'production'
? DisableIntrospection::ENABLED
: DisableIntrospection::DISABLED,
],
'pagination' => [
'default_count' => 10,
'max_count' => 50,
],
];Complexity function for the paginated list:
<?php
declare(strict_types=1);
namespace App\GraphQL\Security;
final class ListComplexity
{
/**
* A page costs (page size x cost of everything selected under each item).
* Signature documented at https://lighthouse-php.com/master/api-reference/directives.html#complexity
*
* @param array<string, mixed> $args
*/
public function __invoke(int $childrenComplexity, array $args): int
{
$first = min((int) ($args['first'] ?? 10), 50);
return 1 + $first * $childrenComplexity;
}
}Computed field, client-safe exception with extensions and a mutation with user errors and idempotency:
<?php
declare(strict_types=1);
namespace App\GraphQL\Queries;
use App\Models\Order;
final class OrderTotal
{
/**
* Uses the already eager-loaded relations when present, so selecting
* totalCents next to lines does not add queries per order.
*/
public function __invoke(Order $order): int
{
$order->loadMissing('lines.product');
return (int) $order->lines->sum(
fn ($line): int => $line->quantity * $line->product->price_cents,
);
}
}<?php
declare(strict_types=1);
namespace App\GraphQL\Exceptions;
use Exception;
use GraphQL\Error\ClientAware;
use GraphQL\Error\ProvidesExtensions;
/** A client-safe error that carries a machine-readable code in `extensions`. */
final class OrderPlacementRejected extends Exception implements ClientAware, ProvidesExtensions
{
public function __construct(string $message, private readonly string $reason)
{
parent::__construct($message);
}
public function isClientSafe(): bool
{
return true;
}
/** @return array<string, mixed> */
public function getExtensions(): array
{
return ['code' => $this->reason];
}
}<?php
declare(strict_types=1);
namespace App\GraphQL\Mutations;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
final class PlaceOrder
{
/**
* Validation problems are returned as DATA (userErrors); an exception would
* land in the top-level errors array and null the whole non-null payload.
*
* @param array{input: array{customerId: string, idempotencyKey: string, lines: list<array{productId: string, quantity: int}>}} $args
* @return array{order: ?Order, userErrors: list<array{field: list<string>, code: string, message: string}>}
*/
public function __invoke(mixed $root, array $args): array
{
$input = $args['input'];
$userErrors = [];
foreach ($input['lines'] as $i => $line) {
if ($line['quantity'] < 1) {
$userErrors[] = [
'field' => ['input', 'lines', (string) $i, 'quantity'],
'code' => 'QUANTITY_MUST_BE_POSITIVE',
'message' => 'quantity must be at least 1',
];
}
}
if ($userErrors !== []) {
return ['order' => null, 'userErrors' => $userErrors];
}
// A unique index on orders.idempotency_key makes a retry return the same row.
$order = DB::transaction(function () use ($input): Order {
$order = Order::firstOrCreate(
['idempotency_key' => $input['idempotencyKey']],
['customer_id' => $input['customerId'], 'status' => 'PLACED', 'placed_at' => now()],
);
if ($order->wasRecentlyCreated) {
$order->lines()->createMany(array_map(
fn (array $l): array => ['product_id' => $l['productId'], 'quantity' => $l['quantity']],
$input['lines'],
));
}
return $order;
});
return ['order' => $order, 'userErrors' => []];
}
}Feature test with MakesGraphQLRequests: counts queries to prove the batching and checks the page-size cap.
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Customer;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
use Nuwave\Lighthouse\Testing\RefreshesSchemaCache;
use Tests\TestCase;
final class OrdersGraphQLTest extends TestCase
{
use MakesGraphQLRequests;
use RefreshDatabase;
use RefreshesSchemaCache;
public function test_customer_relation_is_batched_not_n_plus_one(): void
{
$customers = Customer::factory()->count(10)->create();
foreach ($customers as $customer) {
Order::factory()->for($customer)->create();
}
$this->actingAs(User::factory()->create(['is_admin' => true]));
DB::enableQueryLog();
$response = $this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL'
{
orders(first: 10) {
edges { node { id customer { name } } }
}
}
GRAPHQL);
$queries = count(DB::getQueryLog());
$response->assertJsonCount(10, 'data.orders.edges');
// One query for the page, one for the page count, one for all customers.
// A lazy-loading resolver would need 1 + 10 + the count query.
$this->assertLessThanOrEqual(4, $queries, 'queries: '.$queries);
}
public function test_page_size_is_capped_by_max_count(): void
{
$this->actingAs(User::factory()->create(['is_admin' => true]));
$this->graphQL(/** @lang GraphQL */ <<<'GRAPHQL'
{ orders(first: 5000) { edges { node { id } } } }
GRAPHQL)->assertGraphQLErrorMessage('Maximum number of 50 requested items exceeded, got 5000. Fetch smaller chunks.');
}
}-- Schema the PlaceOrder mutation relies on: a retry returns the same row.
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers (id),
status TEXT NOT NULL DEFAULT 'PLACED',
placed_at TIMESTAMPTZ NOT NULL,
idempotency_key TEXT NOT NULL,
UNIQUE (idempotency_key)
);The Laravel angle
| Laravel or Lighthouse feature | Use here | Note |
|---|---|---|
nuwave/lighthouse | GraphQL server, schema from SDL | Config in config/lighthouse.php |
@belongsTo, @hasMany, @with | Relation fields with batched loading | batchload_relations can be turned off |
@paginate(type: CONNECTION) | Relay-shaped types and first, after | Cursor decodes to an offset today |
security.max_query_complexity, max_query_depth, disable_introspection | Limits | Disabled by default |
pagination.max_count | Cap on first | null means unrestricted |
@guard, @canModel, @canResolved, @canFind | Authentication and policy checks | @can is deprecated in favour of the @can* family |
ClientAware, ProvidesExtensions | Safe messages and extensions | From webonyx/graphql-php |
MakesGraphQLRequests | $this->graphQL(...) in feature tests | Add RefreshesSchemaCache too |
Model::preventLazyLoading() | Lazy loading throws in development | Laravel 13 Eloquent docs |
| Subscriptions | Pusher or Echo drivers (set LIGHTHOUSE_BROADCASTER=echo) | Not graphql-ws |
| Rate limiting | RateLimiter::for(...) plus the throttle middleware, added to the middleware list in config/lighthouse.php | Per request, not per cost: add cost analysis separately |
Solving the classic problems
N+1 queries
| Solution | How | Advantage | Limit |
|---|---|---|---|
| DataLoader per request | Batch keys in a window | Works for any source (SQL, REST, gRPC) | Needs per-request wiring |
| Eager loading in the parent | JOIN or with() using the selection set | One query, no window | Parent must know the selection (look-ahead) |
| Lighthouse relation directives | @belongsTo and @hasMany batch | No code | Eloquent only |
Look-ahead (graphql.CollectAllFields) | Read requested columns in the parent | Fewer columns | Resolver couples to the query shape |
Runaway queries
| Solution | How | Advantage | Limit |
|---|---|---|---|
| Depth limit | Reject beyond N levels | Cheap, easy | Wide queries slip through |
| Complexity limit | Cost per field times page size | Reflects real work | Needs calibration |
| Trusted documents | Allow only known operations | Strongest | Not for public APIs |
| Timeout and cancellation | ctx deadline, DB statement timeout | Last line of defence | Work done before the timeout counts |
| Rate limit by cost | Token bucket debited by complexity | Fair per client | Needs an identity |
Unsafe mutations on retry
| Solution | How | Advantage | Limit |
|---|---|---|---|
| Idempotency key in the input | Unique key per intent, server stores key to result | Safe retries | Storage and TTL |
| Natural idempotency | upsert by business key | No extra table | Not always possible |
Payload with userErrors | Report business failures as data | Client shows field errors | More schema |
Public read-heavy API
| Solution | How | Advantage | Limit |
|---|---|---|---|
| Persisted queries plus GET | Hash in the URL | CDN caching, small requests | No arbitrary queries |
| Response cache per field | Redis, @cache | Offloads database | Invalidation |
| Normalised client cache | Type:id | Instant UI after mutation | Clients must request id |
Choosing
REST, GraphQL or gRPC
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Public API, CRUD, webhooks, third-party integrations | REST | OpenAPI, ETag, CDN | Tooling, caching, simplicity |
| Many client types (web, iOS, Android, TV) with different needs | GraphQL | BFF, codegen, persisted queries | One contract, client-chosen fields |
| Mobile app on slow networks, many nested resources | GraphQL | APQ, GET, response compression | Fewer round trips and bytes |
| Aggregating 4+ backends for one screen | GraphQL BFF or federation | DataLoader, timeouts per upstream | Joins on the server |
| Internal service to service, low latency, strict schema | gRPC | Deadlines, mTLS | Binary, HTTP/2, streaming |
| Simple internal CRUD with one client | REST | None | GraphQL is overhead |
| Event stream to the browser | SSE or WebSocket | Subscriptions only if you already run GraphQL | Cheaper |
| File-heavy API | REST or pre-signed URLs | Multipart | Do not tunnel large files through GraphQL |
See REST API Design and gRPC & Protocol Buffers for the other two sides.
Which pagination and limit settings
| Workload | Page cap | Depth | Complexity | Notes |
|---|---|---|---|---|
| Public marketing site | 20 | 6 | 100 | GET plus CDN, trusted documents |
| Logged-in consumer app | 50 | 8 | 200–500 | Per-user rate limit |
| Internal admin tool | 100 | 12 | 1000 | Auth required, audit log |
| Partner API | 50 | 8 | by key | Contract per partner, cost-based quotas |
The numbers are starting points taken from the snippet defaults, not vendor recommendations. Calibrate from your own query logs.
In architecture: from a single process to a distributed system
Monolith: one process, one database
One GraphQL server inside the web app. Resolvers call services in the same process; DataLoader turns lists into WHERE id IN (...) queries against the one database. A Laravel app mounts Lighthouse at /graphql; a Go service mounts the gqlgen handler on a ServeMux. Limits, introspection policy and authorization are all configuration of one process, and tests run through httptest or graphQL() with no network.
Modular monolith: boundaries without the network
Each module (Orders, Customers, Catalog) exposes a Go interface or a Laravel service; resolvers call the module interface, never its tables. The schema may be split across files per module (orders.graphqls, customers.graphqls) and merged at build time. Authorization lives in the module service, so REST, GraphQL and jobs share one rule. When one module later becomes a service, only its resolver implementation changes.
Microservices: one graph over many services
Two shapes. A BFF GraphQL server calls services over gRPC or REST, with a loader per upstream, a timeout per upstream and nullable fields for optional services. Or Apollo Federation: each service owns a subgraph, the router plans queries, and entity keys connect them. Failures are partial by design: a failing Reviews subgraph nulls reviews and leaves the product page working. Mutations spanning services need a saga or an outbox (see Saga and Transactional Outbox), never a distributed transaction hidden in a resolver.
Distributed data: replicas, caches, regions
Reads behind loaders can go to replicas, so a mutation followed by a query can read stale data: return the written object from the mutation (and prime the loader), or route the next read to the primary (see Replication). Persisted-query GETs can be cached at a CDN edge per region; responses with errors must not be cached. Subscriptions need a shared bus (Redis Pub/Sub, Kafka, NATS) so that any instance can push to any connected client, and the connection layer scales separately from the query layer (Real-Time Communication).
Scaling path: 1x, 10x, 100x
| Load | Typical design | What changes |
|---|---|---|
| 1x (hundreds of RPS) | One server, loaders, depth and page caps, introspection off | Nothing exotic |
| 10x | Stateless replicas behind a load balancer, persisted queries over GET, response cache in Redis, query cost metrics, slow-resolver tracing | Cache and observability become the work |
| 100x | Federation or sharded BFFs, CDN for public reads, trusted documents only, cost-based rate limiting, subscription gateway on its own fleet, schema registry with CI checks | Organisational scaling (teams, ownership) matters as much as RPS |
Lab
Goal: count database round trips for the same query with and without batching, then prove that limits reject abusive queries before any SQL runs. The Go lab is a unit-level run in one process; the Laravel lab is expected, not run («expected, not run»).
Go: run the tests
cd docs/snippets/system-design/graphql/go
go vet ./... && go test -count=1 -v ./app
# --- PASS: TestNaiveResolverCausesNPlusOne customer queries = 10 (one per order)
# --- PASS: TestDataLoaderBatchesCustomerLookups customer queries = 1
# --- PASS: TestNestedBatching customer = 1, product = 1
# --- PASS: TestDepthLimitRejectsBeforeResolvers store order queries = 0
# --- PASS: TestComplexityLimitCountsPageSizes "exceeds the limit of 100"
# ok academy/graphql/app(The output above was produced on this machine with Go 1.27.4; all 14 tests passed.)
Go: poke the running server
Expected, not run:
GRAPHQL_INTROSPECTION=1 go run ./cmd/server &
curl -s localhost:8080/graphql -H 'Authorization: Bearer admin' -H 'Content-Type: application/json' \
-d '{"query":"{ orders(first: 2) { totalCount pageInfo { hasNextPage endCursor } edges { node { id customer { name } } } } }"}'
# {"data":{"orders":{"totalCount":10,"pageInfo":{"hasNextPage":true,"endCursor":"bzow..."},"edges":[...]}}}
curl -s localhost:8080/graphql -H 'Authorization: Bearer c1' -H 'Content-Type: application/json' \
-d '{"query":"{ order(id:\"o002\") { id } }"}'
# {"errors":[{"message":"not allowed to see this order","path":["order"],"extensions":{"code":"FORBIDDEN"}}],"data":{"order":null}}Laravel: count queries
Expected, not run (needs a Laravel 13 app with nuwave/lighthouse installed, factories for the models and a User model with is_admin and customer_id columns):
composer require nuwave/lighthouse
php artisan vendor:publish --tag=lighthouse-schema
php artisan test --filter=OrdersGraphQLTest
# test_customer_relation_is_batched_not_n_plus_one ..... PASS (<= 4 SQL statements for 10 orders)
# test_page_size_is_capped_by_max_count .................. PASSCommon misconceptions
| Belief | Reality |
|---|---|
| "GraphQL is faster than REST" | It saves round trips and bytes; the server can do more database work (N+1) unless you batch |
| "One endpoint means one failure domain I can monitor with 5xx" | Failures sit in errors under HTTP 200; count them |
| "Introspection off means the schema is secret" | Suggestions in errors, client bundles and trusted partners can leak it; authorize every field |
| "Non-null everywhere is cleaner" | One failure nulls the nearest nullable parent; model optional or flaky data as nullable |
| "A cursor is a page number" | It is an opaque string; clients must not parse it |
| "Mutations run in parallel like queries" | Top-level mutation fields run serially in the written order |
| "Rate limiting by requests is enough" | One query can cost a million rows; limit by cost |
| "DataLoader can be a singleton" | It caches by key; it must be per request or it leaks data |
"@deprecated removes the field" | It only marks it; remove after usage reaches zero |
| "GraphQL cannot use a CDN" | With GET and persisted queries it can; it just is not automatic |
| "Federation is a reverse proxy" | The router plans queries across subgraphs and merges entities |
| "GraphQL subscriptions equal graphql-ws" | Subscriptions are in the spec; graphql-ws is one transport (Lighthouse uses Pusher or Echo) |
Cheat sheet
| Topic | What to remember |
|---|---|
| Schema | SDL is the contract; schema-first with gqlgen and Lighthouse; check breaking changes in CI |
| Nullability | ! is a promise; failures propagate to the nearest nullable parent |
| Execution | Parse, validate, guards, coerce, execute; queries parallel, top-level mutations serial |
| N+1 | One loader per request; batch window of a few ms; return in key order |
| Pagination | Relay connection; opaque cursor; cap first; limit + 1 for hasNextPage |
| Errors | data plus errors; extensions.code; business problems as userErrors |
| Status codes | 200 usually; 422 for validation (gqlgen); monitor errors |
| Caching | Global ids, persisted queries, GET, normalised cache; APQ is not a safelist |
| Security | Depth ~8, complexity budget, first cap, timeout, rate limit by cost, introspection off in prod |
| Authorization | In the service layer; per object; same rule on every path (order, node, search) |
| Evolution | Add, @deprecated, measure, remove; no /v2 |
| Federation | Subgraphs own entities by @key; router plans; compose in CI |
| Subscriptions | graphql-ws: ConnectionInit, ConnectionAck, Subscribe, Next, Complete; shared bus behind |
| Uploads | Multipart spec or pre-signed URL; prefer the latter for large files |
| When it wins | Many clients, aggregation, mobile bandwidth; loses to REST for public cacheable and to gRPC for internal |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does GraphQL tend to produce N+1 queries, and what does DataLoader change? Must-know
Answer
Answer: Each field has its own resolver, so Order.customer is called once per order and cannot see its siblings. DataLoader collects the keys requested in the same batching window, de-duplicates them and calls one batch function, so 10 orders cost 1 customer query instead of 10. The loader must be created per request because it caches by key.
2 — A response has HTTP 200, data.order = null and one entry in errors. What happened, and how should monitoring treat it? Important
Answer
Answer: The field resolver failed (for example FORBIDDEN) and the null was returned for a nullable field, so the other fields could still be returned: partial data. HTTP 200 only says the server executed the request. Metrics should count responses with a non-empty errors array, split by extensions.code.
3 — What does [Order!]! mean, and what happens if one resolver for a non-null field fails? Important
Answer
Answer: The list is never null and never contains null. A failure in a non-null field cannot be represented as null, so the null propagates to the nearest nullable parent (and to data: null if there is none), with the error recorded in errors.
4 — Why is a Relay cursor "opaque", and what is wrong with @paginate(type: CONNECTION) in Lighthouse if you expected keyset paging? Good to know
Answer
Answer: Clients must not parse cursors, so the server can change their format (offset, keyset, encrypted). Lighthouse's docs say it "does not support actual cursor-based pagination as of now" and that the cursor decodes into a page offset, so it has Relay's shape but offset behaviour (rows can shift under inserts, deep pages cost more).
5 — Give two defences against abusive queries and explain why request-count rate limiting is not enough. Must-know
Answer
Answer: Depth limit and complexity (cost) limit, plus a first cap, timeouts and trusted documents. One request can ask for 50 x 50 x 50 rows, so a limit of N requests per minute does not bound the work; the limit must count cost.
6 — Where should an authorization check live, and why is checking the /graphql endpoint not enough? Must-know
Answer
Answer: In the service or domain layer the resolvers call, per object. The same object is reachable through order(id:), customer.orders, node(id:) and search; if each path implements its own check one is forgotten. The endpoint check only proves authentication.
7 — What is APQ, how does the handshake work, and why does it not replace a safelist? Important
Answer
Answer: Automatic Persisted Queries send the SHA-256 hash of the query. If the server answers PersistedQueryNotFound the client resends hash plus text, the server stores it, and later requests (even GET) carry only the hash. Any client can register any query, so APQ saves bytes and enables CDN caching but does not restrict what can be executed; a build-time safelist does.
8 — How do you remove a field without versioning the API? Must-know
Answer
Answer: Add the replacement, mark the old field @deprecated(reason: ...), measure usage per client version in the schema registry or logs, announce a date, and remove it when usage is near zero and the schema check passes.
9 — Federation versus a plain BFF: when is each right? Important
Answer
Answer: A BFF is simpler when one team owns the graph and the clients. Federation fits many teams that each own domain data: subgraphs own entities by @key, a router plans queries across them and compose checks protect the supergraph. It adds a hop and an operational platform.
10 — Name three situations where REST or gRPC is a better choice than GraphQL. Must-know
Answer
Answer: A public cacheable API where URL-level HTTP caching and CDN help; webhooks and simple CRUD integrations; internal service-to-service calls that need strict binary contracts, deadlines and streaming (gRPC). Also file-heavy APIs.
Glossary
| Term | Meaning |
|---|---|
| GraphQL | A query language and execution model for APIs with a typed schema; spec by the GraphQL Foundation |
| Schema | The set of types and root operations a server exposes |
| SDL | Schema Definition Language, the text syntax for a schema |
| Type | A named shape (object, interface, union, enum, input, scalar) |
| Scalar | A leaf type: Int, Float, String, Boolean, ID or a custom scalar |
| Enum | A scalar-like closed set of names |
| Interface | A set of fields that object types promise to provide |
| Union | A type that is one of several object types with no shared fields |
| Input type | A type used for arguments (input PlaceOrderInput) |
| Non-null | The ! modifier; null is not allowed and failures propagate upward |
| Query | A read operation |
| Mutation | A write operation; top-level fields run serially |
| Subscription | A long-lived operation that pushes results on events |
| Resolver | The function that produces one field's value |
| Execution | Parse, validate, coerce, run resolvers, complete values |
| Introspection | Querying the schema with __schema, __type and __typename |
| N+1 | One list query plus one query per item |
| DataLoader | A per-request batching and caching utility for key lookups |
| Batching | Combining many key lookups into one data-source call |
| Persisted queries | Queries stored on the server and referenced by hash |
| APQ | Automatic Persisted Queries: hash first, upload on miss |
| Normalised cache | Client cache keyed by type and id |
| Relay | Facebook's GraphQL client and the connection convention |
| Cursor connection | A paginated field with edges, node, cursor and pageInfo |
| Edges | The list of { node, cursor } items in a connection |
| pageInfo | hasNextPage, hasPreviousPage, startCursor, endCursor |
| Partial data | A response with both data and errors |
| errors array | The list of field or request errors in the response |
| extensions | A free map on errors and responses; holds machine codes |
| Query depth | Nesting level of a selection set |
| Query complexity | Estimated cost of an operation before execution |
| Cost analysis | Pricing fields and lists to enforce a budget |
| Rate limiting | Limiting calls (best by cost) per client and time |
| Authorization directive | A schema annotation that triggers an access check |
| Deprecation | Marking a field or value as scheduled for removal with @deprecated |
| Federation | Composing independent subgraphs into one supergraph |
| Supergraph | The composed schema a router serves |
| Subgraph | One service's part of a federated graph |
| Schema stitching | Merging remote schemas in a gateway at runtime |
| graphql-ws | The graphql-transport-ws WebSocket protocol for subscriptions |
| File upload | The multipart request convention with an Upload scalar |
| Over-fetching | Receiving more data than needed |
| Under-fetching | Needing several requests for one view |
| BFF | Backend for Frontend, a server shaped for one client |
| gqlgen | Go schema-first GraphQL generator and server |
| Lighthouse | Laravel GraphQL package (nuwave/lighthouse) |
| Apollo | Company and ecosystem: Apollo Client, Router, Federation, GraphOS |
References
- GraphQL specification, October 2021 edition: https://spec.graphql.org/October2021/
- GraphQL Learn: https://graphql.org/learn/, Pagination, Caching, Best practices, Schemas and types, Queries, Execution, Introspection, Authorization, Global Object Identification, Serving over HTTP, Federation
- Relay cursor connections specification: https://relay.dev/graphql/connections.htm
- graphql-ws protocol: https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md
- GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec
- DataLoader: https://github.com/graphql/dataloader
- Apollo Federation: https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/federation; Apollo APQ: https://www.apollographql.com/docs/apollo-server/performance/apq/
- The Guild: GraphQL Mesh, Schema stitching
- OWASP GraphQL Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html
- gqlgen: https://gqlgen.com/, Getting started, Dataloaders, Complexity, APQ, pkg.go.dev, dataloadgen
- Lighthouse: Installation, Directives reference, N+1, Relationships, Authorization, Resource exhaustion, Error handling, Subscriptions, File uploads, Testing,
lighthouse.phpconfig (v6.74.1),composer.json(v6.74.1) - Laravel 13: Eloquent relationships, Authorization, Rate limiting, Broadcasting