Skip to content

No. 43API8 min read2,082 words

GraphQL vs REST: when GraphQL is the right call

GraphQL vs REST for product teams: when GraphQL earns its keep, what it costs in N+1 queries, caching and security, and when REST or tRPC is the better pick.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways · 05

The short version

  1. 01GraphQL is the right call when several different clients need different slices of a deeply relational domain, and the teams building those clients should not have to wait on backend changes.
  2. 02For one web app built by the team that owns the backend, REST, tRPC or React Server Components reading data directly usually deliver the same type safety with far less machinery.
  3. 03Every GraphQL relationship needs batching with a per-request DataLoader, or a list of 50 items fires 51 database queries.
  4. 04GraphQL loses free HTTP caching because queries usually travel as POST to one endpoint; persisted queries sent over GET are the main way to get CDN caching back.
  5. 05A public GraphQL API needs depth limits, query cost analysis, timeouts and cost-based rate limiting before launch, because any client can write an expensive query.
On this page · 09

GraphQL is the right call when several different clients, such as a web app, mobile apps and partners, need different slices of a deeply relational domain, and you want them to get exactly the data they need without a new backend endpoint for every screen. It is the wrong call for a single frontend over mostly flat CRUD resources, where REST, tRPC or Server Components give you the same type safety with much less to maintain.

GraphQL gets pitched as the grown-up way to build an API, and REST as the thing you settle for. That framing has cost a lot of teams a lot of weekends. The useful question is not "is GraphQL better" but "does our situation actually look like the problem GraphQL was built to solve". Here is how we answer it.

What GraphQL is, in one paragraph

GraphQL is a query language and runtime for APIs. You publish a typed schema describing your data as a graph of types and relationships. Clients send a query naming exactly the fields they want, nested as deeply as the schema allows, and get back JSON in exactly that shape. Everything typically goes through a single endpoint. On the server, each field is backed by a resolver function that knows how to fetch it.

That design gives clients enormous flexibility. It also moves a lot of decisions that REST makes at design time (what data, what shape, how expensive) to runtime, chosen by whoever writes the query.

What GraphQL is actually good at

GraphQL came out of Facebook's need to serve mobile clients on unreliable networks that pulled deeply nested, client-specific data. That is still where it shines. When many consumers want different shapes of the same underlying graph, GraphQL lets each one ask for exactly what it needs in a single round trip.

Concretely, GraphQL earns its keep when:

  • You have a highly relational domain where a single screen needs data from five or six entities, and those combinations differ a lot per screen.
  • You have multiple distinct clients with different data needs, and you do not want to ship a new backend endpoint every time a UI changes.
  • Over-fetching and round trips are real costs, for example a mobile client on a flaky connection where every extra request hurts.
  • Many teams contribute to one API. A shared schema becomes the meeting point, and federation lets separate services own separate parts of the graph.
  • You want a strongly typed contract with introspection and code generation built in.

That last point is underrated. A typed schema plus generated TypeScript types means the compiler catches a whole category of frontend bugs before they ship. It is real value, and it is why some teams adopt GraphQL even when the network arguments do not apply. Just know that it is not unique to GraphQL any more.

GraphQL vs REST vs tRPC at a glance

RESTGraphQLtRPC
Shape of responsesFixed by the server per endpointChosen by the client per queryFixed by the server per procedure
Type safetyVia OpenAPI and codegenBuilt-in schema, plus codegenInferred end to end, TypeScript only
HTTP cachingWorks out of the box with GETNeeds persisted queries over GETPossible for queries over GET
N+1 riskLow, you write the queryHigh, needs DataLoader everywhereLow
Security surfaceBounded by what each endpoint returnsAny client can compose expensive queriesBounded
Multiple languages and clientsExcellentExcellentTypeScript clients only
Best fitPublic APIs, CRUD, partner integrationsMany clients, relational data, many teamsOne TypeScript team, one or two apps

What GraphQL costs you

None of the benefits are free. Here is the bill.

N+1 queries become your full-time job

The flexibility that lets clients ask for nested data is the same flexibility that can flatten your database. A query for 50 posts, each asking for its author, naively fires 1 query for the posts and 50 more for the authors. The standard fix is DataLoader, which batches all lookups requested in one tick into a single query and caches them for the rest of the request. You have to wire it up for every relationship.

import DataLoader from "dataloader";
import { db } from "./db";
 
