Designing GraphQL Architecture

1. Designing GraphQL Schema Architecture

ElementDescription
TypeObject, Interface, Union, Enum, Scalar
QueryRead entry points
MutationWrite entry points
SubscriptionReal-time over WS/SSE
Directive@deprecated, @auth, custom
NamingPascalCase types; camelCase fields

2. Designing Query Optimization

TechniqueDetail
DataLoaderBatch + cache per request
Persisted queriesHash → query; smaller payloads, allowlist
Field projectionPush selection set into SQL
Defer/StreamSend fast fields first
CachingPer-resolver, per-field TTL

3. Designing DataLoader Pattern

Example: DataLoader (Node.js)

import DataLoader from "dataloader";

const userLoader = new DataLoader(async (ids) => {
  const rows = await db.query("SELECT * FROM users WHERE id = ANY($1)", [ids]);
  const byId = new Map(rows.map(r => [r.id, r]));
  return ids.map(id => byId.get(id) ?? null);
});

// In resolver:
const author = await userLoader.load(post.authorId);
PropertyDetail
ScopePer-request (avoid cross-request leaks)
BatchesWithin event loop tick
CachesBy key for life of request

4. Designing Mutations and Subscriptions

PatternDetail
Input typeSingle input arg per mutation
Payload typeReturn modified entity + clientMutationId
Errors as dataUnion: SuccessResult | ValidationError
Subscriptionsgraphql-ws over WebSocket

5. Designing Authentication and Authorization

LayerApproach
AuthNJWT in HTTP header → context
AuthZPer-field directive @auth(role: ADMIN)
Resolver guardCheck entitlement against ctx.user
Field maskingReturn null for unauthorized fields

6. Designing Schema Federation

ConceptDetail
SubgraphOwns slice of schema (e.g., Reviews)
SupergraphComposed schema served by router
EntityType extended across subgraphs (@key)
Reference resolverFetch entity by key
ToolsApollo Federation v2, GraphQL Mesh

7. Designing Query Complexity Analysis

StrategyDetail
Depth limitReject queries deeper than N
Cost analysisSum field costs; reject if > budget
Pagination capsMax first/last per connection
Persisted queries onlySafest; allow only known queries

8. Designing Caching Strategy

LayerDetail
CDN (persisted GETs)Cacheable URLs from query hash
Per-resolverCache by args + parent id
Object cacheApollo Server Response Cache
ClientApollo Client / Relay normalized cache

9. Designing Error Handling

PatternDetail
errors[] in responseStandard partial-error mode
extensions.codeMachine-readable code (UNAUTHENTICATED)
Errors as union typesType-safe expected errors
Avoid leaking internalsMask stack traces in prod

10. Designing Pagination and Filtering

SpecDetail
Relay Cursor Connectionsedges, node, pageInfo, cursors
first / after / last / beforeForward + backward cursors
Filter inputwhere: { status: ACTIVE, createdAfter: ... }
SortorderBy: [{field: CREATED_AT, dir: DESC}]

11. Designing Rate Limiting for GraphQL

ApproachDetail
Per request countInsufficient — 1 query may be huge
Cost-basedCharge each field; cap budget per minute
Persisted query allowlistPre-known costs
Per-operationLimit by operation name

12. Designing Schema Stitching

vs FederationDetail
StitchingGateway introspects + merges remote schemas
FederationSubgraphs declare ownership via directives
When to use stitchingAggregating 3rd-party GraphQL APIs
ToolsGraphQL Tools, Mesh