GraphQL vs REST: GraphQL for Nested Data, REST for Caching

Neither one wins outright. Choose GraphQL when clients need flexible, nested data from several backends, as in mobile apps, dashboards and e-commerce front ends. Choose REST for public APIs, simple services and anywhere HTTP caching and familiar security patterns matter most. Many larger teams end up running both: GraphQL as a front-end aggregation layer, REST or another protocol between services.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

How GraphQL and REST differ in architecture

Both solve client-server communication, but from opposite directions. REST organizes data around resources, each reachable at its own URL. A typical e-commerce API might expose /api/products, /api/users and /api/orders. Each endpoint returns a structure the server defines, so the client gets the full payload every time. REST builds on standard HTTP methods, and as the HTTP request methods reference describes, those semantics are universally understood.

According to graphql.org, Facebook’s mobile apps have been powered by GraphQL since 2012, the specification was open-sourced in 2015, and the GraphQL Foundation has been hosted by the Linux Foundation since 2018. GraphQL is a query language for APIs and a server-side runtime built on a strongly typed schema, and it is not tied to a specific database. Instead of many endpoints, clients typically send structured queries to a single endpoint such as /graphql and specify exactly the fields they need. That removes over-fetching and under-fetching.

To show a user profile with recent orders, a REST client usually makes two calls, one to /api/users/123 and one to /api/users/123/orders. With GraphQL one query retrieves both in a single round trip:

query {
  user(id: "123") {
    name
    email
    orders(last: 5) {
      id
      total
      status
    }
  }
}

The type system is another dividing line. GraphQL APIs describe themselves through their schema, and every field and relationship can be queried through introspection. REST APIs rely on external description formats such as the OpenAPI Specification, and that documentation can drift from the implementation over time.

Performance, caching and payload size

GraphQL wins when one screen needs data from several related resources, because one round trip replaces several and the response carries only the requested fields. REST often matches or beats GraphQL on simple single-resource fetches, because the server skips query parsing, validation and per-field resolution.

FactorRESTGraphQLBetter fit
Complex page needing several resourcesSeveral callsOne callGraphQL
Simple single-resource fetchDirect, little server workParsing and validation overheadREST
Server CPU and memoryBaselineExtra work per queryREST
Payload size with selective fieldsFull payloadOnly requested fieldsGraphQL
Continuous updatesPolling or separate WebSocketSubscriptionsGraphQL
CachingNative HTTP cachingRequires a custom solutionREST
Bandwidth on mobileHigher because of over-fetchingLower with precise queriesGraphQL

Caching is the factor that most often decides the question. REST can use CDN caching out of the box: a Cache-Control header on a GET endpoint means repeat requests may never reach your server. GraphQL’s POST-based query model bypasses CDN caching by default. Persisted queries and GET-based execution can partly restore it, but they add complexity and limit the flexibility that makes GraphQL attractive.

The practical rule is to benchmark your own query patterns before committing. If most traffic is simple, read-heavy and cacheable, REST’s advantages compound. If each screen stitches together several resources over slow mobile connections, GraphQL’s saved round trips and smaller payloads usually outweigh the extra server work.

Feature comparison: GraphQL vs REST

FeatureRESTGraphQL
Data FetchingFixed endpoints, server-defined responseClient-defined queries, flexible response
EndpointsMultiple (one per resource)Single endpoint
Over-fetchingCommon (returns full resource)Avoided (client specifies fields)
Under-fetchingCommon (requires multiple calls)Avoided (nested queries)
Type SystemNone built-in (OpenAPI optional)Strong schema with SDL
Real-time DataPolling or WebSocket (separate)Subscriptions
CachingNative HTTP caching (ETags, CDN)Custom (persisted queries, normalized cache)
VersioningURL versioning (/v1/, /v2/)Schema evolution (deprecation directives)
Error HandlingHTTP status codes (400, 404, 500)Usually 200, errors in response body
File UploadNative multipart supportRequires multipart spec extension
AuthenticationStandard HTTP headers/OAuthStandard HTTP headers/OAuth
API DocumentationExternal (OpenAPI/Swagger)Built-in introspection
Tooling MaturityDecades of tools (Postman, cURL)Growing (GraphiQL, Apollo Studio)
Learning CurveLow (HTTP fundamentals)Moderate (SDL, resolvers, schema design)
FederationAPI Gateway patternFederation (Apollo, WunderGraph)
Batch OperationsCustom implementationQuery batching

API evolution is one of the biggest practical differences. REST traditionally uses URL versioning, which can mean maintaining several parallel versions. GraphQL marks fields as deprecated with a reason and adds new fields without breaking existing queries. That lowers maintenance burden but needs disciplined schema governance to stop the schema growing without limit.

