50 Topics
Chapter•120 Minutes

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?

Difficulty:EasyTopic:Basics

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

Creator

Facebook (Meta)

Initial Release

2015

Key Takeaways
  • GraphQL allows clients to request exactly what data they need.

  • It eliminates over-fetching and under-fetching using a single endpoint.

Knowledge Check

Which issue is directly eliminated by GraphQL allowing field-level selection?

Q2: How does GraphQL differ from a traditional REST API?

Difficulty:EasyTopic:Architecture

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

Endpoints

Multiple resource URIs

REST requires multiple network calls for relational data.

GraphQL Endpoints

Single endpoint

GraphQL executes complex declarative queries at one endpoint.

Data Fetching

Server defines payload

REST payload structure is static.

GraphQL Data Fetching

Client defines payload

GraphQL response reflects requested schema fields.

Key Takeaways
  • REST relies on multiple resource endpoints, while GraphQL operates over a single endpoint.

  • GraphQL gives the client total control over response shape.

Knowledge Check

What is the typical network architecture for a standard GraphQL server?

Q3: What is the GraphQL Schema and SDL?

Difficulty:EasyTopic:Schema

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
}
Key Takeaways
  • The Schema acts as a strongly-typed contract between frontend and backend.

  • SDL is the language-agnostic syntax used to declare GraphQL types.

Knowledge Check

What does the exclamation mark ! indicate in SDL (e.g., id: ID!)?

Q4: What are the three root operation types in GraphQL?

Difficulty:EasyTopic:Operations

GraphQL supports three primary root operations:

  1. Query: Read-only fetches (analogous to HTTP GET).
  2. Mutation: Write operations that create, update, or delete data (analogous to POST/PUT/DELETE).
  3. Subscription: Event-driven real-time updates maintained over long-lived transport (e.g., WebSockets).
Key Takeaways
  • Queries are read-only, Mutations perform writes, and Subscriptions stream real-time events.

Knowledge Check

Which root operation should be used to modify data in a database?

Q5: What are the built-in scalar types in GraphQL?

Difficulty:EasyTopic:Types

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: true or false.
  • ID: Unique identifier serialized as a String, often used to re-fetch objects.
Key Takeaways
  • GraphQL provides 5 scalar primitives: Int, Float, String, Boolean, and ID.

Knowledge Check

Which of the following is NOT a built-in GraphQL scalar type?

Q6: What is a GraphQL Resolver?

Difficulty:EasyTopic:Execution

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.

Basic JavaScript Resolver
const resolvers = {
  Query: {
    user: (parent, args, context, info) => {
      return context.db.findUserById(args.id);
    }
  }
};

Resolvers receive four positional arguments: parent, args, context, and info.

Key Takeaways
  • Resolvers bridge schema fields to actual data sources (DBs, REST APIs, microservices).

Knowledge Check

What role does a resolver fulfill in a GraphQL server?

Q7: What are the four standard arguments passed to a GraphQL resolver?

Difficulty:EasyTopic:Execution

Standard GraphQL resolvers in JavaScript environments receive four positional arguments:

  1. parent (or obj): The result returned from the resolver on the parent field.
  2. args: The parameters/arguments passed into the field in the GraphQL query.
  3. context: Shared contextual state across all resolvers in a request (e.g., auth user, DB instances).
  4. info: AST and execution information regarding the query state.
Key Takeaways
  • Resolver arguments are (parent, args, context, info).

  • context is the primary mechanism for sharing request-scoped objects like database connections.

Knowledge Check

Which resolver argument contains the current authenticated user object?

Q8: What are GraphQL Fragments and why are they used?

Difficulty:EasyTopic:Query Constructs

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.

GraphQL Fragment Example
fragment UserFields on User {
  id
  name
  email
}

query GetUser {
  user(id: "1") {
    ...UserFields
  }
}

The fragment UserFields is reused using the spread syntax (...UserFields).

Key Takeaways
  • Fragments eliminate duplicate field selections across queries.

  • They are vital for UI components that define their own data dependencies.

