GraphQL Architecture
20 min read
GraphQLSchemaResolversQueriesMutationsSubscriptionsOver-fetching
GraphQL: A Query Language for Your API
GraphQL was created by Facebook in 2012 to solve the over-fetching and under-fetching problems of REST APIs. Instead of multiple endpoints, you have one endpoint and the client specifies exactly what data it needs.
Core Concepts
Schema Definition Language (SDL)
The schema is the contract between client and server. It defines types, queries, and mutations:
Queries vs. Mutations vs. Subscriptions
| Operation | Purpose | HTTP Analogy |
|---|---|---|
| Query | Read data | GET |
| Mutation | Write/update data | POST/PUT/DELETE |
| Subscription | Real-time updates | WebSocket |
REST vs. GraphQL Trade-offs
| Aspect | REST | GraphQL |
|---|---|---|
| Endpoints | Many (/users, /posts) | Single (/graphql) |
| Data fetching | Fixed response shape | Client specifies fields |
| Caching | HTTP caching (easy) | Complex (needs client-side cache) |
| Versioning | /v1, /v2 | Evolve schema, deprecate fields |
| Learning curve | Low | Higher |
| File uploads | Native (multipart) | Complex (spec extension) |
The N+1 Problem in GraphQL
If a query fetches 100 users and each user has posts, a naive resolver would make 100 separate database queries for posts. The solution is DataLoader — a utility that batches and caches database lookups within a single request.
When to Use GraphQL
- Multiple clients (web, mobile, TV) needing different data shapes
- Complex, nested data relationships
- Rapid frontend iteration without backend changes
When NOT to Use GraphQL
- Simple CRUD APIs with few clients
- Heavy file upload requirements
- When HTTP caching is critical