Error handling also differs. REST maps errors to HTTP status codes, which integrate cleanly with monitoring tools and load balancers. GraphQL typically returns HTTP 200 and puts error details in the response body’s errors array. Errors can therefore be partial: some fields resolve while others fail. That is more flexible but demands more careful client-side handling, and it complicates standard monitoring and audit logging.

Security: attack surfaces and mitigation

REST keeps an edge here because its attack surface is simpler. GraphQL’s flexibility adds challenges teams must address deliberately.

Query complexity attacks are the main GraphQL-specific risk. Because clients can build arbitrarily nested queries, a malicious one can consume heavy server resources, for example friends of friends of friends in a social API. REST endpoints return what the server defines, so this risk is largely absent. Mitigations include query depth limiting, query cost analysis that assigns a cost to each field and rejects queries over a threshold, and persisted queries that allow only pre-approved shapes in production.

Introspection exposure is another risk. By default a GraphQL API can reveal its entire schema, giving attackers a map of data and operations. Disable introspection in production. REST APIs do not inherently expose their structure.

Authorization complexity grows because field-level access control is harder than endpoint-level control. In REST you can restrict a whole endpoint such as /api/admin/users. In GraphQL the same User type may be reachable through several paths, so authorization has to be enforced in resolvers for each field. That model is more powerful and more error-prone.

Both share common web API risks such as injection, broken authentication and rate-limiting challenges. GraphQL’s single endpoint means fewer endpoints to protect but makes endpoint-specific rate limits harder. REST benefits from long-established WAF rules and monitoring built around HTTP endpoints. Teams shipping GraphQL should treat depth limits, cost analysis and disabled introspection as launch requirements, not later hardening.

Developer experience and tooling

REST’s developer experience rests on simplicity. Any HTTP client, from cURL to Postman to a browser address bar, can call a REST API. Testing means sending a request, checking the status code and validating the body, and browser DevTools show each request clearly.

GraphQL’s experience is richer but more involved. The introspective type system enables IDE auto-completion, generated documentation and compile-time query validation with TypeScript. Tools like Apollo GraphOS cover schema management and governance of GraphQL and REST APIs, and GraphiQL lets developers explore an API interactively with schema-powered suggestions. Code generators such as GraphQL Code Generator produce TypeScript types, React hooks and client code from the schema, so a typo in a field name becomes a compile error instead of a runtime failure. OpenAPI code generators offer similar type safety for REST, though the workflow is less tightly integrated.

For full-stack TypeScript teams, tRPC is a third option. It gives end-to-end type safety with a simpler mental model: you define procedures instead of schemas. It is a narrower tool than GraphQL and fits only when both client and server are TypeScript. The trade-off is that GraphQL’s autocompletion and typing help daily work, but debugging a production performance problem is easier with plain endpoints, clear status codes and simple logging.

Cost and infrastructure

Both paradigms run on the same HTTP infrastructure, but their resource patterns differ. GraphQL servers do extra work per request for parsing, validation and resolution, which can raise compute cost. GraphQL can also cut bandwidth and request counts by removing over-fetching and consolidating calls, which matters for mobile-heavy apps and for request-based API gateway pricing.

Cost FactorRESTGraphQLNotes
Compute (CPU)BaselineHigherQuery parsing and resolution overhead
BandwidthHigher (over-fetching)Lower (precise queries)Matters most on mobile
API Gateway CostsHigher request countLower request countFewer calls with GraphQL
Caching (CDN)Free via HTTP cachingCustom caching requiredREST CDN caching can remove server load entirely
Team TrainingLow (familiar paradigm)Moderate (schema design, resolvers)GraphQL requires specialized knowledge
Tooling LicensesMostly freeVaries by vendorEnterprise GraphQL tooling can carry licensing costs
MonitoringStandard APM toolsSpecialized GraphQL monitoringApollo Studio, GraphQL Inspector, etc.
MaintenanceLower (simpler architecture)Higher (schema governance)GraphQL schemas need ongoing upkeep

Caching is the biggest cost differentiator, since a cached REST response costs almost nothing to serve. For teams already on REST, migration is non-trivial: you need people who understand schema design, resolver patterns and N+1 prevention. A sensible test is to compare the compute you would add against the bandwidth and request volume you would remove. If your traffic is mostly cacheable reads, the comparison favors REST. If it is mostly uncacheable, personalized, multi-resource requests, it can favor GraphQL.

Who uses what, and which to pick for each use case

GraphQL has moved well beyond its Facebook origin. graphql.org lists Meta, AWS, Airbnb, Intuit, IBM, The New York Times, Starbucks, Shopify and GitHub among its users. Large organizations commonly run both styles side by side, which is why the practical question is which fits each use case.

