GraphQL vs REST: Choosing the Right API Paradigm
Compare GraphQL and REST APIs, understand when to use each approach, schema design, queries, mutations, and trade-offs between the two paradigms.
REST organizes APIs around resources and HTTP semantics, while GraphQL lets clients select fields through a typed schema. This guide compares their query and mutation models, caching, error handling, subscription transports, and schema federation. It also covers N+1 query risks, persisted queries, security checks, and the trade-offs that matter when choosing one approach or combining both.
GraphQL vs REST: Choosing the Right API Paradigm
Introduction
REST and GraphQL offer different ways to expose application data. REST uses resource-oriented endpoints with fixed representations, while GraphQL lets a client request a specific shape through a schema and query language.
This guide compares their fetching, caching, error handling, subscriptions, and operational trade-offs. It also covers N+1 query risks, persisted queries, schema federation, and the conditions that make either style a better fit.
Core Concepts
REST: Multiple Endpoints
REST uses different endpoints for different resources:
# REST: Multiple endpoints
GET /users/123
GET /users/123/posts
GET /users/123/followers
Each endpoint returns a fixed data structure. If you need a user’s posts with follower counts, you might need multiple requests or get more data than necessary.
GraphQL: Single Endpoint
GraphQL uses a single endpoint with flexible queries:
# GraphQL: Single endpoint, flexible query
POST /graphql
query {
user(id: 123) {
name
posts {
title
}
followersCount
}
}
One request gets exactly the data you need.
Query Patterns
Queries
Queries are read operations: they fetch data and produce no side effects. The shape of the contract is the central comparison point between REST and GraphQL. REST spreads reads across many endpoints, each one returning a fixed resource shape. GraphQL consolidates reads to a single endpoint, where the client specifies which fields of which resources it actually wants.
The sub-sections below walk through the same read problem in both styles: fetching a user along with their recent posts. Notice how REST needs multiple round-trips or a denormalized payload, while GraphQL expresses the relationship declaratively in one request.
REST Queries
# REST: Get user and their posts
GET /users/123
GET /users/123/posts
GraphQL Queries
# GraphQL: One request, precise data
query GetUserWithPosts($userId: ID!) {
user(id: $userId) {
name
email
posts {
title
createdAt
}
}
}
GraphQL can resolve sibling query fields concurrently, but that does not guarantee parallel database work. The resolver implementation and its data source determine how each field is fetched.
Mutation Patterns
Mutations
Mutations are write operations: they change server state. Like queries, the surface looks different in REST and GraphQL. REST typically maps a mutation to a single HTTP verb on a resource URL (POST for create, PUT or PATCH for update, DELETE for removal). GraphQL collapses all writes into a single endpoint with an operation type, and the resolver decides what the write actually does.
The sub-sections below show the same write problem in both styles: creating a post, updating a user, deleting a comment. Pay attention to the partial-update case, where REST and GraphQL express it quite differently. PATCH in REST is a partial update of a single resource; in GraphQL, partial updates are the natural mode because the client controls which fields it sends back.
REST Mutations
# REST: Create, update, delete with different HTTP methods
POST /users
PUT /users/123
DELETE /users/123
GraphQL Mutations
# GraphQL: Mutations are explicit
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
updateUser(id: $id, input: $input) {
id
name
email
}
}
mutation DeleteUser($id: ID!) {
deleteUser(id: $id)
}
Subscriptions
A GraphQL subscription is a long-lived operation that delivers updates as events occur. The GraphQL specification does not choose a transport. Implementations commonly use WebSockets or server-sent events (SSE), and the client and server must agree on the protocol. Choose based on implementation support, proxies, authentication, delivery needs, and connection limits; evaluate WebSockets and SSE against the same requirements.
A subscription operation uses the schema’s subscription root:
subscription OrderStatus($id: ID!) {
orderStatus(id: $id) {
status
}
}
Subscriptions keep state for connected clients. A multi-server deployment may need a broker or shared event source, plus reconnection and cleanup behavior. Recheck authorization when access can change, bound query cost and active connections, and decide how to handle missed events. For infrequent updates, polling or a webhook may be simpler.
For protocol choices, lifecycle, authorization, and recovery, see the focused GraphQL subscriptions guide. The official GraphQL guide explains the operation model and transport independence.
Persisted Queries
Some GraphQL servers accept an operation hash in place of the full query text. Automatic persisted queries (APQ) can store query text by hash, then let clients send the shorter hash on later requests. A registered persisted-query list instead restricts execution to operations that were approved in advance. The server’s implementation determines how it handles an unknown hash; check whether clients can retry with full query text.
For example, a client may send a hash like this:
{
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "<operation-hash>"
}
}
}
APQ can reduce request size. A registered list can limit which operations the API accepts. Neither setting grants access to data or replaces resolver authorization, input validation, and query-cost limits. GET requests may also work with HTTP caches, but the cache key and response policy still need to account for variables, caller, and freshness.
Use APQ when request size is the main concern. Use a registered list when the API should reject unapproved operations, and confirm the server’s behavior for a cache miss. For the distinction between these modes and their caching implications, see GraphQL caching, Apollo’s APQ documentation, and its persisted-query list guidance.
Data Fetching and N+1 Problem
GraphQL lets a client select related fields in one operation, but one request does not guarantee one database query. Each resolver decides how to load its field. If a resolver fetches posts separately for each user, a query for users { posts { title } } can trigger one user query plus one posts query per user.
Batch related lookups by collecting the user IDs and fetching their posts together. A request-scoped loader can do this and memoize repeated keys during the same operation. Keep the loader scoped to a request so one user’s cached result cannot leak into another request. The batch function must return results in the same order as the requested keys.
Measure resolver and data-source calls on representative operations. Batching helps with repeated lookups, but it does not fix an expensive query plan, an unbounded selection set, or poor database indexes. The official DataLoader library is one common implementation.
Error Handling
Error Handling Overview
REST APIs commonly use HTTP status codes to report request outcomes, with details in the response body. GraphQL responses use data and errors fields; a field can fail while other fields return partial data. The HTTP status behavior depends on the transport, server, and error class, so clients should follow the API’s response contract.
Status codes let REST clients handle broad failure classes before parsing a response body. GraphQL can return both partial data and field errors, which requires clients to inspect the response body as well as the HTTP status. Each approach has trade-offs for retries, monitoring, and observability.
The sub-sections below compare the two patterns in detail, with concrete examples of how the same failure surfaces in each style.
REST Errors
REST uses HTTP status codes:
HTTP/1.1 404 Not Found
Content-Type: application/json
{"error": "User not found"}
GraphQL Errors
A GraphQL response can include errors in the body, sometimes alongside partial data. The HTTP status depends on the server, transport, and error:
{
"data": null,
"errors": [
{
"message": "User not found",
"locations": [{ "line": 3, "column": 5 }],
"path": ["user"]
}
]
}
Document the status and error-body behavior your clients should expect; GraphQL implementations differ in how they map errors to HTTP status codes.
Caching Strategies
REST responses often use HTTP cache headers and shared caches. GraphQL requests are commonly sent to one endpoint, so a cache needs to account for the operation, variables, authorization, and response policy. A persisted query can make a request identifiable, but it does not make the result safe to cache by itself.
Client normalized caches store entities by identity and update them as operations return new data. Server-side caching can target resolver results or data sources. In either case, define cache keys, authorization boundaries, invalidation after mutations, and freshness requirements before enabling a cache.
For cache keys, server policies, client normalization, and invalidation, see GraphQL caching, the GraphQL over HTTP guidance, and Apollo Client caching documentation.
Schema Federation
Schema federation composes a client-facing graph from services that own separate parts of a schema. A gateway or router plans requests across those subgraphs. Teams may deploy parts independently, but composition checks, cross-service calls, query planning, and new failure and latency paths come with that split.
Federation is useful when teams have clear domain ownership and can maintain service contracts. It does not remove authorization at each data boundary or make multiple services behave like one database. Before adopting it, measure a representative cross-subgraph request and decide how a partial failure should reach the client.
Federation and stitching have different models and operating costs. Compare them against the teams and services you have; neither is a default answer to schema growth. See the focused GraphQL federation guide and Apollo’s federation documentation.
When to Choose REST vs GraphQL
When to Choose REST
REST works well when:
- Your API is simple with predictable data requirements
- You need HTTP caching
- You are building public APIs consumed by many clients
- Your team is familiar with REST
- You need simple documentation (just list endpoints)
Examples: CRUD applications, simple CRUD APIs, public APIs for third-party developers
When to Choose GraphQL
GraphQL works well when:
- Clients need different data shapes
- Mobile apps needing minimal data transfer
- Complex domains with many related entities
- Rapid iteration with frontend teams
- You want strong typing and schema validation
Examples: Mobile apps, complex dashboards, microservices with varying client needs
Endpoint and Schema Security Checklist
Before shipping either style, check the API boundary:
- Authorize each requested object and field, including nested relationships and mutations.
- Bound query depth, item counts, total query cost, request rate, and execution time.
- Validate input values and limit batching or persisted operations according to the threat model.
- Set introspection and development-tool access intentionally for the deployment.
- For subscriptions, limit active connections and operations, and revoke access when a user’s permissions change.
- Keep credentials and sensitive variables out of logs.
GraphQL adds a flexible query surface, so apply these checks at resolver and request boundaries. The OWASP GraphQL cheat sheet covers query limits and authorization. For object-level authorization, see API scopes, roles, and object-level permissions.
Trade-off Analysis
Decision Framework
| Factor | REST | GraphQL |
|---|---|---|
| Data Fetching | Multiple endpoints; over/underfetching common | Single endpoint; exact data shapes |
| Caching | Standard HTTP cache controls | Cache policy must account for operation, variables, and authorization |
| Type Safety | No enforced schema; OpenAPI optional | Strongly typed schema; self-documenting |
| Learning Curve | Simpler for beginners; familiar HTTP concepts | Steeper; requires understanding of queries and resolvers |
| Tooling | Mature ecosystem; standard HTTP debugging | GraphQL-specific IDEs; introspection for discovery |
| Performance | Predictable; caching reduces load | N+1 risk without DataLoader; complex query optimization |
| Real-time | Polling or webhooks | Subscription operations; transport depends on the implementation |
| Security | Endpoint-based rate limiting; familiar patterns | Query complexity limits; introspection control |
| Schema Evolution | Versioned APIs; breaking changes managed | Additive changes; @deprecated directive |
| Team Ownership | Endpoint ownership can follow service boundaries | Federation can expose separately owned subgraphs |
Coexistence Pattern
Many organizations use both. A pragmatic approach:
// api/index.js
import { createServer } from "./api-server";
// REST for simple, stable resources
app.use("/api/users", usersRestRouter);
app.use("/api/health", healthCheckRouter);
// GraphQL for complex, client-driven data
app.use("/api/graphql", graphqlMiddleware);
// Bridge: REST endpoints call GraphQL resolvers internally
app.get("/api/users/:id/summary", async (req, res) => {
const result = await graphql.execute({
query: `query UserSummary($id: ID!) {
user(id: $id) { name email role }
}`,
variables: { id: req.params.id },
});
res.json(result.data);
});
When to Migrate
| Signal | Action |
|---|---|
| Mobile app requests 15+ REST calls per screen | Consider GraphQL |
| Frontend team blocked by backend endpoint pace | GraphQL gives frontend autonomy |
| Complex data graphs with varying client needs | GraphQL shines here |
| Heavy HTTP caching requirements | REST likely sufficient |
| Simple CRUD with predictable data shapes | REST is probably fine |
| Third-party public API | REST for stability and caching |
Production Failure Scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Query complexity explosion | Server overwhelmed; possible DoS | Implement query depth limiting; set complexity budgets |
| N+1 query problem | Database flooded with queries; slow responses | Use DataLoader for batching; optimize resolvers |
| Unwanted schema discovery | Clients can inspect types and fields | Choose an introspection policy for the deployment; keep resolver authorization in place |
| Subscription memory leaks | Server memory grows; eventual crash | Set subscription limits; implement timeouts |
| Mutation race conditions | Data inconsistency between related operations | Implement optimistic locking; use transactions |
| Unapproved operations | Clients submit costly or unreviewed operations | Use a safelist when appropriate; keep authorization and cost limits independent |
| Error masking with 200 OK | Errors hidden; debugging difficult | Return proper error status codes; use extensions |
Observability Checklist
GraphQL observability is harder than REST because a single endpoint handles every request—you cannot tell at a glance which operation a misbehaving request belongs to. You have to instrument the operation name, the selection set, and the resolver timing from the start, or you will spend your first outage paging through generic 200-OK logs. The checklist below covers the minimum useful signal set.
Think of observability in three layers. Metrics show what is happening right now—query rates, error rates, latency distributions. Logs capture what happened during a specific request—resolver timing, variable values, error details. Alerts fire when thresholds are crossed—error spikes, anomalous patterns, unusual activity. These layers connect: a metric anomaly surfaces in logs, a log pattern triggers an alert.
The sections that follow detail each layer with concrete items to track. Subscriptions and DataLoader particularly need extra instrumentation beyond what REST teams typically monitor.
Metrics
- Query rate by operation type (query/mutation/subscription)
- Query complexity distribution
- Request duration by operation and field
- Error rate by error type
- DataLoader batch efficiency (cache hit ratio)
- Schema introspection requests
- Subscription active count
- Query depth and breadth distribution
Logs
- Query operation name or persisted-query ID, complexity score, and redacted variable metadata
- Mutation name, outcome, and authorization decision; leave credentials and full auth context out
- DataLoader batch operations and cache misses
- Error responses with path and locations
- Schema change events
- Subscription lifecycle events
- Security events (introspection attempts, rate limit hits)
Alerts
- Query complexity exceeds threshold
- Error rate exceeds normal baseline
- DataLoader cache hit ratio drops below 80%
- Subscription count exceeds limits
- Unusual introspection activity
- Query depth spikes indicate potential attack
Common Pitfalls / Anti-Patterns
Overusing GraphQL for Simple Cases
GraphQL adds complexity. Simple REST endpoints may be better.
# Overkill: GraphQL for simple, predictable data
query {
healthCheck {
status
}
}
# Better: Simple REST endpoint
GET /health
Ignoring N+1 Queries
GraphQL makes N+1 problems easy to create.
# Problem: Fetches posts for each user separately
query {
users {
name
posts {
title
} # N queries for N users
}
}
# Better: Use DataLoader to batch
query {
users {
name
posts {
title
} # Single batched query
}
}
Not Implementing Proper Error Handling
GraphQL returns 200 OK even for errors.
// Problem: Error masked as success
{
"data": { "user": null },
"errors": [{ "message": "Not authorized" }]
}
// Better: Use proper HTTP status codes
{
"errors": [{
"extensions": { "code": "UNAUTHORIZED" }
}]
}
Managing Schema Introspection
Introspection lets clients and developer tools inspect the schema. Decide whether that discovery is part of the public API. If it is not, a server may restrict introspection or disable it for selected deployments. This reduces schema discovery; it does not authorize requests or replace access checks in resolvers.
const server = new ApolloServer({
schema,
introspection: false, // Use when schema discovery is not part of the API
playground: false, // Keep development tools out of deployments that do not need them
});
Quick Recap Checklist
- Choose REST for resource-oriented operations that benefit from standard HTTP behavior and caching.
- Use GraphQL when clients need different selections from a shared typed schema.
- Batch resolver data loads and set limits on query depth, cost, and page size.
- Enforce authorization in resolvers and monitor partial GraphQL errors.
Interview Questions
REST fits resource-oriented APIs with predictable representations and HTTP cache behavior. GraphQL can help when several clients need different selections from a shared schema. Compare the client needs, resolver costs, security controls, and operational experience before choosing.
No. Each resolver can call a data source, so nested fields can trigger an N+1 pattern. Batch repeated lookups with a request-scoped loader, then measure backend calls and query plans for the operations clients actually use.
Set a policy for each cache layer. Shared HTTP caches need keys and response headers that reflect the operation, variables, authorization scope, and freshness. Client normalization needs stable entity identity and an update or refetch plan after writes. See GraphQL caching for implementation details.
No. GraphQL defines the subscription operation, while the server chooses a supported transport such as WebSockets or SSE. Deployment must account for long-lived connections, authorization, event delivery, and reconnects. See GraphQL subscriptions.
Federation can help when multiple teams own stable domains and clients benefit from a composed graph. It adds composition checks, query planning, cross-service latency, and failure handling, so it is not a default scaling step. See GraphQL federation for the trade-offs.
Further Reading
Related GeekWorkBench Guides
- RESTful API Design — Resource modeling and standard HTTP behavior.
- API Resource Names, Relationships, and Collections — Routes and relationships for collection APIs.
- API Contracts — Contract documentation and compatibility expectations.
- API scopes, roles, and object-level permissions — Authorization at API object boundaries.
- GraphQL subscriptions — Transport and deployment decisions for long-lived operations.
- GraphQL federation — Subgraph ownership, composition, and router trade-offs.
- GraphQL caching — Cache keys, authorization boundaries, and freshness.
Official Documentation
- GraphQL Specification — The complete GraphQL specification
- Apollo GraphQL Docs — Apollo Server and Client documentation
- REST Maturity Model — Richardson’s REST maturity levels
Schema Design
- Schema Design Principles — Official GraphQL query documentation
- Schema Federation — Apollo Federation architecture
- GraphQL Schema Stitching — Schema stitching vs federation
Performance
- DataLoader — Official Facebook DataLoader library
- Query Complexity Analysis — Apollo query planning
- Persisted Queries — Apollo persisted queries documentation
Security
- GraphQL Security — Official GraphQL security best practices
- Query Depth Limiting — Apollo query depth limits
- Apollo schema introspection settings — Configure introspection for your deployment
Conclusion
REST and GraphQL make different trade-offs. REST is resource-oriented with fixed endpoints and built-in HTTP caching. GraphQL is query-oriented with flexible data fetching and strong typing.
REST works well for simple, predictable APIs where caching matters. GraphQL works well for complex, client-driven data requirements where you want to avoid overfetching. Neither is universally better.
For REST API design, see the RESTful API Design post. For versioning both types of APIs, see the API Versioning Strategies post.
Category
Related Posts
RESTful API Design: Best Practices for Building Web APIs
Learn REST principles, resource naming, HTTP methods, status codes, and best practices. Design clean, maintainable, and scalable RESTful APIs.
API Versioning: Managing Change Without Breaking Clients
Learn API versioning by comparing URL paths, headers, and query parameters, then plan compatible changes, deprecation, and consumer migrations.
GraphQL Federation: Subgraphs, Routing, and Trade-offs
Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.