Most engineers can write a schema and a few resolvers. Interviews for mid and senior roles go further. They ask what happens when that schema meets real traffic: a client nests five levels deep, a mobile app from two years ago still sends an old query, or one failing downstream service has to avoid blanking an entire screen. This guide covers the concepts behind strong answers to those situational questions. Each section explains the mechanism, shows a short example from an invented product, and lists the traps that separate a textbook answer from one grounded in production experience. Work through them in the study order at the end. The first few come up in almost every GraphQL interview.
Study order
If time is short, go in this order.
- The N+1 problem and request-scoped batching with DataLoader
The most common performance question in GraphQL interviews. It tests whether you understand how resolvers actually execute.
- Protecting the server with depth, complexity and rate limits
Shows you know that flexible queries are also an attack and capacity problem, a core senior-level concern.
- Nullability, null propagation and partial results
Null propagation surprises many engineers. Explaining it well signals real production experience with partial failures.
- Authorization at the field and object level
Graph traversal breaks endpoint-style security, and interviewers probe this to check you think about data exposure.
- Evolving a schema without versioning
Versionless evolution is how GraphQL APIs survive years of client releases, and it comes up in any API-design discussion.
- Cursor-based pagination and the connection pattern
A concrete design question that combines schema shape, database indexing and correctness under concurrent writes.
- Caching and persisted queries
Rounds out the production picture: performance at the edge and in clients, and locking down first-party APIs.
The N+1 problem and request-scoped batching with DataLoader
GraphQL resolves each field independently. Take a bookstore app called Inkwell, where a query asks for 50 books and each book's author. A naive Book.author resolver runs one SELECT per book: 1 query for the list plus 50 for authors. Nothing in the schema warns you. The cost only shows up in database metrics.
DataLoader fixes this by collecting every load(id) call made in the same tick of the event loop, then calling your batch function once with all the keys. The batch function must return results in the same order and the same length as the keys, with an Error or null where a key has no match. It also memoizes per key, so the same author requested twice is fetched once.
Create loaders per request, inside the context factory. A loader shared across requests becomes an unbounded cache that serves stale data, and it can leak one user's data to another when access rules differ.
TypeScript
import DataLoader from 'dataloader';
type Author = { id: string; name: string };
declare const db: { query<T>(sql: string, params: unknown[]): Promise<T[]> };
async function batchAuthors(ids: readonly string[]): Promise<(Author | Error)[]> {
const rows = await db.query<Author>(
'SELECT id, name FROM authors WHERE id = ANY($1)',
[ids],
);
const byId = new Map(rows.map((r) => [r.id, r]));
return ids.map((id) => byId.get(id) ?? new Error(`Author ${id} not found`));
}
export function createContext() {
return { authorLoader: new DataLoader(batchAuthors) };
}
export const resolvers = {
Book: {
author: (book: { authorId: string }, _args: unknown, ctx: ReturnType<typeof createContext>) =>
ctx.authorLoader.load(book.authorId),
},
};Fifty Book.author calls collapse into one SQL query. The batch function reorders rows to match the input keys.
Traps
- Returning database rows in whatever order SQL gives them. DataLoader maps results by position, so authors get attached to the wrong books.
- Creating the loader at module level instead of per request. This produces stale reads across requests and possible cross-tenant leaks.
- Assuming DataLoader fixes every N+1. Paginated or filtered children such as
author.books(first: 5)need a batch query that applies the limit per parent, for example with a window function or LATERAL join. - Awaiting inside a loop before calling load, which splits calls across ticks and defeats batching.
Protecting the server with depth, complexity and rate limits
A single GraphQL request can ask for an arbitrary amount of work. On Inkwell, shelves(first: 100) { books(first: 100) { reviews(first: 100) { ... } } } describes a million review nodes in under a hundred bytes. Counting requests per minute is meaningless when one request can be a million times more expensive than another.
The defences come in layers. A depth limit rejects deeply nested and cyclic queries cheaply. A complexity or cost analysis runs before execution: it multiplies list sizes by the cost of their children and rejects anything over a budget. Production APIs often rate limit on cost points per client per window rather than on request count. Add a hard cap on first and last arguments in the schema or resolver, plus an execution timeout as a last resort.
Cost estimation is static and approximate. It runs on the parsed document and the variables before any resolver fires. Tune the weights against real latency data instead of treating them as exact.
TypeScript
import { parse, Kind, SelectionSetNode } from 'graphql';
function cost(set: SelectionSetNode | undefined, multiplier = 1): number {
if (!set) return 0;
let total = 0;
for (const sel of set.selections) {
if (sel.kind !== Kind.FIELD) continue;
const first = sel.arguments?.find((a) => a.name.value === 'first');
const n = first && first.value.kind === Kind.INT ? parseInt(first.value.value, 10) : 1;
total += multiplier + cost(sel.selectionSet, multiplier * n);
}
return total;
}
const doc = parse('{ shelves(first: 20) { books(first: 50) { title } } }');
const op = doc.definitions[0];
if (op.kind === Kind.OPERATION_DEFINITION) {
console.log(cost(op.selectionSet)); // 1021
}A simplified cost walker: 1 shelves field, 20 books fields, 1000 title fields. Real implementations also resolve variables, fragments and per-field weights.
Traps
- Ignoring fragments and variables in cost analysis. Attackers then move the expensive part into a fragment or pass
firstas a variable. - Relying on a depth limit alone. A shallow query with huge list sizes, or many aliased copies of one expensive field, stays under any depth limit.
- Forgetting aliases and batched operations. Fifty aliases of the same field in one document multiply the work.
- Leaving introspection and verbose error messages open in production without considering what they reveal, when the API is meant to serve only first-party clients.
Evolving a schema without versioning
GraphQL APIs usually live at one endpoint with no /v2. Clients select only the fields they use, so adding types, fields, enum values and optional arguments is safe for most clients. The breaking changes are the ones that remove or narrow something: deleting a field, changing a type, making a nullable field non-null in an input, making an argument required, or making an output field nullable when clients assumed it never was.
The workflow is additive first, then deprecate, then remove. Say PawPoint, a vet booking app, wants to replace Appointment.time: String with a proper timestamp. You add startsAt: DateTime!, mark time with @deprecated(reason: ...), ship clients that use the new field, and watch field-level usage metrics until traffic on time drops to zero or to an agreed threshold. Only then do you remove it.
Enums deserve extra care. Adding an enum value is backward compatible for the schema, but older clients with exhaustive switch statements may crash on a value they don't know. Treat new output enum values as a coordinated change.
GraphQL
scalar DateTime
enum AppointmentStatus {
BOOKED
CHECKED_IN
COMPLETED
CANCELLED
}
type Appointment {
id: ID!
time: String @deprecated(reason: "Use startsAt. Removal planned once usage reaches zero.")
startsAt: DateTime!
durationMinutes: Int!
status: AppointmentStatus!
}
type Query {
appointments(clinicId: ID!, first: Int = 20): [Appointment!]!
}The old field keeps working and shows a deprecation notice in tooling, while new clients move to startsAt.
Traps
- Removing a deprecated field because the web app no longer uses it, while old mobile app versions still in the wild keep requesting it.
- Changing an output field from non-null to nullable and calling it safe. Typed clients that generated non-optional types will break or crash on null.
- Skipping schema diff checks in CI. A tool that compares the new schema against the published one catches accidental breaking changes before deploy.
- Deprecating without a replacement or reason string, which leaves client teams guessing what to migrate to.
Nullability, null propagation and partial results
A GraphQL response can contain both data and errors. When a resolver throws, the executor records the error with a path and sets that field to null. If the field is declared non-null, the null can't live there, so it propagates up to the nearest nullable parent. A single failing non-null field deep in a list can wipe out the whole list, or the entire data object.
This makes nullability a resilience decision as much as a typing one. On PawPoint, the clinic page shows opening hours from the main database and a rating from a separate reviews service. If Clinic.rating is non-null, a reviews outage blanks the clinic page. If it is nullable, the page renders with the rating missing and an entry in errors. A common guideline: mark a field non-null only when it comes from the same source as its parent and cannot fail independently.
For expected failures a client must handle, such as a slot already taken during booking, many teams model errors as data with union or result types. The errors array is then reserved for unexpected faults.
JSON
{
"data": {
"clinic": {
"id": "cl_42",
"name": "Harbourside Vets",
"openingHours": "Mon-Fri 08:00-18:00",
"rating": null
}
},
"errors": [
{
"message": "Reviews service unavailable",
"path": ["clinic", "rating"],
"extensions": { "code": "UPSTREAM_UNAVAILABLE" }
}
]
}Because Clinic.rating is nullable, a reviews outage degrades one field instead of nulling the whole clinic.
Traps
- Making everything non-null for nicer client types. Any single resolver failure then nulls out large parts of the response.
- Clients that check only for HTTP 200 and ignore the
errorsarray, silently rendering missing data as if it were valid. - Putting business errors such as validation failures in
errorswith free-text messages. Clients can't handle them reliably without stable codes or typed result unions. - Leaking stack traces or SQL text in error messages. Mask unexpected errors in production and keep details in server logs keyed by a request ID.
Cursor-based pagination and the connection pattern
Offset pagination (limit and offset) gets slower as offsets grow, because the database still walks the skipped rows. It also skips or duplicates items when rows are inserted or deleted between page loads. Cursor pagination encodes a position, typically the sort key plus a unique tiebreaker, and asks for the rows after it. With a matching index that is an index seek, so cost stays roughly constant no matter how deep the client pages.
The connection pattern standardises the shape: a Connection type with edges (each holding a node and a cursor) and pageInfo with hasNextPage and endCursor. Client libraries understand this shape and can merge pages into a cache automatically. Cursors should be opaque, usually base64-encoded, so you can change their internals later.
On Inkwell, a book's reviews sorted newest first would use a cursor of (created_at, id). The resolver fetches first + 1 rows to compute hasNextPage without a separate count query.
GraphQL
type Review {
id: ID!
rating: Int!
body: String
createdAt: DateTime!
}
type ReviewEdge {
cursor: String!
node: Review!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
type ReviewConnection {
edges: [ReviewEdge!]!
pageInfo: PageInfo!
}
type Book {
id: ID!
title: String!
reviews(first: Int = 10, after: String): ReviewConnection!
}The resolver decodes after, queries WHERE (created_at, id) < (cursor values) ORDER BY created_at DESC, id DESC LIMIT first + 1.
Traps
- Using only a timestamp as the cursor. Rows that share a timestamp get skipped or repeated, so include a unique tiebreaker such as the id.
- Exposing a
totalCountthat runs COUNT(*) on a large table for every request. Make it a separate field so clients pay for it only when they ask. - Not capping
first, which turns pagination into an unbounded list query. - Building the cursor from a column that isn't in the ORDER BY or isn't indexed together with it, which brings back full scans.
Caching and persisted queries
GraphQL typically uses POST to a single URL, so standard HTTP caches and CDNs have nothing to key on. Caching therefore happens in several places. Normalized client caches store objects by __typename and id. Resolvers and loaders can cache upstream data with explicit TTLs. Whole-response caching works at the edge only when requests are made cacheable.
Persisted queries make that possible. At build time the client registers each operation and gets a hash, usually SHA-256 of the query text. At runtime it sends only the hash and variables, often as a GET, which a CDN can cache. Automatic persisted queries register hashes lazily on first miss. A strict allowlist, registered during deploy, rejects any operation not in the list. For a first-party API that also removes most of the arbitrary-query attack surface.
Response caching must respect the viewer. Mark data as public or private per field, use the most restrictive hint in the response, and never let a CDN cache a response that contains user-specific fields under a shared key.
TypeScript
import { createHash } from 'node:crypto';
const allowlist = new Map<string, string>();
export function registerOperation(query: string): string {
const hash = createHash('sha256').update(query).digest('hex');
allowlist.set(hash, query);
return hash;
}
export function resolveIncoming(body: { hash?: string; query?: string }): string {
if (body.query !== undefined) {
throw new Error('Arbitrary queries are disabled; send a registered hash');
}
const query = body.hash ? allowlist.get(body.hash) : undefined;
if (!query) throw new Error('PERSISTED_QUERY_NOT_FOUND');
return query;
}
const h = registerOperation('query Clinic($id: ID!) { clinic(id: $id) { id name } }');
console.log(resolveIncoming({ hash: h }).startsWith('query Clinic')); // trueA strict allowlist: the build step registers operations, and production executes only known hashes.
Traps
- Putting a response with private fields behind a CDN under a key that doesn't include the user, which serves one user's data to another.
- Forgetting that a normalized client cache needs
idselected on every object. Without it, updates after mutations don't reach other views. - Enabling strict allowlists while old clients still send unregistered queries. Keep registrations from previous releases for as long as those clients are supported.
- Turning on GET for mutations. Only queries should be cacheable or sent via GET.
Common questions
Short answers to the usual doubts.
What HTTP status code should a GraphQL server return when a field fails?
Over the common GraphQL-over-HTTP setup with the application/json response type, a request that executes returns 200 even if some fields fail, with details in the errors array. Non-2xx codes are used for requests that can't be executed at all, such as malformed JSON, a parse or validation failure under the newer media type, or a failed authentication at the transport level. Monitoring must therefore inspect the errors array, not just status codes.
When is GraphQL a worse choice than REST?
When clients are few and their needs are simple and stable, when you rely heavily on HTTP caching for public resources, or when the main workload is file transfer or streaming. GraphQL shines when many clients need different slices of related data and you can invest in batching, cost limits and schema governance.
How do subscriptions change the production picture?
They hold long-lived connections, usually over WebSockets, so you need sticky sessions or a pub/sub layer such as Redis so events reach the right server instance. Authorization must be checked both at subscribe time and for each event, since permissions can change while the connection stays open. Connection limits and heartbeat timeouts matter as much as query limits.
What is federation and when do teams adopt it?
Federation composes one supergraph from multiple subgraphs owned by different teams, with a gateway or router planning queries across them. Teams adopt it when a single schema becomes an organisational bottleneck. It adds query-planning latency, cross-service N+1 risks and the need for composition checks in CI, so it's rarely worth it for a small team.
How should mutations be designed for reliability?
Use one specific mutation per intent, such as cancelAppointment, rather than a generic update. Accept a single input object and return a payload that includes the changed objects so client caches update. For operations that clients may retry, like payments or bookings, accept an idempotency key and return the original result on duplicates.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- GraphQL APIs in productionTake the test
- A public GraphQL APISolve the exercise