Knowledge Check

Which operator is used to apply a fragment inside a query?

Q9: What are GraphQL Aliases and when should you use them?

Difficulty:EasyTopic:Query Constructs

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.

Querying with Aliases
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.

Key Takeaways
  • Aliases prevent JSON property collision when querying a field multiple times in one operation.

Knowledge Check

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?

Difficulty:EasyTopic:Security & Syntax

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.
Key Takeaways
  • Variables separate query structure from parameter values.

  • Using variables prevents query injection and enables client/server execution caching.

Knowledge Check

How are variable names prefixed in standard GraphQL query documents?

Q11: How do Enum types work in GraphQL?

Difficulty:EasyTopic:Types

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 SDL Definition
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.

Key Takeaways
  • Enums validate field parameters against explicit allowed constant string choices.

Knowledge Check

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?

Difficulty:EasyTopic:Schema

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.
Key Takeaways
  • input types define structured arguments passed to operations.

  • input fields cannot have arguments or reference standard output type entities.

Knowledge Check

Can an input type field contain field arguments?

Q13: Why are fields in GraphQL nullable by default?

Difficulty:EasyTopic:Error Handling

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.

Null Bubbling

If a non-nullable (!) field returns null due to an error, that null value 'bubbles up' to the nearest parent nullable field.

Key Takeaways
  • Default nullability facilitates partial data responses during partial service outages.

Knowledge Check

What happens if a non-nullable field returns null due to a runtime error?

Q14: What is GraphQL Introspection?

Difficulty:EasyTopic:Tooling

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.

Key Takeaways
  • Introspection allows tools to inspect schema documentation and types.

  • Introspection is typically disabled in production environments for security.

Knowledge Check

Which prefix identifies built-in GraphQL introspection fields?

Q15: What are `@include` and `@skip` directives?

Difficulty:EasyTopic:Directives

Directives modify query execution based on runtime conditions:

  • @include(if: Boolean): Includes a field/fragment only if the argument evaluates to true.
  • @skip(if: Boolean): Skips a field/fragment if the argument evaluates to true.
Using Directive in Query
query GetUser($withDetails: Boolean!) {
  user(id: "1") {
    name
    email @include(if: $withDetails)
  }
}

The email field is only fetched if $withDetails is true.

Key Takeaways
  • @include and @skip allow dynamic query shape changes using client variables.

Knowledge Check

What happens when @skip(if: true) is placed on a field?

Q16: How do Interfaces work in GraphQL SDL?

Difficulty:IntermediateTopic:Schema Design

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.

GraphQL Interface Syntax
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.

Key Takeaways
  • Interfaces establish abstract guarantees across diverse GraphQL types.

Knowledge Check

Must an object type implement every field defined in its interface?

Q17: What are GraphQL Union types and how do they differ from Interfaces?

Difficulty:IntermediateTopic:Schema Design

A union type represents a object choice across multiple concrete types, but members do not need to share common fields (unlike an interface).

Union Definition and Querying
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.

Key Takeaways
  • Unions group distinct types without enforcing common fields.

  • Inline fragments must be used to select fields from union options.

Knowledge Check

How do clients query distinct fields on a Union return type?

Q18: What is the `__typename` field used for?

Difficulty:IntermediateTopic:Caching & Tooling

__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.

Key Takeaways
  • __typename reveals the concrete type of an object at runtime.

  • Normalizing client caches requires __typename alongside unique identifiers.

Knowledge Check

Which system component relies heavily on __typename for normalizing cache objects?

Q19: What is the N+1 problem in GraphQL?

Difficulty:IntermediateTopic:Performance

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.

N+1 Execution Flaw
Key Takeaways
  • Naïve resolver execution results in $1+N$ database queries for nested lists.

  • It is the primary performance challenge in backend GraphQL implementations.

Knowledge Check

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?

Difficulty:IntermediateTopic:Performance

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 (...)).

Key Takeaways
  • DataLoader batches concurrent resolver requests in the same event loop frame.

  • It replaces $N$ individual queries with a single batch IN query.

