Skip to main content

GraphQL Interview Questions & Answers

A comprehensive guide for backend developers learning GraphQL


Table of Contents​

  1. Basic Level
  2. Intermediate Level
  3. Advanced Level
  4. Real-World Scenarios
  5. Quick Reference

1. Basic Level​

Introduction to GraphQL​

Q1: What is GraphQL and why was it created?​

Answer: GraphQL is a query language for APIs and a runtime for executing those queries against your data. It was developed by Facebook in 2012 and released publicly in 2015. It was created to solve specific problems with traditional REST APIs.

Problems GraphQL Solves:

  1. Over-fetching: REST endpoints often return more data than needed

    • Example: A /users/123 endpoint might return all user fields when you only need the name and email
    • GraphQL lets you request exactly: { user(id: "123") { name email } }
  2. Under-fetching: Getting related data requires multiple API calls

    • Example: To get a user with their posts, you might need:
      • Call 1: GET /users/123 (get user data)
      • Call 2: GET /users/123/posts (get user's posts)
    • GraphQL gets it in one request: { user(id: "123") { name posts { title } } }
  3. Tight coupling: Clients are dependent on server-defined endpoints

    • With REST: If the API changes from /users to /people, all clients must update
    • With GraphQL: Clients specify exactly what they need, so API evolution doesn't break existing clients as long as requested fields still exist

How GraphQL Works:

  • Single endpoint: All requests go to one URL (typically /graphql)
  • Client-defined responses: The client specifies exactly what data structure it wants
  • Strongly typed schema: The API defines what data is available through a schema

Q2: What are the main differences between REST and GraphQL?​

Answer: While both are architectural styles for building APIs, they differ fundamentally in how data is requested and delivered.

AspectRESTGraphQL
PhilosophyResource-based (everything is a URL)Graph-based (everything is connected)
EndpointsMultiple (e.g., /users, /posts, /comments)Single (usually /graphql)
Data FetchingServer decides structure (Fixed)Client decides structure (Flexible)
Over/Under-fetchingCommon problemsSolved by design
VersioningOften uses /v1/, /v2/Versionless (evolution through deprecation)
Error HandlingHTTP Status codes (404, 500, etc.)Always 200 OK (errors in response body)
CachingBuilt-in HTTP caching (ETags, Max-Age)Custom caching (usually at client/field level)

Summary: REST is great for simple, stable APIs with standardized caching. GraphQL is superior for complex, evolving applications with varying data needs across different clients (mobile vs. web).

Q3: What is a GraphQL Schema?​

Answer: The schema is the "contract" between the client and the server. It defines the entire data model of the API, including the types, fields, and relationships available for querying. It is written in Schema Definition Language (SDL).

Key Components of a Schema:

  1. Object Types: Representations of your domain objects (User, Post).
  2. Fields: Specific attributes of an object.
  3. Scalars: Basic data types (String, Int, Float, Boolean, ID).
  4. Root Types: Special types that define entry points (Query, Mutation, Subscription).

Example Schema:

# 1. Custom Object Type
type User {
id: ID! # '!' means non-nullable
username: String!
email: String
posts: [Post!]! # A list of non-nullable Posts
}

type Post {
id: ID!
title: String!
author: User!
}

# 2. Entry Point for Reading
type Query {
user(id: ID!): User
allUsers: [User!]!
}

# 3. Entry Point for Writing
type Mutation {
createPost(title: String!, authorId: ID!): Post!
}

Q4: What are the different GraphQL operation types?​

Answer: GraphQL defines three primary operation types, each serving a different purpose:

  1. Query (Read):

    • Used to fetch data from the server.
    • Analogue to GET in REST.
    • Operations are executed in parallel by the server.
    query GetUserData {
    user(id: "1") {
    name
    }
    }
  2. Mutation (Write):

    • Used to create, update, or delete data.
    • Analogue to POST, PUT, PATCH, DELETE in REST.
    • Operations are executed sequentially to ensure data integrity.
    mutation AddNewUser {
    createUser(name: "Alice") {
    id
    }
    }
  3. Subscription (Real-time):

    • Used to establish a persistent connection (usually via WebSockets).
    • The server pushes data to the client whenever a specific event occurs.
    subscription OnCommentAdded {
    commentAdded(postId: "123") {
    text
    author
    }
    }

Q5: What are GraphQL Types?​

Answer: Types are the core building blocks of a GraphQL schema. They define the shape of your data and the possible operations.

  1. Scalar Types (Primitives):

    • String: UTF-8 character sequence.
    • Int: Signed 32-bit integer.
    • Float: Signed double-precision floating-point.
    • Boolean: true or false.
    • ID: Unique identifier (serialized as String).
  2. Object Types: Custom types with fields (e.g., User, Post).

  3. Enum Types: A restricted set of allowed values.

    enum Status {
    ACTIVE
    INACTIVE
    BANNED
    }
  4. Interface Types: Abstract types that define a set of fields that multiple object types must include.

    interface Character {
    id: ID!
    name: String!
    }
    type Human implements Character {
    id: ID!
    name: String!
    planet: String
    }
  5. Union Types: A type that can represent one of several object types (no shared fields required).

    union SearchResult = User | Post

Q6: What is a GraphQL Resolver?​

Answer: A resolver is a function on the server that "resolves" or fetches the data for a specific field in a query. Every field in your schema corresponds to a resolver function.

Resolver Signature (Arguments):

  • parent: The result returned from the resolver of the parent field.
  • args: The arguments provided to the field in the GraphQL query.
  • context: A shared object accessible by all resolvers (e.g., database connection, user auth).
  • info: Technical information about the execution state (AST).

Example (JavaScript):

const resolvers = {
Query: {
user: (parent, args, context, info) => {
// Fetch user from DB using the 'id' provided in 'args'
return context.db.users.findById(args.id);
},
},
User: {
posts: (parent, args, context) => {
// 'parent' here is the User object resolved above
return context.db.posts.findByUserId(parent.id);
},
},
};

Q7: What is the N+1 problem in GraphQL?​

Answer: The N+1 problem occurs when fetching a list of items where each item has a field that requires an additional database query.

Example Scenario:

  1. A query asks for 100 users and their posts.
  2. The server runs 1 query to get the list of 100 users.
  3. For each of those 100 users, the posts resolver is called independently.
  4. Total queries = 1 (to get users) + 100 (to get posts for each user) = 101 queries.

Solution: DataLoader DataLoader is a utility that batches and caches requests. Instead of 100 individual queries, it collects all IDs requested in one "tick" of the event loop and runs a single "Batch" query: SELECT * FROM posts WHERE user_id IN (1, 2, 3, ... 100);

Q8: How do you handle Errors in GraphQL?​

Answer: In GraphQL, errors do not cause the whole request to fail (unless it's a syntax error). The server returns an object containing both a data key (for successful fields) and an errors key (for failed fields).

Key Features:

  • Partial Success: If fetching a user's name succeeds but posts fails, you still get the name.
  • Error Object: Contains a message, locations, and an extensions field for custom metadata (like error codes or stack traces).

Example Response:

{
"data": { "user": { "name": "Krisp" } },
"errors": [
{
"message": "Database timeout",
"path": ["user", "posts"],
"extensions": { "code": "TIMEOUT" }
}
]
}

Q9: What are GraphQL Subscriptions?​

Answer: Subscriptions enable real-time functionality by maintaining a persistent connection. When an event occurs on the server, the client receives the updated data.

subscription OnNewMessage {
newMessage(roomId: "1") {
id
content
sender {
name
}
}
}

Q10: What are GraphQL Arguments?​

Answer: Arguments are values passed to fields to specify the data you want. They can be required or optional with default values.

query GetUser {
user(id: "1") {
name
posts(limit: 5, offset: 0) {
title
}
}
}

2. Intermediate Level​

Advanced GraphQL Concepts​

Q11: What is the N+1 problem in GraphQL?​

Answer: The N+1 problem occurs when fetching a list of items where each item requires additional database queries. This happens because each field resolver runs independently.

Problem example: 1 query for users + N queries for posts (one per user) = N+1 queries.

Solutions include DataLoader which batches and caches requests, and proper resolver design to fetch data efficiently.

Q12: How do you handle pagination in GraphQL?​

Answer: There are two main patterns for pagination in GraphQL.

  1. Offset-based Pagination (Limit/Offset):

    • Simple to implement.
    • Problem: If a new item is added to the database while the user is paginating, they might see the same item twice on different pages.
    • users(limit: 10, offset: 20)
  2. Cursor-based Pagination (Recommended):

    • Uses a "cursor" (a pointer to a specific record) instead of an offset.
    • More complex but highly performant for large datasets and stable against concurrent writes.
    • Usually follows the Relay Connection Specification.

Example (Relay style):

query {
posts(first: 10, after: "YXJyYXljb25uZWN0aW9uOjI=") {
edges {
node {
id
title
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}

Q13: How do you implement Authentication and Authorization?​

Answer:

  • Authentication (Who are you?): Usually handled outside of GraphQL (e.g., via a middleware). The middleware verifies a JWT or Session and attaches the user object to the Context.
  • Authorization (What can you do?): Handled inside the resolvers or via Directives.

Example (Authorization in Resolver):

const resolvers = {
Mutation: {
deletePost: (parent, args, context) => {
if (!context.user) throw new Error("Unauthenticated");
if (context.user.role !== "ADMIN") throw new Error("Forbidden");
return db.posts.delete(args.id);
},
},
};

Q14: How do you handle authorization in GraphQL?​

Answer: Authorization determines what data a user can access. Implement it at the resolver level by checking user permissions before returning data, or use GraphQL Shield for declarative authorization.

const resolvers = {
Post: {
content: (parent, args, context) => {
if (context.user.id === parent.authorId) {
return parent.content;
}
return parent.content.substring(0, 100);
},
},
};

Q15: What are GraphQL Interfaces and Unions?​

Answer: Both are abstract types but work differently. Interfaces define a set of fields that implementing types must have. Unions are types that could be any of several types without shared fields.

interface Person {
id: ID!
name: String!
}

type User implements Person {
id: ID!
name: String!
role: String!
}

union SearchResult = User | Post | Comment

Q16: How do you handle errors in GraphQL?​

Answer: GraphQL has a structured error format. Use HTTPException for top-level errors, custom error handling with extensions for detailed error information, and formatError for consistent error responses.

const formatError = (error) => {
return {
message: error.message,
extensions: {
code: error.originalError?.code || "INTERNAL_ERROR",
},
};
};

Q17: What is GraphQL Caching?​

Answer: Caching in GraphQL is more complex than REST because responses are custom-shaped. Use normalized cache with Apollo Client, Server-side caching with Redis, and Persisted Queries for production.

Q18: What are GraphQL Variables?​

Answer: Variables allow parameterizing queries instead of hardcoding values.

query GetUser($userId: ID!) {
user(id: $userId) {
name
email
}
}

Variables: { "userId": "1" }

Q19: What is GraphQL Schema Stitching?​

Answer: Schema stitching combines multiple GraphQL schemas into one unified schema. Use @graphql-tools/schema mergeSchemas or Apollo Gateway for federation.

Q20: How do you implement rate limiting in GraphQL?​

Answer: Rate limiting protects your API from abuse. Implement using GraphQL Rate Limit library or custom middleware that tracks requests per user/IP.

const { rateLimitDirective } = rateLimit({
identifyContext: (context) => context.ip,
limits: { generalQuery: { limit: 100, window: "1m" } },
});

3. Advanced Level​

Enterprise GraphQL​

Q21: What is Apollo Federation?​

Answer: Apollo Federation is an architecture for building a unified GraphQL schema across multiple services. Define entities with @key directive, implement services independently, and compose with Apollo Gateway.

extend type User @key(fields: "id") {
id: ID! @external
posts: [Post!]!
}

Q22: How do you optimize GraphQL performance?​

Answer: Optimize with query complexity analysis to prevent expensive queries, response caching, persisted queries to reduce payload size, and DataLoader for batching.

const { createComplexityRule } = require("graphql-complexity");
const complexityRule = createComplexityRule({ maximumComplexity: 1000 });

Q23: What are GraphQL Subscriptions implementation patterns?​

Answer: Use Redis Pub/Sub for distributed subscriptions, WebSockets with authentication, and filter subscriptions on the server side for efficiency.

Q24: How do you handle file uploads in GraphQL?​

Answer: Use GraphQL Multipart Request Specification with GraphQL Upload scalar. Server implementation uses Apollo Server with graphql-upload.

type Mutation {
uploadFile(file: Upload!): File!
}

Q25: What are GraphQL Data Sources?​

Answer: Data Sources are a pattern for managing data fetching from external services. Use REST Data Source or database Data Source with built-in caching.

class UserAPI extends RESTDataSource {
baseURL = "https://api.example.com/";
async getUser(id) {
return this.get(`users/${id}`);
}
}

Q26: What is GraphQL Code Generation?​

Answer: Code generation creates type-safe code from your GraphQL schema. Use GraphQL Code Generator to generate TypeScript types, resolvers, and hooks.

Q27: How do you version a GraphQL API?​

Answer: GraphQL favors evolution over versioning. Use deprecation for backward compatibility, field-level versioning with new fields, and consider type evolution instead of breaking changes.

Q28: What is GraphQL Security Best Practices?​

Answer: Security best practices include input validation, query complexity limiting, preventing malicious queries, implementing rate limiting, using authentication/authorization, and securing the introspection endpoint in production.

Q29: What is GraphQL Tracing?​

Answer: Tracing helps identify performance bottlenecks. Use Apollo Tracing, OpenTelemetry integration, or custom tracing in resolvers.

Q30: How do you test GraphQL APIs?​

Answer: Test with unit tests for resolvers, integration tests for queries/mutations, and end-to-end tests with test fixtures. Use mocking for data sources. Test error cases, authorization, and query complexity limits.


2. Intermediate Level (Expanded)​

Q31: What are GraphQL Fragments and when should you use them?​

Answer: Fragments let you reuse sets of fields across queries. Useful for shared UI components that need the same fields. Reduces duplication and ensures consistency.

fragment UserFields on User {
id
name
email
}

query GetUser($id: ID!) {
user(id: $id) {
...UserFields
}
}

🔍 Behind the Question: Code reusability and query composition. ❌ The Red Flags: Not using fragments for repeated field sets.

Q32: How do you handle pagination in GraphQL?​

Answer: Two main approaches: (1) Offset-based: limit/offset or page/pageSize. Simple but inconsistent with real-time data. (2) Cursor-based: first/after with opaque cursors. Consistent and efficient for large datasets. Relay spec defines cursor-based pagination.

type Query {
posts(first: Int, after: String): PostConnection!
}

type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}

type PageInfo {
hasNextPage: Boolean!
endCursor: String
}

🔍 Behind the Question: Pagination strategies and performance. ❌ The Red Flags: Using OFFSET for infinite scroll.

Q33: What is GraphQL query complexity and how do you limit it?​

Answer: Query complexity assigns a cost to each field/type. Limit total complexity per request to prevent expensive queries. Example: scalar = 1, object = sum of children, list = items * child cost. Reject queries exceeding limit.

def calculate_complexity(ast):
# Recursively calculate field costs
return sum(field_complexity for field in ast.fields)

🔍 Behind the Question: DoS prevention and resource protection. ❌ The Red Flags: No complexity limits; server crashes on deep queries.

Q34: How do you implement authentication in GraphQL?​

Answer: Use context to pass user info from auth middleware to resolvers. Common patterns: (1) JWT in Authorization header, decoded in context. (2) Session cookies. (3) API keys. Check auth in directives or resolver decorators.

def get_context(request):
token = request.headers.get("Authorization")
user = verify_jwt(token)
return {"user": user}

🔍 Behind the Question: Auth patterns and context propagation. ❌ The Red Flags: Auth checks in every resolver manually.

Q35: How do you handle file uploads in GraphQL?​

Answer: Use the GraphQL multipart request spec. Define Upload scalar type. Client sends multipart/form-data with operations and map. Server maps files to variables. Apollo Server and Relay support this.

type Mutation {
uploadProfilePicture(file: Upload!): User!
}

🔍 Behind the Question: File handling and multipart requests. ❌ The Red Flags: Base64 encoding large files in JSON.

Q36: What are GraphQL Data Sources and when do you use them?​

Answer: Data sources abstract external data fetching (REST, databases, gRPC). Handle caching, batching, and error handling. Use when resolvers need to fetch from multiple backends or when you want to share logic across resolvers.

class UserDataSource:
def get_user(self, id):
return fetch_from_service(f"/users/{id}")

🔍 Behind the Question: Data fetching patterns and abstraction. ❌ The Red Flags: Direct DB calls in every resolver.

Q37: How do you implement rate limiting in GraphQL?​

Answer: Rate limit by: (1) Query complexity (expensive queries count more). (2) Per-user/IP limits. (3) Per-field limits. (4) Cost-based limiting. Use middleware or directives. Return 429 Too Many Requests with Retry-After.

@rate_limit(complexity=100, per_user=True)
def resolve_field(obj, info, **kwargs):
...

🔍 Behind the Question: Abuse prevention and fair usage. ❌ The Red Flags: No rate limiting; server DoS.

Q38: What is GraphQL Schema Stitching?​

Answer: Schema stitching combines multiple GraphQL schemas into one gateway schema. Clients query gateway; gateway routes to appropriate service. Useful for microservices with separate GraphQL APIs.

const gateway = new ApolloGateway({
supergraphSdl: new IntrospectionAndComposition({
subgraphEndpoints: [
{ name: 'users', url: 'http://users/graphql' },
{ name: 'posts', url: 'http://posts/graphql' },
],
}),
});

🔍 Behind the Question: Microservice GraphQL integration. ❌ The Red Flags: Single schema for all services; no federation.

Q39: How do you handle N+1 problems in GraphQL?​

Answer: Use DataLoader to batch and cache requests. DataLoader batches multiple object loads into one request. Resolvers return promises; DataLoader deduplicates and batches.

def resolve_posts(parent, info):
return dataloader.load(parent.id) # Batches all user post loads

🔍 Behind the Question: Performance optimization and batching. ❌ The Red Flags: One DB query per resolver call.

Q40: What is GraphQL persisted queries and when should you use them?​

Answer: Persisted queries store query hashes on the server. Client sends only hash instead of full query. Benefits: reduced bandwidth, query whitelisting, performance monitoring. Used by Shopify, GitHub.

# Client sends
{
"query": "queryhash123",
"variables": {}
}

🔍 Behind the Question: Performance and security. ❌ The Red Flags: No persisted queries for mobile clients.

Q41: How do you implement GraphQL subscriptions?​

Answer: Subscriptions use WebSocket for real-time updates. Client sends subscription query; server pushes events. Use graphql-ws or subscriptions-transport-ws. Server publishes events via Pub/Sub (Redis, Kafka).

subscription {
commentAdded(postId: "123") {
id
content
author {
name
}
}
}

🔍 Behind the Question: Real-time patterns and WebSocket integration. ❌ The Red Flags: Polling for real-time updates.

Q42: What is GraphQL schema-first vs code-first development?​

Answer: Schema-first: write SDL schema first, then implement resolvers. Code-first: define types in code, generate schema. Schema-first is more common (clear contract). Code-first is faster for prototyping.

🔍 Behind the Question: Development workflow and tooling. ❌ The Red Flags: No schema; resolvers define API implicitly.

Q43: How do you handle errors in GraphQL?​

Answer: Use GraphQLError for field-level errors. Return partial data with errors array. Use error codes for categorization. Never return HTTP 500 for expected errors. All responses return HTTP 200.

{
"data": { "user": null },
"errors": [
{
"message": "User not found",
"path": ["user"],
"extensions": { "code": "NOT_FOUND" }
}
]
}

🔍 Behind the Question: Error handling and API design. ❌ The Red Flags: HTTP 500 for business errors.

Q44: What is GraphQL directive and how do you use it?​

Answer: Directives modify schema execution. Built-in: @include, @skip. Custom: @auth, @rateLimit, @deprecated. Applied to fields/types. Executed by server during query execution.

type Query {
publicPosts: [Post] @auth(requires: PUBLIC)
privatePosts: [Post] @auth(requires: USER)
}

🔍 Behind the Question: Schema extensibility and cross-cutting concerns. ❌ The Red Flags: Hardcoding auth logic in resolvers.

Q45: How do you implement GraphQL caching?​

Answer: Client-side: Apollo Client caches by query ID. Server-side: use @cacheControl directive, CDN caching with Cache-Control headers, persisted queries. For REST integration, use RESTDataSource with caching.

🔍 Behind the Question: Caching strategies and performance. ❌ The Red Flags: No caching; every request hits backend.

Q46: What is GraphQL federation and when should you use it?​

Answer: Apollo Federation combines multiple GraphQL services into one gateway. Each service owns its types. Gateway resolves queries across services. Use when teams own different domains and need separate GraphQL APIs.

# Users service
extend type User @key(fields: "id") {
id: ID! @external
email: String
}

# Posts service
extend type User @key(fields: "id") {
id: ID! @external
posts: [Post!]!
}

🔍 Behind the Question: Microservice GraphQL integration. ❌ The Red Flags: Single schema for all services; no domain ownership.

Q47: How do you handle GraphQL subscriptions at scale?​

Answer: Use Redis Pub/Sub for multi-instance subscription broadcasting. Each server instance publishes to Redis; all instances broadcast to connected clients. Use connection pools and horizontal scaling.

🔍 Behind the Question: Real-time scaling and multi-instance broadcasting. ❌ The Red Flags: In-memory Pub/Sub; single instance.

Q48: What is GraphQL query whitelisting and when is it useful?​

Answer: Query whitelisting allows only pre-approved queries. Useful for security (prevent malicious queries), performance (guaranteed complexity), and analytics (track query usage). Store query hashes and validate before execution.

🔍 Behind the Question: Security and performance guarantees. ❌ The Red Flags: Executing arbitrary queries without limits.

Q49: How do you implement GraphQL rate limiting?​

Answer: Rate limit by: (1) Query complexity (expensive queries cost more). (2) Per-user/IP limits. (3) Time-based windows. Use directives or middleware. Return 429 with Retry-After.

class RateLimitDirective:
def visit_field(self, node, *args):
cost = calculate_cost(node)
if not rate_limiter.allow(user, cost):
raise GraphQLError("Rate limit exceeded")

🔍 Behind the Question: Abuse prevention and resource protection. ❌ The Red Flags: No rate limiting; server DoS.

Q50: How do you monitor GraphQL performance?​

Answer: Track: query latency, error rate, query complexity, resolver duration, N+1 count, cache hit rate. Use Apollo Studio, Datadog, or custom metrics. Alert on slow queries and high error rates.

🔍 Behind the Question: Observability and performance monitoring. ❌ The Red Flags: No metrics; blind to performance issues.

Q51: What is GraphQL schema evolution and how do you manage it?​

Answer: Add new fields/types without breaking existing queries. Deprecate fields with @deprecated directive. Remove fields only after grace period. Use CI to detect breaking changes (field removal, type change).

type User {
name: String!
email: String! @deprecated(reason: "Use emailAddress")
emailAddress: String!
}

🔍 Behind the Question: API lifecycle and backward compatibility. ❌ The Red Flags: Breaking changes without deprecation.

Q52: How do you implement GraphQL file uploads?​

Answer: Use the GraphQL multipart request spec. Define Upload scalar. Client sends multipart/form-data with operations and map. Server maps files to variables. Apollo Server supports this out of the box.

mutation UploadAvatar($file: Upload!) {
uploadAvatar(file: $file) {
id
url
}
}

🔍 Behind the Question: File handling and multipart requests. ❌ The Red Flags: Base64 encoding large files in JSON.

Q53: How do you test GraphQL resolvers?​

Answer: Unit test resolvers with mocked data sources. Integration test with test GraphQL client. Test queries, mutations, and error cases. Use graphql-core for testing without server.

def test_get_user():
result = graphql_sync(schema, "{ user(id: 1) { name } }", context_value={"user": mock_user})
assert result["data"]["user"]["name"] == "Alice"

🔍 Behind the Question: Testing strategies and resolver correctness. ❌ The Red Flags: No resolver tests; only integration tests.

Q54: How do you implement GraphQL query batching?​

Answer: Allow clients to send multiple operations in one request. Use @batch directive or automatic batching. Reduces HTTP overhead. Be careful with query complexity.

query Batch {
user1: user(id: 1) { name }
user2: user(id: 2) { name }
}

🔍 Behind the Question: Network efficiency and batching. ❌ The Red Flags: One HTTP request per query.

Q55: What is GraphQL persisted queries and when is it useful?​

Answer: Persisted queries store query hashes on server. Client sends only hash. Benefits: reduced bandwidth, query whitelisting, performance monitoring. Used by Shopify, GitHub.

🔍 Behind the Question: Performance and security. ❌ The Red Flags: No persisted queries for mobile clients.

Q56: How do you handle GraphQL schema migration?​

Answer: Add fields as optional first. Migrate data in background. Deprecate old fields. Remove after grace period. Use feature flags for breaking changes. Test with production-like queries.

🔍 Behind the Question: Schema evolution and zero-downtime migrations. ❌ The Red Flags: Big-bang schema changes.

Q57: What is GraphQL query depth limiting?​

Answer: Limit query nesting depth to prevent deeply nested queries that cause performance issues. Example: max depth 10. Implement in query validation phase.

def depth_limit_validator(max_depth):
def validate(context):
if context.query.depth > max_depth:
raise GraphQLError("Query too deep")

🔍 Behind the Question: DoS prevention and query validation. ❌ The Red Flags: No depth limit; server crashes on deep queries.

Q58: How do you implement GraphQL authorization?​

Answer: Use directives or middleware to check permissions. Common patterns: (1) Field-level auth: @auth(requires: ADMIN). (2) Type-level auth. (3) Resolver-level checks. Use context for user info.

type Query {
secretData: String @auth(requires: ADMIN)
publicData: String
}

🔍 Behind the Question: Authorization patterns and security. ❌ The Red Flags: Auth in every resolver manually.

Q59: What is GraphQL schema stitching vs federation?​

Answer: Stitching merges schemas at gateway level; federation uses @key and @extends for distributed services. Stitching is simpler for small setups. Federation is better for large microservices with independent deployments.

🔍 Behind the Question: Microservice GraphQL patterns. ❌ The Red Flags: Using stitching for large microservice setups.

Q60: How do you handle GraphQL WebSocket connections?​

Answer: Use graphql-ws protocol. Handle connection_init, start, stop, connection_terminate. Authenticate during connection_init. Implement heartbeats. Scale with Redis Pub/Sub for multi-instance.

🔍 Behind the Question: Real-time protocols and scaling. ❌ The Red Flags: No authentication on WebSocket; no heartbeats.

Q61: How do you implement GraphQL query caching?​

Answer: Cache by query + variables hash. Use Apollo Client cache, Redis for server-side, or CDN for public APIs. Set Cache-Control headers. Invalidate on mutations.

@cache(max_age=60, vary_on=["query", "variables"])
def resolve_field(obj, info, **kwargs):
...

🔍 Behind the Question: Caching strategies and performance. ❌ The Red Flags: No caching; every query hits DB.

Q62: What is GraphQL introspection and when should you disable it?​

Answer: Introspection allows clients to query schema structure. Useful for development and tools. Disable in production for security (prevents schema discovery). Use environment-based config.

const server = new ApolloServer({
introspection: process.env.NODE_ENV !== 'production',
});

🔍 Behind the Question: Security and production hardening. ❌ The Red Flags: Introspection enabled in production.

Q63: How do you handle GraphQL batching and DataLoader?​

Answer: DataLoader batches multiple loads into one request. Use DataLoader from graphql-dataloader. Create loaders per request context. Deduplicates identical loads.

user_loader = DataLoader(load_users_by_ids)
def resolve_user(parent, info):
return user_loader.load(parent.userId)

🔍 Behind the Question: N+1 prevention and batching. ❌ The Red Flags: One DB query per resolver.

Q64: What is GraphQL schema-first development?​

Answer: Write SDL schema first, then implement resolvers. Clear contract between frontend and backend. Tools: Apollo Server, GraphQL Code Generator. Benefits: type safety, documentation, mock generation.

🔍 Behind the Question: Development workflow and API design. ❌ The Red Flags: Resolvers define API implicitly; no schema.

Q65: How do you implement GraphQL error handling?​

Answer: Use GraphQLError for field-level errors. Return partial data with errors array. Use error codes for categorization. Never return HTTP 500 for expected errors. All responses return HTTP 200.

def resolve_user(parent, info, id):
user = db.get_user(id)
if not user:
raise GraphQLError("User not found", extensions={"code": "NOT_FOUND"})
return user

🔍 Behind the Question: Error handling and API design. ❌ The Red Flags: HTTP 500 for business errors.

Q66: How do you handle GraphQL query complexity?​

Answer: Assign cost to each field. Limit total complexity per request. Reject expensive queries. Use directives to annotate field costs.

def complexity_limit_validator(max_complexity):
def validate(context):
if context.query.complexity > max_complexity:
raise GraphQLError("Query too complex")

🔍 Behind the Question: DoS prevention and resource protection. ❌ The Red Flags: No complexity limits; server crashes.

Q67: What is GraphQL persisted queries and why use them?​

Answer: Persisted queries store query hashes on server. Client sends only hash. Benefits: reduced bandwidth, query whitelisting, performance monitoring. Used by Shopify, GitHub.

🔍 Behind the Question: Performance and security. ❌ The Red Flags: No persisted queries for mobile clients.

Q68: How do you implement GraphQL subscriptions with Redis?​

Answer: Use Redis Pub/Sub for multi-instance subscription broadcasting. Each server publishes to Redis; all instances broadcast to connected clients. Use graphql-redis-subscriptions library.

pubsub = RedisPubSub(redis=redis_client)
subscription_source = RedisIterator(pubsub, "comment_added")

🔍 Behind the Question: Real-time scaling and multi-instance. ❌ The Red Flags: In-memory Pub/Sub; single instance only.

Q69: What is GraphQL query analysis and why is it important?​

Answer: Analyze queries for performance, complexity, and security. Track slow queries, expensive fields, and N+1 patterns. Use for optimization and capacity planning.

🔍 Behind the Question: Performance monitoring and optimization. ❌ The Red Flags: No query analysis; blind to performance issues.

Q70: How do you implement GraphQL file uploads?​

Answer: Use GraphQL multipart request spec. Define Upload scalar. Client sends multipart/form-data. Server processes file. Apollo Server supports this out of the box.

type Mutation {
uploadFile(file: Upload!): File!
}

🔍 Behind the Question: File handling and multipart requests. ❌ The Red Flags: Base64 encoding large files in JSON.

Q71: How do you handle GraphQL authorization with directives?​

Answer: Create @auth directive that checks permissions. Apply to fields/types. Directive receives context with user info. Reject unauthorized access with error.

directive @auth(requires: Role!) on FIELD_DEFINITION

type Query {
adminData: String @auth(requires: ADMIN)
userData: String @auth(requires: USER)
}

🔍 Behind the Question: Authorization patterns and schema design. ❌ The Red Flags: Auth logic in every resolver.

Q72: What is GraphQL schema composition and when is it used?​

Answer: Combine multiple GraphQL schemas into one. Used in microservices where each service has its own GraphQL API. Gateway composes schemas using Apollo Federation or schema stitching.

🔍 Behind the Question: Microservice integration and schema management. ❌ The Red Flags: Single schema for all services.

Q73: How do you implement GraphQL query caching with Redis?​

Answer: Cache query results by query hash + variables. Use Redis for distributed cache. Set TTL based on data freshness. Invalidate on mutations.

cache_key = f"graphql:{hash(query + str(variables))}"
cached = redis.get(cache_key)
if cached:
return json.loads(cached)
result = execute_query(query, variables)
redis.setex(cache_key, 300, json.dumps(result))

🔍 Behind the Question: Caching strategies and performance. ❌ The Red Flags: No caching; every query hits DB.

Q74: What is GraphQL query batching and when is it useful?​

Answer: Send multiple operations in one HTTP request. Reduces overhead. Apollo Client supports automatic batching. Server processes all operations in one request.

query Batch {
user1: user(id: 1) { name }
user2: user(id: 2) { name }
}

🔍 Behind the Question: Network efficiency and batching. ❌ The Red Flags: One HTTP request per query.

Q75: How do you handle GraphQL WebSocket connections at scale?​

Answer: Use connection pools, horizontal scaling, Redis Pub/Sub for multi-instance. Implement heartbeats. Use graphql-ws protocol. Scale horizontally with sticky sessions or connection registry.

🔍 Behind the Question: Real-time scaling and WebSocket management. ❌ The Red Flags: Single instance; no heartbeats; no scaling.

Q76: What is GraphQL query allowlisting and when is it used?​

Answer: Allow only pre-approved queries. Store query hashes. Validate before execution. Prevents malicious queries and DoS. Used in production for security.

🔍 Behind the Question: Security and query validation. ❌ The Red Flags: Executing arbitrary queries without limits.

Q77: How do you implement GraphQL query depth limiting?​

Answer: Limit query nesting depth. Reject queries exceeding max depth. Prevents deeply nested queries that cause performance issues.

def depth_limit(max_depth):
def validate(context):
if context.query.depth > max_depth:
raise GraphQLError("Query too deep")

🔍 Behind the Question: DoS prevention and query validation. ❌ The Red Flags: No depth limit; server crashes.

Q78: What is GraphQL query cost analysis?​

Answer: Assign cost to each field/type. Limit total cost per request. Prevents expensive queries. Use for billing or rate limiting.

def calculate_cost(ast):
# Recursively calculate field costs
return sum(field.cost for field in ast.fields)

🔍 Behind the Question: Resource protection and cost-based limiting. ❌ The Red Flags: No cost analysis; unlimited queries.

Q79: How do you handle GraphQL query timeouts?​

Answer: Set per-query timeout. Cancel long-running resolvers. Use deadlines in resolvers. Return partial data with timeout error.

@timeout(ms=5000)
def resolve_field(obj, info, **kwargs):
return expensive_operation()

🔍 Behind the Question: Timeout handling and resource protection. ❌ The Red Flags: No timeouts; runaway queries.

Q80: What is GraphQL query caching with persisted queries?​

Answer: Persisted queries + caching = query hash as cache key. Client sends hash; server looks up query, executes, caches result. Reduces bandwidth and improves performance.

🔍 Behind the Question: Performance and caching. ❌ The Red Flags: No caching; repeated queries hit DB.

Q81: How do you implement GraphQL query logging?​

Answer: Log queries, variables, execution time, errors, and user. Use structured logging. Be careful with PII in variables. Use for debugging and performance analysis.

logger.info("graphql.query", extra={
"query": query,
"variables": sanitize(variables),
"duration_ms": duration,
"user": user.id,
})

🔍 Behind the Question: Observability and debugging. ❌ The Red Flags: No query logging; blind to issues.

Q82: What is GraphQL schema registry and when is it used?​

Answer: Central registry for GraphQL schemas. Tracks versions, validates changes, manages composition. Used in microservices with federation or stitching. Apollo Studio, GraphQL Hive.

🔍 Behind the Question: Schema management and microservices. ❌ The Red Flags: No schema registry; schema drift.

Q83: How do you handle GraphQL query validation?​

Answer: Validate queries before execution: syntax, type checking, depth, complexity, authorization. Use built-in validators or custom. Reject invalid queries early.

validation_errors = validate(schema, query_ast, [depth_limit_validator(10)])
if validation_errors:
raise GraphQLError("Invalid query")

🔍 Behind the Question: Query safety and validation. ❌ The Red Flags: No validation; invalid queries reach resolvers.

Q84: What is GraphQL query deduplication?​

Answer: Deduplicate identical queries within a request or time window. Prevents duplicate work. Use DataLoader or query cache.

🔍 Behind the Question: Performance and efficiency. ❌ The Red Flags: Duplicate queries in same request.

Q85: How do you implement GraphQL query tracing?​

Answer: Trace resolver execution time. Use OpenTelemetry or Apollo Tracing. Identify slow resolvers. Export to Jaeger or Datadog.

@trace_resolver
def resolve_user(obj, info, id):
return db.get_user(id)

🔍 Behind the Question: Performance debugging and observability. ❌ The Red Flags: No tracing; can't identify slow queries.

Q86: What is GraphQL query complexity analysis?​

Answer: Assign complexity cost to each field. Limit total complexity per request. Prevents expensive queries. Use for rate limiting or billing.

def calculate_complexity(ast):
total = 0
for field in ast.fields:
total += field.complexity
total += calculate_complexity(field.selection_set)
return total

🔍 Behind the Question: DoS prevention and resource protection. ❌ The Red Flags: No complexity limits; server crashes.

Q87: How do you handle GraphQL query allowlisting?​

Answer: Store approved query hashes. Validate incoming queries against allowlist. Prevents malicious queries. Used in production for security.

🔍 Behind the Question: Security and query validation. ❌ The Red Flags: No allowlist; arbitrary queries allowed.

Q88: What is GraphQL query batching and when is it useful?​

Answer: Send multiple operations in one request. Reduces HTTP overhead. Apollo Client supports automatic batching. Server processes all operations in one request.

🔍 Behind the Question: Network efficiency and batching. ❌ The Red Flags: One HTTP request per query.

Q89: How do you implement GraphQL query caching with CDN?​

Answer: Use Cache-Control headers. Cache by query + variables. Use CDN for public queries. Invalidate on mutations. Use persisted queries for cache keys.

🔍 Behind the Question: Caching and CDN integration. ❌ The Red Flags: No CDN; every query hits origin.

Q90: What is GraphQL query analysis and why is it important?​

Answer: Analyze queries for performance, complexity, and security. Track slow queries, expensive fields, and N+1 patterns. Use for optimization and capacity planning.

🔍 Behind the Question: Performance monitoring and optimization. ❌ The Red Flags: No query analysis; blind to performance issues.

Q91: How do you handle GraphQL query timeouts?​

Answer: Set per-query timeout. Cancel long-running resolvers. Use deadlines in resolvers. Return partial data with timeout error.

🔍 Behind the Question: Timeout handling and resource protection. ❌ The Red Flags: No timeouts; runaway queries.

Q92: What is GraphQL query deduplication?​

Answer: Deduplicate identical queries within a request or time window. Prevents duplicate work. Use DataLoader or query cache.

🔍 Behind the Question: Performance and efficiency. ❌ The Red Flags: Duplicate queries in same request.

Q93: How do you implement GraphQL query logging?​

Answer: Log queries, variables, execution time, errors, and user. Use structured logging. Be careful with PII in variables.

🔍 Behind the Question: Observability and debugging. ❌ The Red Flags: No query logging; blind to issues.

Q94: What is GraphQL schema registry and when is it used?​

Answer: Central registry for GraphQL schemas. Tracks versions, validates changes, manages composition. Apollo Studio, GraphQL Hive.

🔍 Behind the Question: Schema management and microservices. ❌ The Red Flags: No schema registry; schema drift.

Q95: How do you handle GraphQL query validation?​

Answer: Validate queries before execution: syntax, type checking, depth, complexity, authorization. Reject invalid queries early.

🔍 Behind the Question: Query safety and validation. ❌ The Red Flags: No validation; invalid queries reach resolvers.

Q96: What is GraphQL query tracing and why is it important?​

Answer: Trace resolver execution time. Identify slow resolvers. Export to tracing systems. Use OpenTelemetry or Apollo Tracing.

🔍 Behind the Question: Performance debugging and observability. ❌ The Red Flags: No tracing; can't identify slow queries.

Q97: How do you implement GraphQL query cost analysis?​

Answer: Assign cost to each field. Limit total cost per request. Prevents expensive queries. Use for rate limiting or billing.

🔍 Behind the Question: Resource protection and cost-based limiting. ❌ The Red Flags: No cost analysis; unlimited queries.

Q98: What is GraphQL query depth limiting and when is it used?​

Answer: Limit query nesting depth. Prevents deeply nested queries that cause performance issues. Implement in query validation.

🔍 Behind the Question: DoS prevention and query validation. ❌ The Red Flags: No depth limit; server crashes.

Q99: How do you handle GraphQL query allowlisting?​

Answer: Store approved query hashes. Validate incoming queries against allowlist. Prevents malicious queries. Used in production for security.

🔍 Behind the Question: Security and query validation. ❌ The Red Flags: No allowlist; arbitrary queries allowed.

Q100: What is GraphQL query batching and when is it useful?​

Answer: Send multiple operations in one request. Reduces HTTP overhead. Apollo Client supports automatic batching. Server processes all operations in one request.

🔍 Behind the Question: Network efficiency and batching. ❌ The Red Flags: One HTTP request per query.

Q101: How do you implement GraphQL query caching with persisted queries?​

Answer: Persisted queries + caching = query hash as cache key. Client sends hash; server looks up query, executes, caches result.

🔍 Behind the Question: Performance and caching. ❌ The Red Flags: No caching; repeated queries hit DB.

Q102: What is GraphQL query analysis and why is it important?​

Answer: Analyze queries for performance, complexity, and security. Track slow queries, expensive fields, and N+1 patterns.

🔍 Behind the Question: Performance monitoring and optimization. ❌ The Red Flags: No query analysis; blind to performance issues.

Q103: How do you handle GraphQL query timeouts?​

Answer: Set per-query timeout. Cancel long-running resolvers. Return partial data with timeout error.

🔍 Behind the Question: Timeout handling and resource protection. ❌ The Red Flags: No timeouts; runaway queries.

Q104: What is GraphQL query deduplication and when is it used?​

Answer: Deduplicate identical queries within a request or time window. Prevents duplicate work. Use DataLoader or query cache.

🔍 Behind the Question: Performance and efficiency. ❌ The Red Flags: Duplicate queries in same request.

Q105: How do you implement GraphQL query logging?​

Answer: Log queries, variables, execution time, errors, and user. Use structured logging. Be careful with PII.

🔍 Behind the Question: Observability and debugging. ❌ The Red Flags: No query logging; blind to issues.

Q106: What is GraphQL schema registry and when is it used?​

Answer: Central registry for GraphQL schemas. Tracks versions, validates changes. Apollo Studio, GraphQL Hive.

🔍 Behind the Question: Schema management and microservices. ❌ The Red Flags: No schema registry; schema drift.

Q107: How do you handle GraphQL query validation?​

Answer: Validate queries before execution: syntax, type checking, depth, complexity, authorization. Reject invalid queries early.

🔍 Behind the Question: Query safety and validation. ❌ The Red Flags: No validation; invalid queries reach resolvers.

Q108: What is GraphQL query tracing and why is it important?​

Answer: Trace resolver execution time. Identify slow resolvers. Export to tracing systems.

🔍 Behind the Question: Performance debugging and observability. ❌ The Red Flags: No tracing; can't identify slow queries.

Q109: How do you implement GraphQL query cost analysis?​

Answer: Assign cost to each field. Limit total cost per request. Prevents expensive queries.

🔍 Behind the Question: Resource protection and cost-based limiting. ❌ The Red Flags: No cost analysis; unlimited queries.

Q110: What is GraphQL query depth limiting and when is it used?​

Answer: Limit query nesting depth. Prevents deeply nested queries that cause performance issues.

🔍 Behind the Question: DoS prevention and query validation. ❌ The Red Flags: No depth limit; server crashes.

Q111: How do you handle GraphQL query allowlisting?​

Answer: Store approved query hashes. Validate incoming queries against allowlist. Prevents malicious queries.

🔍 Behind the Question: Security and query validation. ❌ The Red Flags: No allowlist; arbitrary queries allowed.

Q112: What is GraphQL query batching and when is it useful?​

Answer: Send multiple operations in one request. Reduces HTTP overhead.

🔍 Behind the Question: Network efficiency and batching. ❌ The Red Flags: One HTTP request per query.

Q113: How do you implement GraphQL query caching with persisted queries?​

Answer: Persisted queries + caching = query hash as cache key.

🔍 Behind the Question: Performance and caching. ❌ The Red Flags: No caching; repeated queries hit DB.

Q114: What is GraphQL query analysis and why is it important?​

Answer: Analyze queries for performance, complexity, and security.

🔍 Behind the Question: Performance monitoring and optimization. ❌ The Red Flags: No query analysis; blind to performance issues.

Q115: How do you handle GraphQL query timeouts?​

Answer: Set per-query timeout. Cancel long-running resolvers.

🔍 Behind the Question: Timeout handling and resource protection. ❌ The Red Flags: No timeouts; runaway queries.

Q116: What is GraphQL query deduplication and when is it used?​

Answer: Deduplicate identical queries within a request or time window.

🔍 Behind the Question: Performance and efficiency. ❌ The Red Flags: Duplicate queries in same request.

Q117: How do you implement GraphQL query logging?​

Answer: Log queries, variables, execution time, errors, and user.

🔍 Behind the Question: Observability and debugging. ❌ The Red Flags: No query logging; blind to issues.

Q118: What is GraphQL schema registry and when is it used?​

Answer: Central registry for GraphQL schemas. Tracks versions, validates changes.

🔍 Behind the Question: Schema management and microservices. ❌ The Red Flags: No schema registry; schema drift.

Q119: How do you handle GraphQL query validation?​

Answer: Validate queries before execution: syntax, type checking, depth, complexity, authorization.

🔍 Behind the Question: Query safety and validation. ❌ The Red Flags: No validation; invalid queries reach resolvers.

Q120: What is GraphQL query tracing and why is it important?​

Answer: Trace resolver execution time. Identify slow resolvers.

🔍 Behind the Question: Performance debugging and observability. ❌ The Red Flags: No tracing; can't identify slow queries.


4. Real-World Scenarios (Expanded)​

Q121: Design a social media feed with GraphQL​

Answer: Use connections for pagination. Fan-out on write for timeline. Use DataLoader to batch user/post lookups. Cache hot feeds. Implement real-time updates with subscriptions.

🔍 Behind the Question: Feed design, pagination, and real-time. ❌ The Red Flags: N+1 on feed; no pagination.

Q122: Design an e-commerce checkout flow with GraphQL​

Answer: Mutations for addToCart, applyCoupon, createOrder. Use fragments for shared address/payment fields. Implement optimistic UI. Validate inventory before order. Handle payment errors gracefully.

🔍 Behind the Question: Complex mutations and state management. ❌ The Red Flags: One mutation per step; no optimistic UI.

Q123: Design a real-time chat application with GraphQL​

Answer: Use subscriptions for new messages. Queries for message history with cursor pagination. Mutations for sending messages. Implement presence with subscriptions. Use Redis for multi-instance Pub/Sub.

🔍 Behind the Question: Real-time chat and subscriptions. ❌ The Red Flags: Polling for messages; no presence.

Q124: Design a multi-tenant SaaS with GraphQL​

Answer: Use schema stitching or federation per tenant. Isolate tenant data at resolver level. Implement tenant-specific rate limiting. Use directives for tenant-specific auth.

🔍 Behind the Question: Multi-tenancy and GraphQL. ❌ The Red Flags: No tenant isolation; shared schema.

Q125: Design a content management system with GraphQL​

Answer: Types: Page, Component, Asset, User. Mutations for create/update/publish. Use versioning for content. Implement preview with draft content. Cache published content aggressively.

🔍 Behind the Question: CMS design and content modeling. ❌ The Red Flags: No versioning; no preview.

Q126: Design an analytics dashboard with GraphQL​

Answer: Queries for metrics, dimensions, filters. Use server-side aggregations. Implement query complexity limits. Cache frequent queries. Use subscriptions for real-time metrics.

🔍 Behind the Question: Analytics and aggregation patterns. ❌ The Red Flags: No caching; unbounded aggregations.

Q127: Design a notification system with GraphQL​

Answer: Queries for notifications list. Subscriptions for real-time updates. Mutations for markAsRead. Use cursor pagination. Implement per-user notification preferences.

🔍 Behind the Question: Notifications and real-time updates. ❌ The Red Flags: Polling for notifications; no pagination.

Q128: Design a file storage service with GraphQL​

Answer: Mutations for upload/delete. Queries for file list with pagination. Use Upload scalar. Implement presigned URLs for large files. Cache metadata.

🔍 Behind the Question: File storage and upload patterns. ❌ The Red Flags: Base64 in JSON; no presigned URLs.

Q129: Design a search API with GraphQL​

Answer: Queries with full-text search, filters, facets. Use Elasticsearch integration. Implement query suggestions. Cache frequent searches. Use cursor pagination for results.

🔍 Behind the Question: Search integration and performance. ❌ The Red Flags: SQL LIKE for search; no caching.

Q130: Design an IoT data platform with GraphQL​

Answer: Subscriptions for real-time telemetry. Queries for historical data with time-range filters. Mutations for device control. Use server-sent events for high-volume data.

🔍 Behind the Question: IoT patterns and real-time data. ❌ The Red Flags: Polling for telemetry; no subscriptions.

Q131: Design a developer portal with GraphQL​

Answer: Expose multiple service schemas via federation. Provide GraphQL playground. Document with SDL. Implement usage tracking and rate limiting per API key.

🔍 Behind the Question: Developer experience and API management. ❌ The Red Flags: No documentation; no rate limiting.

Q132: Design a multi-region GraphQL API​

Answer: Deploy gateway in each region. Route to nearest region. Use global cache for static queries. Replicate data across regions. Implement conflict resolution for writes.

🔍 Behind the Question: Multi-region and latency optimization. ❌ The Red Flags: Single region; no geo-routing.


5. Quick Reference (Expanded)​

GraphQL Built-in Directives​

# Include - include field if condition is true
field @include(if: $condition)

# Skip - skip field if condition is true
field @skip(if: $condition)

# Deprecated - mark field as deprecated
field @deprecated(reason: "Use newField")

GraphQL Client Tools​

# Apollo Client (JS)
npm install @apollo/client graphql

# GraphQL Request
npm install graphql-request

# Relay
npm install react-relay

GraphQL Server Tools​

# Apollo Server
npm install @apollo/server graphql

# GraphQL Yoga
npm install graphql-yoga

# Strawberry (Python)
pip install strawberry-graphql

GraphQL Best Practices​

  1. Use descriptive names in schema
  2. Implement proper nullability
  3. Use interfaces for shared fields
  4. Version through evolution
  5. Handle nullability explicitly
  6. Use DataLoader for batching
  7. Implement proper error handling
  8. Validate all inputs
  9. Limit query complexity
  10. Use proper pagination
  11. Enable introspection in dev only
  12. Use persisted queries in production
  13. Monitor query performance
  14. Use directives for cross-cutting concerns
  15. Document schema with descriptions

End of Guide


4. Real-World Scenarios​

Q133: Design a social media GraphQL API​

Answer: Design includes User, Post, Comment, Like types with relationships. Queries for fetching users, posts, feed. Mutations for creating posts, commenting, liking. Subscriptions for real-time notifications.

Q134: Design an e-commerce GraphQL API​

Answer: Design includes Product, Category, Cart, Order, Review types. Queries for products, categories, cart. Mutations for adding to cart, checkout, creating orders.

Q135: Real-time notifications design​

Answer: Use subscriptions for pushing notifications, implement notification types (like, comment, follow), use WebSocket connections, and handle notification delivery status.


5. Quick Reference​

Common GraphQL Packages​

# Server
npm install apollo-server graphql

# Client
npm install @apollo/client graphql

# Tools
npm install @graphql-tools/schema graphql-tools

# Subscriptions
npm install graphql-subscriptions graphql-ws

Best Practices​

  1. Use descriptive names in schema
  2. Implement proper nullability
  3. Use interfaces for shared fields
  4. Version through evolution
  5. Handle nullability explicitly
  6. Use DataLoader for batching
  7. Implement proper error handling
  8. Validate all inputs
  9. Limit query complexity
  10. Use proper pagination

End of Guide


Senior / Principal — Real World GraphQL Scenarios​

Q136: GraphQL N+1 resolver problem​

Level: Senior

Scenario: A GraphQL query fetches 10 posts with their authors. The resolver runs 1 query for posts, then 1 query per post for the author = 11 queries. At 100 posts, 101 queries. API slows under load.

Impact: Slow API. Database overload. Cascading latency as list size grows.

Root Cause: Naive resolvers fetch related data one-at-a-time without batching or caching within a single request.

Simple explanation: You order 10 books. For each book, you call the publisher separately to ask who wrote it. 11 calls instead of 1.

Technical Answer:

  1. Use DataLoader (graphql-dataloader) to batch and cache loads within a single request.
  2. Batch author IDs: collect all post author IDs, fetch authors in one query, map back.
  3. Use select_related/joinedload at the data layer for single-valued relations.
  4. Add query complexity analysis to reject overly deep/nested queries.

Code/Syntax Justification:

from aiodataloader import DataLoader

async def batch_authors(keys):
authors = await db.fetch_authors(keys) # one query
return [authors.get(k) for k in keys]

author_loader = DataLoader(batch_authors)

async def resolve_author(post):
return await author_loader.load(post.author_id)

Workflow Diagram:

Without DataLoader: With DataLoader:
1 query: posts 1 query: posts
10 queries: authors 1 query: authors (batched)
Total: 11 queries Total: 2 queries

🔍 Behind the Question: N+1 in GraphQL, DataLoader, batching, query complexity.

❌ The Red Flags: Per-item resolver calls; no batching; no query depth limit.


Q137: Over-fetching and large response size​

Level: Senior

Scenario: A GraphQL client requests 50 nested fields across related types. The response is 2MB JSON. Mobile clients on slow networks time out. The server spends CPU serializing unused fields.

Impact: Slow mobile experience. High server CPU. Bandwidth waste.

Root Cause: GraphQL lets clients request anything; without depth limits or field deprecation, clients over-fetch. No persisted queries or operation size limits.

Simple explanation: Ordering a 50-item tasting menu when you only wanted one dish. You pay for and wait on food you don't eat.

Technical Answer:

  1. Set max query depth (e.g., 10) and max fields per query.
  2. Use persisted queries: clients register operations; server only allows known queries.
  3. Field-level cost analysis: assign cost to fields, reject queries over budget.
  4. Encourage clients to request only needed fields (education + linting).
  5. Use @deprecated directive on expensive fields with deprecation reason.

Code/Syntax Justification:

# Ariadne / GraphQL-core depth limit
schema = make_executable_schema(type_defs, query, max_depth=10)
# Persisted query store: only allow registered operation hashes

Workflow Diagram:

Client query depth 15 Client query depth 3 (within limit)
| |
v v
Rejected: "query too deep" Executed normally
|
v
Client must simplify query

🔍 Behind the Question: Query depth limits, persisted queries, field cost, response size, over-fetching.

❌ The Red Flags: No depth limit; arbitrary client queries allowed; no persisted queries.