Back to results for “Performance Optimization & Profiling”
Node.js › GraphQL with Node.js

What is over-fetching and under-fetching in REST APIs, and how does GraphQL specifically address both?

Intermediate

Answer

Over-fetching happens when a REST endpoint returns more data than the client actually needs (like a full user object when the client only wanted the name), wasting bandwidth. Under-fetching happens when a single REST endpoint doesn't return enough related data, forcing the client to make several additional round-trip requests to gather everything it needs (like fetching a post, then separately fetching its author, then separately fetching the author's other posts). GraphQL addresses both by letting the client specify exactly which fields and nested relationships it wants in a single request, receiving precisely that shape of data back and nothing more.
# A single GraphQL query fetches exactly what's needed, nested, in one round-trip
query {
  post(id: "1") {
    title
    author { name, avatarUrl }
  }
}
# Compare to REST: GET /posts/1, then GET /users/{authorId}, then GET /users/{authorId}/avatar -- multiple round-trips
Real-world example A mobile app with a limited-bandwidth user base switches its post-detail screen from three separate REST API calls (fetching the post, then the author, then the author's follower count) to a single GraphQL query requesting exactly those three pieces of nested data together, reducing both the number of round-trips and the total bytes transferred.

Common follow-ups: What's the tradeoff GraphQL introduces in exchange for solving over/under-fetching, particularly around caching complexity compared to REST?;How do REST APIs sometimes address the same under-fetching problem using techniques like HTTP/2 server push or embedded/expanded resource query parameters?