// Batches all author lookups in a single tick into one SQL query.
function createUserLoader() {
  return new DataLoader<string, User>(async (ids) => {
    const users = await db.user.findMany({
      where: { id: { in: [...ids] } },
    });
    // DataLoader requires results in the same order as the input keys.
    const byId = new Map(users.map((u) => [u.id, u]));
    return ids.map((id) => byId.get(id) ?? new Error(`No user ${id}`));
  });
}
 
// Create loaders per request, inside your server's context function.
export function createContext() {
  return { loaders: { user: createUserLoader() } };
}
 
const resolvers = {
  Post: {
    // Without the loader, this runs once per post: the classic N+1.
    author: (post: Post, _args: unknown, ctx: Context) =>
      ctx.loaders.user.load(post.authorId),
  },
};

Create a fresh loader per request so the cache does not leak between users. Forget that, and you have shipped a data-privacy bug. Batching also needs the right indexes behind it: a batched lookup by primary key is cheap, but a loader for a reverse relationship, such as WHERE author_id IN (...) to fetch each author's posts, scans the table unless that foreign key column is indexed; our guide to database indexing for app developers covers that side. This is table stakes, and it is overhead you simply do not have with a hand-written REST endpoint that issues one deliberate JOIN.

Caching gets harder

With REST, HTTP caching just works. A GET /posts/42 is cacheable by the browser, a CDN and a reverse proxy, keyed by URL, using the standard rules MDN's HTTP caching guide describes. GraphQL typically sends everything as a POST to one /graphql endpoint, so all of that free infrastructure stops helping.

The workarounds are well understood:

  • Persisted queries. The client sends a hash of a pre-registered query instead of the query text, over GET. Now each query has a stable URL a CDN can cache, and as a bonus the server can refuse any query it has not seen before.
  • Normalised client caches such as Apollo Client or urql, which store objects by ID and update every view that shows them.
  • Server-side caching of resolver results or whole responses, often in Redis, with invalidation you have to design yourself.

It is all solvable, but you are rebuilding caching you used to get for nothing.

Every client can write a query that hurts you

A public or partner-facing GraphQL endpoint invites deeply nested, expensive queries, whether by accident or on purpose. The GraphQL security guidance and OWASP's GraphQL cheat sheet both list the same baseline: depth limiting, query cost analysis, pagination limits on every list field, timeouts, and disabling introspection where the schema is not meant to be public.

import { ApolloServer } from "@apollo/server";
import depthLimit from "graphql-depth-limit";
 
const server = new ApolloServer({
  schema,
  validationRules: [depthLimit(7)],
  introspection: process.env.NODE_ENV !== "production",
  // Plus per-field cost analysis and a hard request timeout in production.
});

Request-count rate limiting is not enough on its own, because one GraphQL request can cost a thousand times more than another. Rate limit by calculated query cost instead. GitHub's GraphQL API rate limits are a good public example of a points-based model.

Authorization also needs more care. In REST, you check access once per endpoint. In GraphQL, any field can be reached from many paths through the graph, so access checks belong in the business logic layer that resolvers call, not in the resolvers themselves, which is exactly what the official GraphQL authorization guidance recommends.

Uploads, errors and observability are awkward

GraphQL handles file uploads awkwardly; most teams send files directly to object storage with signed URLs, as we describe in handling file uploads safely. Errors usually come back with a 200 status and an errors array, so HTTP-level monitoring sees everything as success. And "POST /graphql is slow" tells you nothing: you need per-operation tracing to know which query is the problem.

Where Server Components change the calculus

A lot of GraphQL adoption in web teams was really about one thing: letting the frontend fetch exactly the data a page needs without waiting for a backend endpoint. In a Next.js App Router app, React Server Components already do that. A server component can query your database or internal services directly, on the server, and send only the rendered result to the browser.

That removes the over-fetching and round-trip arguments for your own web app almost entirely. We go into the patterns in data fetching in React Server Components. GraphQL still makes sense alongside it if you also serve native mobile apps or partners from the same API, or if you consume someone else's GraphQL API, such as a headless commerce platform.

When REST or tRPC is the better call

