GraphQL offers a fundamentally different approach to API design compared to REST. Clients request exactly the data they need, reducing over-fetching and under-fetching. But the flexibility that makes GraphQL powerful also makes it easy to build APIs that are difficult to maintain, insecure, or slow. This guide covers the practices we follow at Nexis Limited when building production GraphQL APIs.
Schema Design Principles
The schema is your API's contract with consumers. Invest time in designing it thoughtfully. Start with the client's needs rather than mirroring your database schema. Use domain language that business stakeholders understand. Avoid exposing internal implementation details.
Use Descriptive Types and Fields
type Order {
id: ID!
status: OrderStatus!
totalAmount: Money!
placedAt: DateTime!
customer: Customer!
items: [OrderItem!]!
}
enum OrderStatus {
PENDING
CONFIRMED
SHIPPED
DELIVERED
CANCELLED
}
type Money {
amount: Float!
currency: CurrencyCode!
}
Avoid generic names like data or info. Use custom scalar types like DateTime, URL, and EmailAddress to encode validation into the schema itself. Use enums for fields with a fixed set of values—they provide documentation and type safety at the schema level.
Pagination
Never return unbounded lists. Use cursor-based pagination following the Relay Connection specification. This approach is efficient with database indexes and handles real-time data insertions gracefully, unlike offset-based pagination which can skip or duplicate records.
type Query {
orders(
first: Int
after: String
last: Int
before: String
filter: OrderFilter
): OrderConnection!
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type OrderEdge {
cursor: String!
node: Order!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
Error Handling
GraphQL returns HTTP 200 for most responses, even errors. Use a structured error approach that distinguishes between user errors and system errors. The union-based result pattern provides type-safe error handling:
type Mutation {
createOrder(input: CreateOrderInput!): CreateOrderResult!
}
union CreateOrderResult =
| CreateOrderSuccess
| ValidationError
| InsufficientStockError
type CreateOrderSuccess {
order: Order!
}
type ValidationError {
field: String!
message: String!
}
type InsufficientStockError {
productId: ID!
availableQuantity: Int!
}
Resolver Performance: The N+1 Problem
The most common performance issue in GraphQL is the N+1 query problem. When a query requests a list of orders with their customers, a naive implementation executes one query for the orders and then one query per order to fetch the associated customer. DataLoader solves this by batching and deduplicating database calls within a single request:
import DataLoader from 'dataloader';
const customerLoader = new DataLoader(async (customerIds: string[]) => {
const customers = await db.customers.findByIds(customerIds);
const customerMap = new Map(customers.map(c => [c.id, c]));
return customerIds.map(id => customerMap.get(id));
});
// In the Order resolver
const resolvers = {
Order: {
customer: (order) => customerLoader.load(order.customerId)
}
};
Security Considerations
GraphQL's flexibility creates unique attack surfaces. Malicious clients can craft deeply nested queries that consume excessive server resources. Implement these safeguards:
- Query depth limiting: Reject queries that exceed a maximum nesting depth (typically 7–10 levels).
- Query complexity analysis: Assign a cost to each field and reject queries exceeding a total cost threshold.
- Rate limiting: Limit requests per client based on query complexity, not just request count.
- Persisted queries: In production, allow only pre-registered queries, preventing arbitrary query execution.
GraphQL's power lies in its flexibility, but production applications require guardrails. A well-designed schema, proper pagination, DataLoader for batching, and layered security measures form the foundation of a scalable GraphQL API. Explore our backend engineering services if you need help building or optimizing your GraphQL layer.