FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

GraphQL vs REST API Architecture

Schema stitching, N+1 query problem, DataLoader batching, and REST endpoint design.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Resolve N+1 query bottlenecks with DataLoader batching
  • ✓Choose between REST and GraphQL for client-facing APIs
Isometric Diagram LabSystem Design · 10 steps · 10 min

REST vs. GraphQL vs. gRPC Contracts

Compare over-fetching, N+1 resolver batching, HTTP/2 multiplexing, and Protobuf wire payloads.

Open Isometric Walkthrough
Full Technical Reference Document

Mental model

REST structures APIs as discrete HTTP endpoints tied cleanly to URL resources and standard caching semantics (GET /v1/projects/42), while GraphQL consolidates clients behind a typed schema graph (POST /graphql) where each frontend queries precisely the nested fields it needs in one round-trip. That field-level flexibility solves over-fetching across diverse web/mobile clients—but flips operational complexity onto the server: bypassing standard URL-based HTTP/CDN caching, opening N+1 SQL amplification unless resolvers are batched via per-request DataLoaders, and risking exponential recursive-query DoS attacks unless query depth and complexity limits guard the execution AST before resolvers run.

GraphQL Query Text
AST Validation + Depth & Cost Budget
Execute Field Resolvers
Per-Request DataLoader Batches SQL IN()
Return Pruned Typed JSON Payload
Conceptual teaching model synthesized from:graphql-spec,owasp-api-security

Theory

Evaluating GraphQL against REST highlights why teams frequently use both intentionally—REST for public webhook/file/cacheable endpoints, GraphQL (or federated BFF layers) where deeply connected product UIs serve varied mobile, dashboard, and desktop clients cleanly:

Architectural DimensionREST (HTTP + OpenAPI)GraphQL (SDL + Typed Resolvers)Production Consequence
HTTP Edge & Browser CachingNative (GET URLs + ETag, Cache-Control: s-maxage)Hard (POST queries bypass standard CDN path caches without APQ + GET persistence)Public read-heavy catalogs serve faster & cheaper via REST CDNs
Over-/Under-Fetching Across UIsCoarse fixed payloads OR multiple waterfall round-trips (users -> orgs -> roles)Exact client field projection inside 1 HTTP round-tripShines for mobile/multi-view dashboards with dense nested entity graphs
Database Query EfficiencyHand-tuned JOIN / CTE SQL per endpointVulnerable to cascading N+1 child SQL fetches without DataLoader batchingResolvers MUST batch via per-request DataLoader keyed per tick
Security Surface (DoS & Introspection)Predictable per-route rate limits (100 req/min on expensive endpoint)One POST /graphql can expand into 1,000,000 cyclic resolver calls (friends { friends ... })Requires AST depth/complexity ceilings + Persisted Queries in prod

Per-Request DataLoader Scoping, N+1 Elimination, and Query Complexity Guardrails

DataLoader solves N+1 resolver storms by coalescing individual loader.load(key) calls queued across one JavaScript/async event-loop tick into a single batched SQL query (WHERE id = ANY($1)), caching keys in memory for the duration of that single HTTP request. Two fatal implementation bugs appear frequently in production:

  1. Sharing a Global Singleton DataLoader Across Requests: Because DataLoader memoizes results forever by key ({ clearAll }) unless rebuilt per HTTP request, initializing const userLoader = new DataLoader(...) at module scope leaks private User A data across User B requests and serves stale mutated fields forever! Always instantiate fresh DataLoader maps inside the per-request GraphQL context factory.
  2. Omitting Input Key Ordering / Padding: DataLoader strictly requires the batch function to return an array of identical length and exact key order (userIds.map(id => map.get(id) ?? null))—otherwise PostgreSQL's unordered WHERE id IN (...) rows assign the wrong author to every article!
typescript
import DataLoader from "dataloader";
​
interface AuthorRecord {
id: string;
displayName: string;
}
​
interface RequestContext {
viewerId: string;
loaders: {
authorById: DataLoader<string, AuthorRecord | null>;
};
}
​
// Per-request factory: NEVER share a single DataLoader instance across different HTTP users!
export function createGraphQLContext(
viewerId: string,
fetchAuthorsByIds: (ids: readonly string[]) => Promise<AuthorRecord[]>,
): RequestContext {
const authorById = new DataLoader<string, AuthorRecord | null>(async (requestedIds) => {
const rows = await fetchAuthorsByIds(requestedIds);
const byId = new Map(rows.map((row) => [row.id, row]));
// CRITICAL invariant: preserve exact length & ordering matching requestedIds
return requestedIds.map((id) => byId.get(id) ?? null);
});
​
return { viewerId, loaders: { authorById } };
}
​
export const resolvers = {
Article: {
author: (article: { authorId: string }, _args: unknown, ctx: RequestContext) =>
ctx.loaders.authorById.load(article.authorId),
},
};