Knowledge Check

DataLoader aggregates individual resource keys across which processing window?

Q21: How do you implement a Custom Scalar in GraphQL?

Difficulty:IntermediateTopic:Schema Extension

When built-in primitives are insufficient, custom scalars (e.g., Date, JSON, URL) can be defined in SDL and provided custom logic for:

  1. serialize: Converts back-end output to JSON.
  2. parseValue: Parses variables sent in JSON requests.
  3. parseLiteral: Parses inline AST literal values inside queries.
Key Takeaways
  • Custom scalars validate and transform specialized datatypes at the framework boundary.

Knowledge Check

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?

Difficulty:IntermediateTopic:Directives

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
Key Takeaways
  • Directives add declarative, reusable middleware logic directly to schema declarations.

Knowledge Check

Where can custom directives be attached in GraphQL?

Q23: How does error handling work in GraphQL responses?

Difficulty:IntermediateTopic:Error Handling

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.

Standard GraphQL Error Format
{
  "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.

Key Takeaways
  • GraphQL responses can simultaneously yield partial data and execution errors.

  • Standard error objects include message, locations, path, and extensions.

Knowledge Check

What is the conventional top-level key for metadata in a standard GraphQL error object?

Q24: Where should Authentication and Authorization be handled in GraphQL?

Difficulty:IntermediateTopic:Security
  • Authentication (who you are): Should occur in HTTP middleware before the GraphQL engine receives the request. The validated user context is then attached to the resolver context.
  • Authorization (what you can do): Should ideally be enforced in the business/domain logic layer rather than inside individual GraphQL resolver functions to keep code maintainable and dry.
Key Takeaways
  • Authenticate at the HTTP layer, attach credentials to context.

  • Enforce granular domain authorization within data service models.

Knowledge Check

Where is the recommended architectural location to place core business authorization rules?

Q25: What are offset-based vs. cursor-based pagination in GraphQL?

Difficulty:IntermediateTopic:API Design
  • Offset-based: Uses limit and offset. 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.
Key Takeaways
  • Cursor pagination avoids pagination drift during real-time data mutations.

  • Relay Connection pattern is the industry standard for cursor pagination in GraphQL.

Knowledge Check

Why is cursor pagination preferred over offset pagination for real-time feeds?

Q26: What is the Relay Cursor Connections Specification?

Difficulty:IntermediateTopic:API Design

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 unique cursor string.
  • pageInfo: Flags (hasNextPage, hasPreviousPage) and boundary cursors (startCursor, endCursor).
Key Takeaways
  • Relay specification structures paginated queries into edges, node, and pageInfo components.

Knowledge Check

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?

Difficulty:IntermediateTopic:Caching

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:

  1. Client-side Normalized Caching (by __typename + id inside Apollo/Relay).
  2. Persisted Queries / Automated Persisted Queries (APQ) to allow HTTP GET caching.
Key Takeaways
  • GraphQL POST operations bypass default CDN/HTTP path caching.

  • Client caches normalize graphs into key-value stores using unique object IDs.

Knowledge Check

What primary feature prevents standard HTTP CDNs from caching default GraphQL queries?

Q28: How do GraphQL Subscriptions work under the hood?

Difficulty:IntermediateTopic:Real-time

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.

Key Takeaways
  • Subscriptions establish bidirectional WebSocket streams for event-driven updates.

Knowledge Check

Which transport protocol is most commonly used to implement GraphQL Subscriptions?

Q29: What is Query Batching vs Query Deduplication on client side?

Difficulty:IntermediateTopic:Client Optimizations
  • 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.
Key Takeaways
  • Batching reduces network overhead; Deduplication eliminates redundant concurrent operations.

Knowledge Check

What does client query deduplication accomplish?

Q30: How does Normalized Caching work in Apollo Client?

Difficulty:IntermediateTopic:State Management

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.

Key Takeaways
  • Normalized caching flattens hierarchical query results into a unified global lookup store.

Knowledge Check

What primary identifier combination does Apollo Client use by default for cache normalization?