Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Schema Design

Schema Design Best Practices

Design a GraphQL schema that lasts: model the domain, name things consistently, write specific mutations with payload types, and avoid flags and JSON blobs.

A GraphQL schema is a contract that many clients will rely on for years, and unlike a REST endpoint you cannot easily hide a mistake behind a version number. Fields are cheap to add and expensive to remove. That makes the first design good enough to matter. This lesson collects the habits that keep a schema pleasant to use and safe to grow.

Reminder: nothing here runs against a real GraphQL server. The schema text is shown read-only, and the runnable examples are small stand-ins: a linter for naming rules and a counter for impossible states.

Model the domain, not the database

The easiest schema to write mirrors your tables: a users table becomes a User type with the same columns, join tables become types, foreign keys become authorId fields. That works for a demo and ages badly. Clients do not care how data is stored; they care about the concepts of your product.

GRAPHQL
# Mirrors the database
type Post {
  id: ID!
  author_id: Int!
  category_id: Int!
  status: Int!
}

# Models the domain
type Post {
  id: ID!
  author: User!
  category: Category!
  status: PostStatus!
}

Return the related object, not its key: author: User! saves the client a second request and lets it pick the author fields it needs (Resolvers shows how a resolver supplies it, and The N+1 Problem and DataLoader how to do it efficiently). Likewise use an enum for a status code, not an integer whose meaning lives in someone's head. The database can change shape later without any client noticing, because the schema is the only interface.

Design from the client side

Start from screens What does the UI need to show?
Link objects Return author, not authorId.
Name concepts Say what it is, not where it lives.
Grow by adding New fields never break old queries.
1 / 2

Naming conventions

Consistency is more useful than any particular rule, but the community has settled on a convention that tools expect:

Thing Style Example
Types, interfaces, unions, inputs PascalCase BlogPost, CreatePostInput
Fields and arguments camelCase publishedAt, first
Enum values SCREAMING_SNAKE_CASE IN_PROGRESS
Mutations verb first, camelCase createPost, archiveProject

A few more habits:

  • Name fields for what they return, without the type name: User.name, not User.userName.
  • Use id for identifiers, typed ID!. An ID is always sent as a string and is meant to be opaque; clients should not do arithmetic on it. Keep it globally unique per type where you can, so a client cache can store objects by type and id.
  • Name a list by its plural (posts) and a single lookup by the singular (post(id: ID!)).
  • Avoid prefixes like get on queries. The root type is already called Query, so user(id: "1") reads better than getUser.

Rules like these are cheap to enforce automatically. The stand-in linter below reads a deliberately messy schema line by line and reports violations. It is a toy (real projects use tools such as graphql-eslint or schema linters in CI), but it shows how mechanical the checks are.

JS A naming-rules linter for SDL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last line of the schema: updateUserEmail passes. The linter does not understand meaning, only form, so reviews are still needed.

Specific mutations, not generic ones

A mutation like updateUser(input: UserInput!) seems flexible, but it hides intent. Which fields may a client change? Does changing the email send a verification message? Does changing the role need an administrator? Authorization, validation and side effects all end up in one big conditional.

Prefer small mutations named after what the user is doing:

GRAPHQL
type Mutation {
  changeEmail(input: ChangeEmailInput!): ChangeEmailPayload!
  publishPost(input: PublishPostInput!): PublishPostPayload!
  archiveProject(input: ArchiveProjectInput!): ArchiveProjectPayload!
}

Each one has its own input, its own permission check, and its own documentation. Mutations and Subscriptions introduced the single input argument pattern; here is why it is worth it. A single argument of an input type can gain optional fields later without changing the mutation's signature.

Payload types with room to grow

Return a dedicated payload type, never the bare object, even if today it has one field:

GRAPHQL
type PublishPostPayload {
  post: Post
  userErrors: [UserError!]!
}

type UserError {
  field: [String!]
  message: String!
  code: ErrorCode!
}

Tomorrow you may want to return the updated author's post count, a cursor, or a list of problems, and a payload type lets you add those fields without breaking anyone. The userErrors list carries expected failures such as "title is too long", which are not exceptions. Modeling Errors compares this style with unions and the top-level errors array.

Avoid boolean flags that pile up

Several booleans that describe one thing usually hide a state machine, and a state machine with impossible combinations is a source of bugs for both sides. If a post is either a draft, published or archived, three flags allow eight combinations, of which five make no sense. An enum allows only the three that do.

JS Booleans versus an enum: counting impossible states

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The enum version is status: PostStatus!. It is also easier to extend: adding SCHEDULED later is one new value (but see the note on evolution below). Booleans are right for genuinely independent yes/no facts such as isVerified; the smell is several of them describing one lifecycle.

No generic JSON blobs

A JSON scalar is tempting when data is "dynamic". It silently gives up what GraphQL is good at: the client cannot select parts of it, tools cannot autocomplete it, and the server cannot validate it. Whatever is inside is untyped, undocumented and therefore frozen forever, because changing it breaks someone unseen.

GRAPHQL
# Hard to use and impossible to evolve safely
type Product {
  attributes: JSON
}

# Typed, selectable, documented
type Product {
  attributes: [ProductAttribute!]!
}
type ProductAttribute {
  name: String!
  value: String!
}

If the data is truly arbitrary (user-defined form answers, for example), model the container but keep the blob small and clearly named. Custom scalars are covered in Input Types, Custom Scalars and Introspection.

Nullability and evolution

Make fields nullable by default unless you are certain the server can always supply them. Because a null in a non-null position bubbles up (see How Execution Works and How Errors Behave), an optimistic ! on a field backed by a flaky service can blank a whole section of a page. Relaxing a non-null output field to nullable later breaks clients that assumed it was there, while making a nullable field non-null is safe for outputs. For inputs the reverse holds. Adding enum values can break clients that handle each value with an exhaustive switch, so document that clients need a default case.

Before adding a field, write down the query that will use it. If you cannot, you are probably guessing, and guesses become permanent API surface.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the conventional style for enum values?

    Enum values are written in uppercase with underscores, such as IN_PROGRESS. Types use PascalCase and fields use camelCase.
  2. 2. Why return a dedicated payload type from a mutation?

    A payload type can gain new fields compatibly. Returning the bare object leaves no place for errors or extra data.
  3. 3. A Post has isDraft, isPublished and isArchived booleans. What is the main design problem?

    Three booleans allow 8 combinations but only 3 stages exist. A single enum field states the allowed values directly.
  4. 4. What is wrong with exposing a field as a generic JSON scalar?

    The server loses type checking and clients lose field selection and autocompletion. The shape also becomes impossible to evolve safely.
  5. 5. Which mutation name follows the usual convention?

    Mutations start with a verb and use camelCase, so publishPost is the conventional name.

Summary

  • Model your domain concepts and link objects; do not mirror tables or expose foreign keys.
  • Types are PascalCase, fields and arguments camelCase, enum values SCREAMING_SNAKE_CASE, mutations start with a verb.
  • Write specific mutations with one input argument and a dedicated payload type that can carry user errors.
  • Replace piles of booleans with enums and avoid generic JSON blobs.
  • Default to nullable output fields, and remember that evolving a schema is mostly adding.

Next: Pagination: Offset, Cursor and Connections.