Complete Interview Questions & Answer Bank
50 curated interview questions ordered strictly by difficulty from Easy to Expert covering core concepts, schema design, performance, security, and federation.
Q1: What is GraphQL and what primary problem does it solve?
GraphQL is an open-source query language for APIs and a runtime for fulfilling those queries with existing data. Developed by Facebook in 2012 and open-sourced in 2015, it provides a complete and understandable description of the data in your API.
Primary problems solved:
- Over-fetching: Clients receive only the specific fields they request.
- Under-fetching: Multiple nested resources can be retrieved in a single request instead of round-tripping to multiple endpoints.
- Strong Typing: The API schema serves as a strict contract between client and server.
Quick Facts
Facebook (Meta)
2015
GraphQL allows clients to request exactly what data they need.
It eliminates over-fetching and under-fetching using a single endpoint.
Which issue is directly eliminated by GraphQL allowing field-level selection?
Q2: How does GraphQL differ from a traditional REST API?
In REST, endpoints represent resources (e.g., /users, /posts), and data structure is fixed by the server. GraphQL uses a single endpoint (typically /graphql) where clients post a structured query specifying the exact response shape.
REST vs GraphQL Comparison
Multiple resource URIs
REST requires multiple network calls for relational data.
Single endpoint
GraphQL executes complex declarative queries at one endpoint.
Server defines payload
REST payload structure is static.
Client defines payload
GraphQL response reflects requested schema fields.
REST relies on multiple resource endpoints, while GraphQL operates over a single endpoint.
GraphQL gives the client total control over response shape.
What is the typical network architecture for a standard GraphQL server?
Q3: What is the GraphQL Schema and SDL?
The GraphQL Schema defines the hierarchy of types, fields, inputs, and operations available on the server. Schema Definition Language (SDL) is the standard human-readable syntax used to write GraphQL schemas.
type User {
id: ID!
name: String!
email: String
}
The Schema acts as a strongly-typed contract between frontend and backend.
SDL is the language-agnostic syntax used to declare GraphQL types.
What does the exclamation mark ! indicate in SDL (e.g., id: ID!)?
Q4: What are the three root operation types in GraphQL?
GraphQL supports three primary root operations:
- Query: Read-only fetches (analogous to HTTP GET).
- Mutation: Write operations that create, update, or delete data (analogous to POST/PUT/DELETE).
- Subscription: Event-driven real-time updates maintained over long-lived transport (e.g., WebSockets).
Queries are read-only, Mutations perform writes, and Subscriptions stream real-time events.
Which root operation should be used to modify data in a database?
Q5: What are the built-in scalar types in GraphQL?
GraphQL includes five built-in primitive scalar types:
Int: Signed 32‐bit integer.Float: Signed double-precision fractional value.String: UTF‐8 character sequence.Boolean:trueorfalse.ID: Unique identifier serialized as a String, often used to re-fetch objects.
GraphQL provides 5 scalar primitives: Int, Float, String, Boolean, and ID.
Which of the following is NOT a built-in GraphQL scalar type?
Q6: What is a GraphQL Resolver?
A resolver is a function that populates the data for a specific field in a GraphQL schema. Every field on every type in GraphQL is backed by a resolver function on the server.
const resolvers = {
Query: {
user: (parent, args, context, info) => {
return context.db.findUserById(args.id);
}
}
};Resolvers receive four positional arguments: parent, args, context, and info.
Resolvers bridge schema fields to actual data sources (DBs, REST APIs, microservices).
What role does a resolver fulfill in a GraphQL server?
Q7: What are the four standard arguments passed to a GraphQL resolver?
Standard GraphQL resolvers in JavaScript environments receive four positional arguments:
parent(orobj): The result returned from the resolver on the parent field.args: The parameters/arguments passed into the field in the GraphQL query.context: Shared contextual state across all resolvers in a request (e.g., auth user, DB instances).info: AST and execution information regarding the query state.
Resolver arguments are
(parent, args, context, info).contextis the primary mechanism for sharing request-scoped objects like database connections.
Which resolver argument contains the current authenticated user object?
Q8: What are GraphQL Fragments and why are they used?
A fragment is a reusable unit of a GraphQL query. It allows developers to construct sets of fields and include them in multiple queries, preventing code duplication.
fragment UserFields on User {
id
name
email
}
query GetUser {
user(id: "1") {
...UserFields
}
}The fragment UserFields is reused using the spread syntax (...UserFields).
Fragments eliminate duplicate field selections across queries.
They are vital for UI components that define their own data dependencies.
Which operator is used to apply a fragment inside a query?
Q9: What are GraphQL Aliases and when should you use them?
Aliases allow you to rename the result of a field in a query. They are essential when you need to query the exact same schema field multiple times with different arguments in a single request.
query GetTwoUsers {
admin: user(id: "1") {
name
}
guest: user(id: "2") {
name
}
}The aliases admin and guest differentiate the two user field calls in the JSON response.
Aliases prevent JSON property collision when querying a field multiple times in one operation.
Why are aliases mandatory when calling the same field twice with different arguments in one query?
Q10: Why should you use variables instead of inline string interpolation in queries?
GraphQL variables allow query values to be dynamic without constructing queries via string manipulation.
Benefits:
- Security: Prevents query injection attacks.
- Caching: Allows GraphQL servers/clients to compile and cache static query document structures.
- Readability: Keeps document text clean and re-executable.
Variables separate query structure from parameter values.
Using variables prevents query injection and enables client/server execution caching.
How are variable names prefixed in standard GraphQL query documents?
Q11: How do Enum types work in GraphQL?
Enumerations (Enums) are special scalar types restricted to a predefined set of allowed values. Enums ensure type safety when a argument or field must only take one of a small set of possible values.
enum Role {
ADMIN
USER
GUEST
}
type User {
id: ID!
role: Role!
}The field role is guaranteed to return only one of the declared Enum values.
Enums validate field parameters against explicit allowed constant string choices.
Are Enum values in GraphQL SDL quotes-enclosed strings?
Q12: What is an Input Object type and how does it differ from an Object type?
input object types define complex object structures passed as arguments into queries or mutations.
Differences:
- Object Types (
type): Define output structures fetched from the server. They can contain fields with arguments. - Input Types (
input): Define input structures sent to the server. Fields cannot accept arguments or contain output object types.
inputtypes define structured arguments passed to operations.inputfields cannot have arguments or reference standard outputtypeentities.
Can an input type field contain field arguments?
Q13: Why are fields in GraphQL nullable by default?
Fields in GraphQL are nullable by default to handle distributed system errors gracefully. If a database query fails or a microservice is down, a single nullable field can evaluate to null while returning partial data for all valid fields without crashing the entire query.
If a non-nullable (!) field returns null due to an error, that null value 'bubbles up' to the nearest parent nullable field.
Default nullability facilitates partial data responses during partial service outages.
What happens if a non-nullable field returns null due to a runtime error?
Q14: What is GraphQL Introspection?
Introspection is the ability of a GraphQL server to expose its own schema details to clients through special top-level fields like __schema and __type. IDEs (GraphiQL, GraphQL Playground) use introspection to auto-generate docs and autocomplete queries.
Introspection allows tools to inspect schema documentation and types.
Introspection is typically disabled in production environments for security.
Which prefix identifies built-in GraphQL introspection fields?
Q15: What are `@include` and `@skip` directives?
Directives modify query execution based on runtime conditions:
@include(if: Boolean): Includes a field/fragment only if the argument evaluates totrue.@skip(if: Boolean): Skips a field/fragment if the argument evaluates totrue.
query GetUser($withDetails: Boolean!) {
user(id: "1") {
name
email @include(if: $withDetails)
}
}The email field is only fetched if $withDetails is true.
@includeand@skipallow dynamic query shape changes using client variables.
What happens when @skip(if: true) is placed on a field?
Q16: How do Interfaces work in GraphQL SDL?
An interface is an abstract type that defines a set of fields that any implementers must include. Object types can implement one or multiple interfaces.
interface Character {
id: ID!
name: String!
}
type Hero implements Character {
id: ID!
name: String!
superpower: String!
}Type Hero implements Character and must declare id and name fields.
Interfaces establish abstract guarantees across diverse GraphQL types.
Must an object type implement every field defined in its interface?
Q17: What are GraphQL Union types and how do they differ from Interfaces?
A union type represents a object choice across multiple concrete types, but members do not need to share common fields (unlike an interface).
union SearchResult = User | Post | Comment
query Search {
search(text: "graphql") {
... on User {
name
}
... on Post {
title
}
}
}Inline fragments (... on Type) query specific fields from union options.
Unions group distinct types without enforcing common fields.
Inline fragments must be used to select fields from union options.
How do clients query distinct fields on a Union return type?
Q18: What is the `__typename` field used for?
__typename is a reserved introspection field accessible on any GraphQL type. It returns a string containing the exact runtime object type name. It is heavily utilized by client libraries (like Apollo Client and Relay) for cache normalization and type identification on unions and interfaces.
__typenamereveals the concrete type of an object at runtime.Normalizing client caches requires
__typenamealongside unique identifiers.
Which system component relies heavily on __typename for normalizing cache objects?
Q19: What is the N+1 problem in GraphQL?
The N+1 problem occurs when a query fetches a list of $N$ items, and for each item, an independent database call is executed to fetch a related field. This results in 1 initial query plus $N$ sub-queries ($1 + N$), crippling server performance.
Naïve resolver execution results in $1+N$ database queries for nested lists.
It is the primary performance challenge in backend GraphQL implementations.
If a query fetches 50 authors and their books, how many total DB queries occur in a naïve N+1 scenario?
Q20: How does DataLoader solve the N+1 problem?
DataLoader (created by Facebook) solves N+1 through batching and caching during execution.
It defers individual load requests occurring within a single event loop tick, combines those IDs into a single batch array, and executes one consolidated batch query (e.g., WHERE id IN (...)).
DataLoader batches concurrent resolver requests in the same event loop frame.
It replaces $N$ individual queries with a single batch
INquery.
DataLoader aggregates individual resource keys across which processing window?
Q21: How do you implement a Custom Scalar in GraphQL?
When built-in primitives are insufficient, custom scalars (e.g., Date, JSON, URL) can be defined in SDL and provided custom logic for:
serialize: Converts back-end output to JSON.parseValue: Parses variables sent in JSON requests.parseLiteral: Parses inline AST literal values inside queries.
Custom scalars validate and transform specialized datatypes at the framework boundary.
Which custom scalar method parses inline literal values written directly inside a query string?
Q22: What are custom Schema Directives and what are common use-cases?
Custom directives (prefixed with @) attach custom behavior or metadata to schema locations (fields, objects, arguments).
Common use-cases:
- Authentication/Authorization (
@auth(role: ADMIN)) - Input formatting (
@upperCase,@trim) - Deprecation markings or rate-limiting metadata
Directives add declarative, reusable middleware logic directly to schema declarations.
Where can custom directives be attached in GraphQL?
Q23: How does error handling work in GraphQL responses?
Unlike REST (which uses HTTP status codes like 404 or 500), GraphQL usually returns 200 OK with a payload containing a top-level errors array alongside partial data results.
{
"data": { "user": null },
"errors": [
{
"message": "User not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["user"],
"extensions": { "code": "NOT_FOUND" }
}
]
}The payload contains a path map, error classification, and exact location markers.
GraphQL responses can simultaneously yield partial
dataand executionerrors.Standard error objects include
message,locations,path, andextensions.
What is the conventional top-level key for metadata in a standard GraphQL error object?
Q25: What are offset-based vs. cursor-based pagination in GraphQL?
- Offset-based: Uses
limitandoffset. Simple to write, but susceptible to missed/duplicate items when records are inserted or deleted during paging. - Cursor-based: Uses opaque pointers (cursors) pointing to specific items. Highly consistent, performs better on massive datasets, and is formalized by the Relay Cursor Connections Specification.
Cursor pagination avoids pagination drift during real-time data mutations.
Relay Connection pattern is the industry standard for cursor pagination in GraphQL.
Why is cursor pagination preferred over offset pagination for real-time feeds?
Q26: What is the Relay Cursor Connections Specification?
A standardized schema structure for paginating lists using cursors. It wraps list responses in edges and pageInfo metadata types.
Key components:
edges: List containing node data and its uniquecursorstring.pageInfo: Flags (hasNextPage,hasPreviousPage) and boundary cursors (startCursor,endCursor).
Relay specification structures paginated queries into
edges,node, andpageInfocomponents.
In the Relay Connection spec, which field on pageInfo tells the client if another page exists?
Q27: How does HTTP Caching differ between REST and GraphQL?
REST leverages native HTTP caching primitives (like Cache-Control, ETag, 304 status codes) via resource URIs and GET requests.
GraphQL uses POST requests to a single /graphql URL, rendering standard HTTP URL caching ineffective. Instead, GraphQL caching relies on:
- Client-side Normalized Caching (by
__typename+idinside Apollo/Relay). - Persisted Queries / Automated Persisted Queries (APQ) to allow HTTP GET caching.
GraphQL POST operations bypass default CDN/HTTP path caching.
Client caches normalize graphs into key-value stores using unique object IDs.
What primary feature prevents standard HTTP CDNs from caching default GraphQL queries?
Q28: How do GraphQL Subscriptions work under the hood?
Subscriptions use long-lived stateful connections (typically WebSockets via graphql-ws protocol). The client sends a subscription query once, and the server pushes incremental GraphQL response payloads whenever backend event publishers (e.g., Redis Pub/Sub, Kafka) emit relevant events.
Subscriptions establish bidirectional WebSocket streams for event-driven updates.
Which transport protocol is most commonly used to implement GraphQL Subscriptions?
Q29: What is Query Batching vs Query Deduplication on client side?
- Query Batching: Combines multiple independent GraphQL requests triggered around the same time into a single HTTP POST request array.
- Query Deduplication: Automatically detects duplicate identical queries sent concurrently and executes only a single network request, sharing the promise response.
Batching reduces network overhead; Deduplication eliminates redundant concurrent operations.
What does client query deduplication accomplish?
Q30: How does Normalized Caching work in Apollo Client?
Apollo Client flattens nested GraphQL query responses into a flat key-value dictionary. By default, it generates a unique key for every object using its __typename and id (or _id) field (e.g., User:123). If multiple queries return data for User:123, the cache updates the single source of truth.
Normalized caching flattens hierarchical query results into a unified global lookup store.
What primary identifier combination does Apollo Client use by default for cache normalization?