Reach for plain REST or a typed RPC layer when:

  • Your API is mostly CRUD with predictable, stable resource shapes. If GET /invoices/:id returns roughly the same fields every time, GraphQL's flexibility is solving a problem you do not have.
  • You have one frontend built by the same team that owns the backend. You can add the exact endpoint you need faster than you can maintain a schema, resolvers and loaders.
  • HTTP caching matters, for example a content-heavy site where CDN caching is the whole performance strategy.
  • It is a public API for third parties, who generally expect REST, predictable rate limits and OpenAPI docs.
  • You are doing file uploads, streaming or binary payloads.

For a TypeScript team with a single Next.js frontend, tRPC is a sweet spot worth naming. It gives you end-to-end type safety (the thing most teams actually wanted from GraphQL) without a schema language, without resolvers and without the N+1 footguns. You write a backend function, you call it from the client, and the types flow through.

// server: the procedure is just a typed function
export const appRouter = router({
  getInvoice: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(({ input }) => db.invoice.findUnique({ where: { id: input.id } })),
});
 
// client: fully typed, no codegen step, no query language
const invoice = await trpc.getInvoice.query({ id: "inv_123" });

If your real goal was "our frontend and backend types should match", tRPC, Server Actions, or REST with a generated OpenAPI client gets you there with a fraction of the moving parts.

A decision framework you can actually use

Skip the religion. Answer four questions about your project:

  1. How many different clients consume this API, and how different are their data needs? One client with stable needs leans REST, tRPC or Server Components. Several clients with very different needs leans GraphQL.
  2. Who owns the frontend and backend? One team that owns both can ship endpoints on demand and rarely needs GraphQL's decoupling. Many independent teams or external consumers benefit from a self-serve typed graph.
  3. Is the data deeply relational, or mostly flat resources? Deep graphs sliced differently per screen are GraphQL's home turf. Flat CRUD is not.
  4. Do you have the capacity to run it well? Loaders on every relationship, cost limits, persisted queries and per-operation monitoring are ongoing work, not a one-off setup.

If you land on GraphQL, commit to the operational work up front:

  • A per-request DataLoader for every relationship
  • Depth limits, cost analysis and timeouts before launch
  • Cursor pagination with a maximum page size on every list field
  • Persisted queries, or a clear alternative plan for caching
  • Authorization in the business layer, not scattered across resolvers
  • Per-operation tracing and error monitoring

If you land on REST or tRPC, do not feel like you settled. You probably avoided a pile of complexity you would have spent the next year managing.

Choose the option that leaves you less to maintain

GraphQL is a specialised tool for relational data served to many different clients, not a default upgrade over REST. Pick it when your problem looks like the problem it solves, and reach for REST, tRPC or Server Components when you mostly need typed, predictable data for one app. The lazy move, in the good sense, is choosing the option that leaves you less to maintain.

When GraphQL is the right fit, we design schemas, loaders and limits properly from the start as part of our GraphQL API development work. If you are mid-decision or mid-migration, send us your use case and we will look at your actual schema and traffic before you commit.

FAQ · 05 questions

Frequently asked questions

Is GraphQL better than REST?

Neither is better in general. GraphQL is better when many clients need flexible, nested views of related data in one round trip. REST is better for stable, resource-shaped APIs, public APIs that benefit from HTTP caching, and teams that want fewer moving parts. Many products use both.

Is GraphQL faster than REST?

Not inherently. GraphQL can reduce the number of round trips and the size of responses for clients that need nested data, which helps on slow mobile networks. On the server it adds parsing, validation and resolver overhead, and naive resolvers can be much slower than a single hand-written SQL query. Speed depends on implementation, not the protocol.

What is the N+1 problem in GraphQL?

It happens when a resolver for a list fetches each item's related data separately. Fetching 50 posts and then each post's author issues 1 query for the posts and 50 for the authors. The standard fix is DataLoader, which collects all the IDs requested in one tick and loads them in a single batched query.

Can you cache GraphQL responses?

Yes, but not as easily as REST. Client libraries like Apollo Client and urql keep a normalised cache in the browser. For CDN caching, use persisted queries sent as GET requests so each query has a stable URL. Server-side, you can cache resolver results or whole responses in Redis with careful invalidation.

Should I use GraphQL with Next.js?

Often not for your own Next.js frontend. Server Components can query your database or services directly on the server, which removes most of the over-fetching and round-trip problems GraphQL was designed to solve. GraphQL still makes sense if you also serve mobile apps or partners from the same API, or if you consume a GraphQL API such as a headless commerce platform.

Filed underAPIBackend

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1–2 weeks
Pricing
Fixed price per phase
You own
All code and accounts