Furthermore, guard public GraphQL servers against GraphQL AST abuse (OWASP API4 / DoS): enforce static query depth caps (maxDepth <= 7), weighted query complexity scoring (multiplying nested list(limit: 100) fan-out costs before running any resolver), disable arbitrary schema Introspection in production (NoSchemaIntrospectionCustomRule), and—at high scale—use Trusted / Persisted Queries (clients send pre-registered query SHA-256 hashes over CDN-cacheable GET requests while arbitrary ad-hoc query text is rejected at the gateway).

Alternatives and trade-offs

  • REST + OpenAPI: Unbeatable when resources map cleanly to CRUD/RPC workflows, public developer APIs (Stripe, OpenAI), streaming SSE tokens, file uploads, and edge CDN caching; forces bespoke endpoints (GET /dashboard-summary) or BFF aggregation routes when screens combine unrelated data sources.
  • GraphQL + Per-Request DataLoader + Persisted Queries: Compelling as an internal UI/BFF orchestration layer unifying multiple microservices/subgraphs cleanly for rapid web and mobile client iteration; introduces schema complexity, harder rate-limiting ("cost per request" vs HTTP route counts), and file/streaming mismatches.
  • tRPC / Type-Safe RPC: Zero schema-language duplication when frontend and backend share one TypeScript monorepo (Next.js + Node), eliminating N+1 resolver fragmentation cleanly while trading away polyglot external consumer compatibility.

Failure modes and misconceptions

  1. Module-Scoped Global DataLoader Leaking Cross-Tenant Cache Data: Sharing one DataLoader outside the per-request context serves Tenant A's private records (cached on ID) to Tenant B and freezes stale mutations indefinitely. Instantiate loaders strictly per HTTP request!
  2. Returning Unaligned SQL Results from batchLoadFn: SQL WHERE id IN (...) returns matching rows in arbitrary disk order and omits deleted IDs, corrupting cross-row associations if not explicitly mapped back into ids.map(id => byId.get(id) ?? new Error(...) / null).
  3. Allowing Recursive Queries & Unbounded Pagination Without Complexity Caps: Exposing author { articles { author { articles ... } } } or items(first: 100000) lets a single request crash Node/Python workers cleanly. Reject queries exceeding static AST depth + cost rules prior to execution, or lock production behind Persisted Operations.
  4. Assuming HTTP 200 OK Always Means GraphQL Succeeded: GraphQL notoriously returns HTTP 200 OK even when "errors": [...] arrays contain UNAUTHORIZED or partial SQL timeouts—confusing naive status-code API healthchecks and client retry interceptors unless monitoring inspects GraphQL error extensions (extensions.code).
Reflect before revealing the guide

Decision scenario

Your SaaS platform runs an internal dashboard (Next.js + iOS/Android apps) composing nested workspaces, author profiles, active prompt versions, and run counts, alongside public high-traffic CDN-cached catalog pages and webhook/streaming endpoints. Keep public catalog APIs (s-maxage), file uploads, and SSE token streaming strictly on clean REST/HTTP endpoints, deploy GraphQL selectively as your authenticated client BFF backed by per-request DataLoader context factories (eliminating author/workspace N+1 waterfalls cleanly), disable production schema introspection, cap AST depth/pagination costs (maxDepth=6, maxComplexity=1000), and convert hot dashboard reads to SHA-256 Persisted Queries.

Learning outcomes

  • Contrast REST URL resource caching and predictable route limits against GraphQL single-roundtrip client-driven projections.
  • Eliminate GraphQL N+1 resolver explosions using per-request DataLoader instances that strictly preserve key length and order.
  • Defend GraphQL engines from recursive/fan-out DoS and cache leaks using AST complexity limits, disabled production introspection, and Persisted Queries.
  • Classify when GraphQL excels vs. when REST/OpenAPI or tRPC remains simpler and faster to operate.

Trade-offs

GraphQL eliminates client over-fetching and multi-hop UI waterfalls across evolving web/mobile products, yet shifts heavy operational burden onto resolver batching (DataLoader), AST DoS cost limiting, Persisted Query pipelines, and semantic error telemetry beyond HTTP status codes.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next