Complete Guide to GraphQL Schema Design
Design GraphQL schemas that evolve without breaking clients. Type design, connections, mutations, error handling, and schema-first vs code-first.
Introduction
A GraphQL schema is the contract between your API and its clients — and contracts are expensive to change. A well-designed schema is easy to learn, hard to misuse, and absorbs new features without breaking anyone. A bad one surfaces as confusing queries, N+1 meltdowns, and migration pain that lands on your clients, not on you.
This guide covers the design decisions that age well: type modeling, connections, mutations, error handling, and deprecation workflows. It stops where implementation begins — resolver internals live in the framework docs, and running a graph in production is covered in the production sections of the Complete Guide to GraphQL Federation.
Schema-First vs Code-First
Two workflows produce the same artifact — an SDL schema — but they change who owns it and who reviews it.
Schema-First
You write .graphql files by hand; generators produce types and resolver signatures.
# schema.graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: User!
}
type Query {
user(id: ID!): User
users(limit: Int = 10, offset: Int = 0): [User!]!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
input CreateUserInput {
name: String!
email: String!
}
type CreateUserPayload {
user: User
errors: [UserError!]!
}
type UserError {
field: String
message: String!
}
The schema becomes the contract you review in a PR — frontend teams can read it before a line of backend code exists, and codegen keeps resolvers honest. The cost is two artifacts to keep in sync and a build step that not every team enjoys.
Code-First
Types live in your language; a library derives the schema.
import { schema } from "nexus";
schema.objectType({
name: "User",
definition(t) {
t.id("id");
t.string("name");
t.string("email");
t.list.field("posts", {
type: "Post",
resolve: (user, _args, ctx) => ctx.db.posts.findMany({ where: { authorId: user.id } }),
});
},
});
schema.queryType({
definition(t) {
t.field("user", {
type: "User",
args: { id: schema.idArg() },
resolve: (_root, args, ctx) => ctx.db.users.findUnique({ where: { id: args.id } }),
});
},
});
One source of truth, type safety end to end, no codegen. The cost: the schema is implicit in implementation — a reviewer can’t see the contract without reading resolvers, and design discussions happen inside backend code. Nexus does this for Node.js; the same pattern exists across ecosystems (Pothos for TypeScript, Graphene and Strawberry for Python, graphql-java for the JVM).
Which to Choose
| Signal | Schema-first | Code-first |
|---|---|---|
| Who reviews the API | Separate API designer or frontend team | Backend team owns everything |
| Type safety | Needs codegen to stay in sync | Native, end to end |
| Schema as a reviewable artifact | Yes — it’s a file | Only via introspection |
| Federation subgraphs | Natural fit (SDL is the handoff) | Works, with an SDL export step |
| Team shape | Mixed frontend/backend | Backend-heavy |
The honest answer: pick the one your team will actually review. A schema-first file nobody reads is worse than a code-first setup with disciplined PR review.
Type Design Principles
Name with Nouns, Not Verbs
Types are entities; actions belong in mutations.
# Good
type User { ... }
type Product { ... }
type Order { ... }
# Bad: verbs as type names
type GetUser { ... }
type CreateOrder { ... }
Use Non-Null by Default
Mark a field non-null (!) when it must always have a value. Reserve nullable for fields that can legitimately be absent.
type User {
id: ID! # Always present
name: String! # Always present
email: String # May be null if user has not set email
deletedAt: DateTime # Null until deleted
}
There’s a real trade-off hiding here. When a non-null resolver throws, the error propagates to the nearest nullable parent — a failed non-null field can blank out the entire object. So keep non-null off fields backed by flaky external services, even if they “should” always return data. Strong nullability is about contract honesty, not optimism.
Use Enums for Fixed Values
Enums are self-documenting and type-safe; strings invite typos that only explode at runtime.
enum OrderStatus {
PENDING
CONFIRMED
SHIPPED
DELIVERED
CANCELLED
}
type Order {
status: OrderStatus!
}
Use Interfaces for Shared Fields
When several types share fields, an interface gives clients polymorphic queries without knowing concrete types.
interface Node {
id: ID!
}
interface Timestamped {
createdAt: DateTime!
updatedAt: DateTime!
}
type User implements Node & Timestamped {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
name: String!
email: String!
}
type Post implements Node & Timestamped {
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
title: String!
body: String!
}
query {
search(term: "alice") {
id
createdAt
... on User { name }
... on Post { title }
}
}
Interfaces vs Unions
Both give you polymorphism; the question is whether the variants share fields. Interfaces are contracts — every implementer exposes the interface’s fields, and clients can query them unconditionally. Unions are membership — the types may share nothing, so every field access needs an inline fragment.
Reach for an interface when types genuinely share structure (Node.id, Timestamped.createdAt). Reach for a union when the only thing they share is where they can appear (SearchResult = User | Post | Product). Modeling a union as an interface means inventing shared fields that don’t mean anything — and clients that can query id on every search result shouldn’t have to write ... on User { id } for each type anyway.
Custom Scalars
Custom scalars (DateTime, Email, URL, UUID) carry validation semantics a plain String can’t express. Use them for domain types with real invariants — a timestamp must parse, an email must be an email. Don’t mint scalars for decoration: every custom scalar is a contract clients must understand, and String with a field description is often enough. Whatever you add needs deterministic serialize/parse behavior on both ends.
Pagination with Connections
Lists deserve more than [User!]!. The Relay Connection spec gives clients cursors, pagination metadata, and a uniform shape across every list field.
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type Query {
users(first: Int = 10, after: String): UserConnection!
}
query {
users(first: 10, after: "abc123") {
edges {
node { id name email }
cursor
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}
The shape does three jobs. edges wraps each item so the cursor travels with its node; pageInfo tells the client whether to fetch more and where to resume; forward args (first/after) and backward args (last/before) cover both directions for UIs that paginate either way. Cursors are opaque — base64 over an ID or timestamp is the convention, and clients should never parse them. totalCount is handy but optional: it’s an extra query that most infinite-scroll clients never read.
Offset vs Cursor Pagination
Offset pagination (limit + offset) is one line of code and breaks the moment someone inserts or deletes an item mid-page — clients see duplicates or gaps. Cursor pagination survives mutation because the cursor anchors to a record, not a position.
Use offset for admin dashboards where “go to page 37” is a real feature. Use cursors for feeds, infinite scroll, and anything client-facing.
Mutation Design
One Mutation per Action
Each mutation is one business operation. Generic “upsert” mutations hide conditional branches that leak into client code anyway — you just made the client guess which half ran.
# Good: separate mutations
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(input: UpdateUserInput!): UpdateUserPayload!
deleteUser(input: DeleteUserInput!): DeleteUserPayload!
}
# Bad: ambiguous upsert
type Mutation {
upsertUser(input: UpsertUserInput!): UpsertUserPayload!
}
Input Types for Arguments
Mutations take a single input object. Adding a field later is a non-breaking change, and every signature stays uniform.
input CreateUserInput {
name: String!
email: String!
role: UserRole = MEMBER
}
input UpdateUserInput {
id: ID!
name: String
email: String
role: UserRole
}
Note the nullability asymmetry: UpdateUserInput keeps everything except id nullable — a null field means “don’t touch it,” which is exactly what partial updates need.
Payload Types with Errors
Every mutation returns a payload: the result plus a list of structured errors clients can switch on.
type CreateUserPayload {
user: User
errors: [UserError!]!
}
type UserError {
field: String
message: String!
code: ErrorCode!
}
enum ErrorCode {
VALIDATION
NOT_FOUND
UNAUTHORIZED
CONFLICT
INTERNAL
}
Mutation Naming
Imperative verb for the operation, {Operation}Input / {Operation}Payload for the types. Consistency does the documenting.
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(input: UpdateUserInput!): UpdateUserPayload!
deleteUser(input: DeleteUserInput!): DeleteUserPayload!
sendPasswordResetEmail(input: SendPasswordResetEmailInput!): SendPasswordResetEmailPayload!
}
Error Handling
GraphQL has two error channels: the top-level errors array (resolver threw) and whatever you return in the payload. Use the right one.
Structured Errors in Payloads
Expected failures — validation, conflicts, not-found — belong in the payload, not the errors array. A thrown UserError forces clients to pattern-match strings; a returned one gives them a code to switch on.
const resolvers = {
Mutation: {
createUser: async (_root, { input }, ctx) => {
const existing = await ctx.db.users.findUnique({ where: { email: input.email } });
if (existing) {
return {
user: null,
errors: [{
field: "email",
message: "Email already in use",
code: "CONFLICT",
}],
};
}
const user = await ctx.db.users.create({ data: input });
return { user, errors: [] };
},
},
};
Throwing for Unexpected Errors
Genuine surprises — the database is down, a bug threw — should propagate. The runtime nulls the field and puts the error in errors, where clients can inspect extensions.code (Apollo Server sets codes like INTERNAL_SERVER_ERROR). Log everything server-side; send the client a generic message. The dividing line: if a client could do something about it, it’s a payload error.
Schema Evolution
GraphQL’s versioning strategy is deprecation, not /v2/. That only works if you treat the schema as a public API.
Adding Fields (Non-Breaking)
New fields are invisible to existing clients and opt-in for new ones.
# v1
type User {
id: ID!
name: String!
email: String!
}
# v2: add avatarUrl (non-breaking)
type User {
id: ID!
name: String!
email: String!
avatarUrl: String
}
Removing Fields (Breaking)
Deleting a field breaks every client that selects it — deprecate first, remove later.
type User {
id: ID!
name: String!
email: String!
avatar: String @deprecated(reason: "Use avatarUrl. Removed in v3.")
avatarUrl: String
}
The safe loop is expand-migrate-contract: add the replacement, ship it, measure until usage of the old field hits zero, then remove. GraphQL tooling (Apollo Studio’s field usage, graphql-inspector between schema versions) tells you when “zero” is real. A deprecated field without a removal date is just clutter.
Deprecation Best Practices
- Always provide a
reason— it’s the migration guide clients actually read - Point to the replacement field or mutation
- Monitor field usage before scheduling removal
- Give deprecated fields a removal date, even a generous one
- Never deprecate without an alternative — “we’re deleting this, good luck” is how you lose client trust
N+1 Prevention
A list resolver that queries per item gives you 101 database hits for 100 users — that’s the N+1 problem, and it’s a schema-adjacent design flaw because good schemas invite it.
DataLoader
DataLoader collapses per-item loads into one batched query — 100 load() calls become a single WHERE authorId IN (...).
import DataLoader from "dataloader";
const postsLoader = new DataLoader(async (userIds: number[]) => {
const posts = await db.posts.findMany({ where: { authorId: { in: userIds } } });
const postsByAuthor = new Map<number, Post[]>();
for (const post of posts) {
const list = postsByAuthor.get(post.authorId) ?? [];
list.push(post);
postsByAuthor.set(post.authorId, list);
}
return userIds.map((id) => postsByAuthor.get(id) ?? []);
});
const resolvers = {
User: {
posts: (user: User) => postsLoader.load(user.id),
},
};
The load order matters: postsLoader must return results in the same order as userIds — an empty array for users with no posts, or DataLoader silently misaligns the batch. Create the loader per request (in context), not globally: a shared instance caches across users and serves stale or leaked data.
Field-Level Batching
When you control the query shape, prefetching at the resolver level avoids a loader entirely:
const resolvers = {
Query: {
users: async (_root, { limit, offset }, ctx) => {
const users = await ctx.db.users.findMany({ take: limit, skip: offset });
const userIds = users.map((u) => u.id);
const allPosts = await ctx.db.posts.findMany({ where: { authorId: { in: userIds } } });
for (const user of users) {
user.posts = allPosts.filter((p) => p.authorId === user.id);
}
return users;
},
},
};
Designing for Federation
Once the schema runs in a federated graph, design decisions get a second dimension: entity ownership. Types that other subgraphs extend need @key fields, and every extension is a network hop — the same design choices (nouns, non-null boundaries, connections) apply, but now each @external and @requires adds an invisible cross-team dependency. Keep entity owners short and boundary fields nullable so a dead subgraph degrades one field instead of the whole response. The Complete Guide to GraphQL Federation covers both the mechanics and the operational side.
Schema Validation and Linting
Design rules only work if they’re enforced:
- graphql-schema-linter: naming conventions, description requirements, deprecation policy
- Apollo Studio: schema analytics, field usage, version history
- graphql-inspector: breaking-change detection between schema versions — wire it into CI before merge
# .graphql-schema-linterrc
rules:
- types-have-descriptions
- fields-have-descriptions
- enum-values-have-descriptions
- input-object-values-have-descriptions
- deprecations-have-a-reason
- enum-values-sorted-alphabetically
- type-fields-sorted-alphabetically
Best Practices
- Design the read path first. Sketch the top client queries before writing types — a schema that reads well usually writes well too.
- Make invalid states unrepresentable. Prefer
OrderStatusoverstatus: String; prefer a union over a field that means three different things. - Keep descriptions on everything public. The schema is your API documentation;
descriptionsare the contract’s fine print. - Version nothing, deprecate everything. Adding fields is free; removing them is the only real versioning event.
- Review the schema, not just the code. Schema changes deserve their own diff review — a one-line SDL change can break clients a resolver refactor never would.
Common Mistakes
- Mirroring the database. Exposing tables 1:1 leaks storage details into the contract. Model the API around what clients ask for.
- Non-null on external data. A non-null field backed by a flaky service converts one bad response into a null graph.
- Mutation payloads without errors. Clients end up parsing
errors[0].messagestrings — the least stable part of your API. - Offset pagination on mutable lists. Inserts between pages produce duplicates and gaps in production, not in tests.
- Enums for values that change.
OrderStatusis fine; a vendor list that grows monthly wants a type, not an enum — enum changes are additive but tooling treats them as constants.
Checklist for Schema Review
Before publishing a schema change, verify:
- All types and fields have descriptions
- Non-null is used correctly (not on fields that depend on external services)
- Lists use the Connection pattern for pagination
- Mutations use input types and return payload types with errors
- Enums are used for fixed-value fields instead of strings
- Interfaces are used for shared fields across types
- Deprecated fields have a reason and a replacement
- No N+1 resolvers (use DataLoader or batch loading)
- Schema passes linter rules
- No breaking changes (or documented in migration guide)
To turn these checks into a shared team standard, the GraphQL API design guidelines template packages them as a copy-paste internal document. The full SDL, linter config, and resolver examples ship in the companion repository.
See Also
- Complete Guide to GraphQL Federation
- GraphQL Interface Polymorphism Pattern
- GraphQL API design guidelines template
- GraphQL specification — the contract itself, worth reading once
- Relay GraphQL Cursor Connections spec — the pagination convention this guide follows
- GraphQL schema linter rules — enforceable versions of these guidelines
Frequently Asked Questions
Should I use nullable or non-null fields?
Default to non-null for fields that always have a value (id, name, createdAt). Use nullable for legitimately absent values (email, avatarUrl, deletedAt) — and for anything resolved from an external service, where a downstream failure would otherwise null out the whole object.
How do I handle authentication in the schema?
You don't — auth lives in the context or middleware layer, not the type system. Resolvers check ctx.user and throw UNAUTHORIZED. The schema stays clean of auth concerns; authorization is resolver logic, not schema shape.
Should I expose computed fields?
Yes. Fields like fullName or orderTotal save every client the same logic and keep business rules on the server. Document them as computed so nobody reimplements them.
How do I version my GraphQL schema?
You evolve instead of versioning: add fields, deprecate the old ones, and remove them once usage metrics show zero consumers. For genuinely breaking redesigns, run two schemas in parallel rather than minting a /v2/ endpoint.
What is the difference between interfaces and unions?
Interfaces are contracts for shared fields (query them without knowing the concrete type). Unions are membership sets with no required fields (every access needs an inline fragment). Same polymorphism, different guarantee.
Should I use custom scalars?
For domain types with real invariants — DateTime, Email, UUID — yes, they carry validation strings can't. For everything else, String plus a description is clearer. Every scalar you add is a contract both sides must implement.
Related Resources
Complete Guide to GraphQL Federation
Build and operate unified GraphQL APIs across multiple services with Apollo Federation. Covers subgraphs, supergraph composition, entity resolution, router deployment, security, and observability.
PatternGraphQL Interface Polymorphism Pattern
Model polymorphic types with GraphQL interfaces to share field contracts across different object types while keeping resolvers type-specific.
GuideComplete Guide to GraphQL Caching
Cache GraphQL responses at every layer: CDN, gateway, DataLoader, persisted queries, and client-side. Covers cache keys, invalidation, HTTP caching directives, and Apollo Client cache.
GuideComplete Guide to GraphQL Security
Secure a production GraphQL API: introspection control, depth and cost limits, rate limiting, persisted queries, injection prevention, and error sanitization.
GuideComplete Guide to GraphQL Testing
Test GraphQL APIs at every layer: resolver unit tests, schema integration tests, contract and security tests, and E2E for critical operations.