GraphQL interview questions and answers, from schema design to federation
GraphQL interview questions cover the schema and type system, how resolvers execute, the N+1 problem and DataLoader batching, cursor pagination, caching without URLs, securing a single endpoint against expensive queries, error handling with nullability, and federation. Many rounds also ask when you would pick REST instead. Strong candidates explain what the server does per field, not only what the client sends.
By Evin JohnPublished 8 min read
Where GraphQL questions come from
GraphQL shows up in frontend interviews (writing queries, fragments and client caching), in backend interviews (schema design, resolvers, performance and security) and in API design rounds where you defend GraphQL against REST or gRPC for a given product. Senior and platform roles add federation: how several teams own parts of one graph. The interviewer usually gives you a small domain such as posts, users and comments and asks for the schema, a query, and what the server does to answer it.
- ConceptsQueries, mutations and subscriptions; the type system; how a request is parsed, validated and executed.
- Design exerciseWrite the schema for a feature, including pagination and a mutation with error results.
- Performance and securityN+1, batching, caching, depth and cost limits, authorization.
- ArchitectureGraphQL versus REST, federation versus a single service, and how you would roll it out.
Fundamentals: schema, types and operations
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are queries, mutations and subscriptions? | Operation types | Queries read, mutations write (top-level mutation fields run one after another), subscriptions push events over a long-lived connection such as WebSocket or server-sent events. |
| What are the built-in scalar types? | Type system | Int, Float, String, Boolean and ID. Custom scalars such as DateTime add parsing and serialization rules. |
| What does the exclamation mark mean? | Nullability | Non-null. [Post!]! is a non-null list of non-null posts; [Post] allows a null list and null items. Nullability choices decide how errors spread. |
| Input type versus object type? | Inputs | Inputs are for arguments and cannot have resolvers or interface fields; object types are for output. Mutations usually take a single input object. |
| Interface versus union? | Abstract types | An interface defines shared fields that implementing types must have. A union groups types with no shared fields. Both need __typename or inline fragments to read type-specific fields. |
| What are fragments for? | Reuse and colocation | A named selection on a type, reused across queries. Component frameworks colocate fragments with the UI that needs them. |
| What are variables and why not string interpolation? | Safety and caching | Variables are typed and validated separately from the document, which avoids injection-like bugs and keeps the operation text constant for caching and persisted queries. |
| What are aliases and directives? | Query features | Aliases rename fields so one query can fetch the same field twice with different arguments. @include and @skip toggle fields by variable; @deprecated marks schema fields. |
| What is introspection? | Tooling | Querying the schema itself through __schema and __type, which powers IDEs and code generation. Many teams restrict it on public production APIs. |
| How do you version a GraphQL API? | Evolution | Mostly you do not: add fields, deprecate old ones with a reason, watch field usage, and remove them after clients migrate. |
type Query {
post(id: ID!): Post
posts(first: Int = 20, after: String): PostConnection!
}
type Mutation {
publishPost(input: PublishPostInput!): PublishPostResult!
}
type Post {
id: ID!
title: String!
author: User!
}
type User {
id: ID!
name: String!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge {
cursor: String!
node: Post!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
input PublishPostInput {
title: String!
body: String!
}
union PublishPostResult = PublishPostSuccess | ValidationError
type PublishPostSuccess { post: Post! }
type ValidationError { field: String! message: String! }Resolvers and execution
- What arguments does a resolver receive? The parent object, the field's arguments, a per-request context (user, database handles, loaders) and info about the query (field name, path, selection).
- What is a default resolver? If you do not write one, the server returns the property of the parent with the field's name. Most fields on simple types never need custom code.
- How is a query executed? Parse, validate against the schema, then resolve fields top-down: each object's fields can resolve in parallel, and each child resolver receives its parent's result.
- What belongs in context, and what must not? Request-scoped things: the authenticated user, loaders and per-request caches. Nothing shared across users, or one user's cached data can leak into another's response.
- Where should business logic and authorization live? In a service layer the resolvers call, so REST, jobs and GraphQL apply the same rules. Resolvers should stay thin.
The N+1 problem and DataLoader
Because each field resolves on its own, a query for 50 posts with their authors calls the author resolver 50 times. If each call runs a SELECT, that is one query for the posts plus 50 for the authors. The standard fix is a per-request loader that collects keys requested in the same tick, removes duplicates and fetches them in one batch.
function createLoader(batchFn) {
let queue = [];
const cache = new Map();
return {
load(key) {
if (cache.has(key)) return cache.get(key); // dedupe per request
const promise = new Promise((resolve, reject) => {
queue.push({ key, resolve, reject });
if (queue.length === 1) {
process.nextTick(async () => { // wait for siblings
const batch = queue;
queue = [];
try {
const values = await batchFn(batch.map((item) => item.key));
batch.forEach((item, i) => item.resolve(values[i]));
} catch (err) {
batch.forEach((item) => item.reject(err));
}
});
}
});
cache.set(key, promise);
return promise;
},
};
}
// Create one loader per request, in the context:
// context.authorLoader = createLoader(ids => selectAuthorsByIds(ids));
// Resolver: Post.author = (post, args, ctx) => ctx.authorLoader.load(post.authorId)- Why must the batch function return values in key order? The loader matches results to callers by position. A SQL
WHERE id IN (...)returns rows in any order, so map rows by ID and return one entry per key, with null for missing ones. - Why one loader per request? Its cache is a memo of that request's reads. A global loader would serve stale data and could return one user's records to another.
- Does DataLoader replace a cache like Redis? No. It removes duplicate and per-row fetches within one request; cross-request caching is a separate layer with its own invalidation.
- What about nested lists, such as comments for each post? Batch by parent ID: load all comments where postId is in the batch, then group them per post. Per-parent limits need a window function or a lateral join in SQL.
Pagination, caching and performance
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Offset or cursor pagination? | Pagination | Offset is simple but skips or repeats items when data changes and slows on deep pages. Cursors encode a position (often the sort key and ID) and stay stable; the connection pattern adds edges, nodes and pageInfo. |
| Why is HTTP caching harder with GraphQL? | Caching | Most requests are POSTs to one URL, so CDNs and browsers cannot key on the URL. Persisted queries sent as GET with a hash and variables restore URL-based caching. |
| What does a normalized client cache do? | Client state | It stores each object once, keyed by type and ID, so an update from a mutation refreshes every query that shows that object. |
| How do you cache on the server? | Response caching | Per-field or per-type cache hints combined into a response max-age, data loaders within a request, and ordinary caches behind the resolvers. |
| How do you stop a query from taking the server down? | Abuse protection | Depth limits, cost analysis that multiplies list sizes, pagination caps on every list, timeouts, rate limits by cost rather than request count, and allowlisting persisted queries for first-party clients. |
| What are persisted queries? | Performance and security | The client sends a hash instead of the full document. The server looks up a registered operation, which saves bandwidth and, when only registered operations are allowed, blocks arbitrary queries. |
| How do you monitor a GraphQL API? | Observability | By operation name and per-field timing, not by URL, since every request hits the same endpoint. Track field usage before removing deprecated fields. |
Errors and nullability
A GraphQL response can contain both data and errors. When a resolver fails, its field becomes null and an error with a path is added. If that field is non-null, the null moves up to the nearest nullable parent, which can wipe out much more of the response than the failing field. This is why many schema designers keep fields that depend on other services nullable.
{
"errors": [
{
"message": "Cannot return null for non-nullable field User.name.",
"locations": [{ "line": 1, "column": 11 }],
"path": ["me", "name"]
}
],
"data": { "me": null }
}- Errors array or errors as data? Use the errors array for unexpected failures. Model expected business outcomes, such as a validation failure or an out-of-stock item, as result types in the schema (a union or a payload with an errors field), so clients handle them with types.
- What HTTP status should a GraphQL server return? Traditionally 200 for anything the server could execute, with errors in the body. The newer GraphQL over HTTP specification work recommends non-200 statuses for requests that fail before execution when using its newer response media type; say what your server and clients expect.
- How do you avoid leaking internals in errors? Mask unexpected errors in production, attach a stable error code in extensions, and log the details server-side with the request ID.
Authorization, federation and GraphQL versus REST
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Where do you authenticate and where do you authorize? | Security layering | Authenticate once per request and put the user in context. Authorize at the object or field level in the business layer, because the same object can be reached through many paths in the graph. |
| What is schema federation? | Distributed graphs | Several subgraphs, each owned by a team, are composed into one supergraph served by a router. Entities declared with a key (for example User by id) can be extended by other subgraphs, and the router plans queries across them. |
| Federation or schema stitching or one monolith? | Trade-offs | One service is simplest until many teams contend for it. Federation adds a router, composition checks and cross-service query plans, worth it when ownership boundaries are real. |
| GraphQL or REST for a new public API? | Judgment | REST is simpler to cache, rate limit and document for third parties. GraphQL shines when many clients need different shapes of the same data and the team controls those clients. |
| How do you handle file uploads? | Practicalities | Usually outside GraphQL: the mutation returns a signed upload URL, the client uploads directly to storage, then a mutation confirms it. |
| How do subscriptions scale? | Real-time | Long-lived connections need a pub/sub backbone across server instances, authorization on each event, and backpressure. For simple cases, polling a query may be enough. |
Fictional example
- Interviewer
- The mobile feed asks for 20 posts with author, comment count and the first three comments. Latency went from 120 ms to over a second. How do you investigate?
- Candidate
- I would start with per-field tracing for that operation name, because GraphQL hides cost behind one endpoint. The pattern you describe sounds like N+1 at two levels: 20 author lookups and 20 comment queries, plus a COUNT per post. Authors are a simple batch, one loader keyed by author ID. Comment counts batch well too: one grouped count for all 20 post IDs. The first three comments per post need care, because a plain IN query cannot limit per parent, so I would use a window function partitioned by post ID, or a lateral join, inside one batch loader. That turns roughly 60 queries into four. Then I would check that the list arguments have caps and that the cost limit counts comments per post, so a client cannot ask for 500 posts with 500 comments each. Finally, I would watch the trace again to confirm the field timings dropped.
One-week GraphQL practice plan
- Day 1: write a schema for a small app with interfaces, a union, an input type and a connection, and validate it with a GraphQL library.
- Day 2: implement resolvers over a real database and log every SQL statement; count the queries for a nested request.
- Day 3: add per-request loaders, then measure again. Get the key-ordering bug on purpose and fix it.
- Day 4: add cursor pagination with an opaque cursor and a cap on page size, and a depth or cost limit.
- Day 5: make a resolver throw inside a non-null field and watch the null propagate; redesign the nullability.
- Days 6 and 7: argue GraphQL versus REST for three products out loud, and sketch how two teams would federate users and orders.
The batching idea here is the same fix Java teams use for ORM N+1 queries, covered in Hibernate and JPA interview questions. If your resolvers sit on a document store, see MongoDB interview questions. Frontend candidates should also read frontend developer interview questions, and API design broader than GraphQL comes up in backend developer interview questions.
GraphQL answers often go wrong in the order of the explanation rather than in the facts. Natively, an AI interview assistant for Mac and Windows, records a text transcript of your mock API round on your computer, so you can review whether you described what the server does per field. During practice it can read a schema or a slow query trace from a screenshot and suggest directions, and with Pro or the free trial it can use the résumé and job description you add. Your transcript and notes remain afterwards.
Questions people ask
What GraphQL questions are asked in interviews?
Expect the type system and nullability, queries versus mutations and subscriptions, how resolvers execute, the N+1 problem and DataLoader, cursor pagination, caching, query cost limits, error handling, federation and when to choose REST instead.
What is the N+1 problem in GraphQL?
Each field resolves separately, so fetching a list of N items and a related object per item can run one query for the list plus N more. A per-request DataLoader batches those lookups into one query and deduplicates keys.
What is the difference between GraphQL and REST?
REST exposes many resource URLs with fixed responses and benefits from HTTP caching. GraphQL exposes one typed endpoint where clients choose the fields they need, which reduces over-fetching but makes caching, rate limiting and monitoring work differently.
How do you secure a GraphQL API?
Authenticate per request, authorize at the object or field level in business logic, and protect the endpoint with depth and cost limits, page size caps, timeouts and, for first-party clients, an allowlist of persisted queries.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
