API Design intermediate LIVE DEMO
⚑

REST API vs GraphQL Data Fetching

Compare REST API waterfall calls with GraphQL nested data resolution. Animate network roundtrips, AST parsing, and database query differences.

restgraphqlapi-designnetwork-protocolsdata-fetching
Interactive Demo

Continue with the guided workspace

Use the paired workspace to connect this guide's mental model with live component state, visible signals, and the outcome each step or scenario is meant to prove.

REST and GraphQL answer the same question β€” how does a client retrieve structured data from a server β€” with fundamentally different tradeoffs. REST exposes fixed resource endpoints where each URL returns a predefined shape. GraphQL lets the client declare exactly the nested fields it needs in a single query document, returning a tailored response at the cost of server-side parsing and resolver coordination.

Mental Model & Real-World Concurrency

In the visualizer, the REST lane demonstrates a deliberately naΓ―ve serial waterfall to clearly highlight dependency hops:

  1. GET /users/42 (fetches user profile: name, avatar, plus 22 unused fields)
  2. GET /users/42/posts (fetches 3 posts: title, body)
  3. GET /posts/101/comments, GET /posts/102/comments, GET /posts/103/comments (fetches comments with author names)

Request Count vs. Critical Path

In production REST systems, request count does not equal critical path latency:

  • Serial Waterfall (NaΓ―ve): 5 requests across 5 sequential roundtrip turns.
  • Concurrent Parallelization (HTTP/2 / Promise.all): Once post IDs are known, the 3 comment calls dispatch concurrently over multiplexed HTTP/2 connections, reducing the critical path from 5 turns to 3 critical roundtrips (/users β†’ /posts β†’ parallel /comments).
  • Bulk Endpoints: A single bulk query (GET /comments?post_ids=101,102,103) reduces the critical path to 3 requests in 3 turns.
  • Backend-For-Frontend (BFF): A dedicated screen endpoint (GET /api/v1/users/42/feed) can return the exact composite payload in 1 roundtrip.

GraphQL achieves this single-roundtrip aggregation declaratively without requiring custom backend BFF endpoint authoring for every UI screen variation.

query GetFeed {
  user(id: 42) {
    name
    avatar
    posts {
      title
      body
      comments {
        text
        author {
          name
        }
      }
    }
  }
}

Components and Architectural Roles

REST Client App

The client application managing API requests. In basic REST architectures, the client must orchestrate cascading requests and stitch separate JSON payloads in memory.

REST Resource Endpoints (/users/:id, /posts, /comments)

Stateless HTTP handlers that map URLs to domain entities. Endpoints return fixed schema representations, which enables transparent CDN caching but can cause over-fetching (returning unneeded fields) or under-fetching (requiring subsequent calls).

REST Database Tier

Backing relational or document stores. Processes discrete queries per endpoint invocation.

GraphQL Client App

Constructs structured query documents declaring required fields and variables, dispatching them over HTTP POST to /graphql.

GraphQL Gateway & Execution Engine

Parses the query document into an Abstract Syntax Tree (AST), validates field selections against the schema type definition, and invokes field resolvers.

Resolvers & DataLoaders

Field-level resolution functions. Sibling resolvers execute concurrently in memory. To prevent backend N+1 query loops, DataLoaders batch lookups within the same tick into a single SQL IN query or bulk RPC.

Architectural Decision Matrix

Constraint / RequirementREST APIGraphQL
Edge CDN CachingNative HTTP GET / Cache-Control / ETagsComplex (POST bypasses standard CDNs; requires APQ or client caches)
Payload PrecisionFixed shapes (over-fetching unless custom query params added)Exact field matching (client declared)
Screen AggregationClient orchestration, Bulk APIs, or custom BFF endpointsDeclarative single-operation nesting
Server ComplexityLow (pre-routed controller actions)Moderate-High (AST parse, type validation, resolver security)
Network EfficiencyHTTP/2 multiplexing mitigates connection overhead1 WAN roundtrip minimizes mobile cellular latency
Best Used ForSimple CRUD, public APIs, static media, high-cache throughputMulti-platform apps, rapid frontend iteration, nested aggregator BFFs

Common Questions

What is the primary difference in data fetching between REST and GraphQL?

REST uses resource-oriented endpoints where each URL returns a fixed data representation. GraphQL uses a single endpoint (POST /graphql) where the client sends a query document declaring the exact nested fields required (e.g. avatar, post body, comment authors).

Is the REST network waterfall always 5 serial roundtrips?

No. The visualizer illustrates a deliberately naΓ―ve serial implementation for comparison. In production, request count does not equal critical-path turns: client-side Promise.all and HTTP/2 multiplexing allow sibling requests (like comments for 3 posts) to run in parallel (reducing 5 turns to 3), while Bulk endpoints or a Backend-For-Frontend (BFF) can collapse requests into a single tailored roundtrip.

How does GraphQL avoid over-fetching?

The client specifies the exact fields it needs in the query document (such as name, avatar, title, body, and comment author). The GraphQL engine strips unrequested database fields before returning the response.

How does DataLoader solve backend N+1 fanout in GraphQL?

DataLoader consolidates individual resolver lookups within a single event loop tick into a batched SQL query using an IN clause (e.g. SELECT * FROM comments WHERE post_id IN (101, 102, 103)), preventing N+1 database queries on internal networks.

When should an engineering team choose REST over GraphQL?

REST is preferable for simple CRUD resources, heavy CDN edge caching (via native HTTP GET/ETag semantics), file uploads, and public APIs. GraphQL excels when multi-platform clients require diverse, rapidly evolving nested UI views without creating bespoke BFF endpoints.