Use cases that favor GraphQL

Mobile applications: constrained bandwidth rewards selective field querying, which cuts data transfer and improves perceived speed. Use persisted queries to shrink requests further.

Complex dashboards and admin panels: dashboards aggregate many sources, and fetching related data in one query reduces waterfall calls and simplifies front-end code. Combine it with normalized client-side caching.

E-commerce platforms: commerce data is nested and relational, with products that have variants, variants that have prices and prices that depend on regions. GraphQL models those relationships naturally, and federation can split the schema across product, inventory and order services.

Use cases that favor REST

Public APIs for third-party developers: these need discoverability, simplicity and cacheability. REST maps to HTTP semantics every developer knows, CDN caching works natively, and rate limiting is simple per endpoint.

Microservices communication: service-to-service traffic prioritizes throughput, latency and simplicity. REST fits, and gRPC is worth considering for maximum performance. A common pattern is gRPC or REST between services with GraphQL only at the front end.

Payment and regulatory systems: these need predictable behavior, clear audit trails and well-understood security patterns. REST’s status codes and idempotent methods suit them, while GraphQL’s partial-success responses complicate audit logging.

When to consider tRPC or both

If your front end and back end are both TypeScript, tRPC gives compile-time validation and type-safe calls without GraphQL’s operational overhead. If your organization operates at scale with several teams, use GraphQL as a front-end aggregation layer backed by REST or gRPC services. This hybrid gives clients flexible fetching while keeping service-to-service traffic simple and cacheable. For a new project, start from the use case rather than the trend: pick GraphQL for the client-facing, multi-source parts, and keep REST for everything that benefits from caching and simplicity. More software coverage on Tech Insider is available if you are comparing frameworks.

Migrating from REST to GraphQL in phases

If GraphQL fits part of your stack, an incremental gateway approach avoids a rewrite and keeps existing REST clients working. The week ranges below are planning estimates for a mid-sized application. The key sequencing point is to put DataLoader and query limits in place before opening the gateway to production traffic.

Phase 1: Schema design (weeks 1-2)

Map existing REST resources to GraphQL types. Each resource such as /api/users becomes a type, and relationships such as a user’s orders become fields. Mirror your existing REST structure first and do not redesign the data model during migration. Here a user has many orders:

type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  total: Float!
  status: OrderStatus!
  createdAt: DateTime!
}

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
}

Phase 2: Gateway layer (weeks 2-4)

Deploy a GraphQL gateway in front of your existing REST services, with each resolver calling the matching REST endpoint. This “strangler fig” pattern migrates incrementally without rewriting backends. Apollo Server, Mercurius (for Fastify) and Yoga (from The Guild) are common gateway choices.

// GraphQL resolver calling existing REST API
const resolvers = {
  Query: {
    user: async (_, { id }) => {
      const response = await fetch("https://api.internal/users/" + id);
      return response.json();
    },
  },
  User: {
    orders: async (parent) => {
      const response = await fetch(
        "https://api.internal/users/" + parent.id + "/orders"
      );
      return response.json();
    },
  },
};

Phase 3: Optimization (weeks 4-8)

Add DataLoader to batch and cache REST calls from resolvers. Without it, a query for 10 users and their orders generates 10 + 10 = 20 REST calls. With it, that collapses to 2 calls, one batch for users and one for orders. This is the most important optimization for GraphQL APIs backed by REST services. Also add query depth limiting and cost analysis to prevent abuse.

// DataLoader prevents N+1 queries
import DataLoader from 'dataloader';

const orderLoader = new DataLoader(async (userIds) => {
  // Single batch REST call instead of N individual calls
  const response = await fetch(
    "https://api.internal/orders?userIds=" + userIds.join(",")
  );
  const orders = await response.json();
  // Map results back to input order
  return userIds.map(id => orders.filter(o => o.userId === id));
});

Phases 4 and 5: Direct data access and federation

Direct data access (weeks 8-16): gradually replace REST-backed resolvers with direct database or service calls. This removes the double serialization of database to REST JSON to GraphQL response. Start with the highest-traffic resolvers.

Federation (optional, week 16 onward): if several teams own different services, federation lets each define its part of the schema independently while a gateway composes them into one graph. Only take this step when team boundaries, not just traffic, justify the added moving parts.

Sofia Lindström

Sofia Lindström

Security and privacy

Sofia Lindström writes about security and privacy for Tech Insider: software vulnerabilities and the updates that fix them, data breaches, privacy rules and how products handle personal data. She works from vendor advisories, official vulnerability catalogues and the documents behind each story.

View all articles