Skip to content
Eduardo Lira

GRAPHQL

GraphQL without mystery: what it is, how it works and what changes compared to REST

From scratch: what a gateway is, what GraphQL is, what a schema, a query and a resolver are, and what it solves and makes worse compared to REST. With diagrams and the real example from my capstone.

My capstone was a GraphQL gateway in Python in front of REST microservices. Every word in that sentence calls for another explanation: what is a gateway? And GraphQL? And why not just keep REST? This series, Capstone fundamentals, answers those questions from the start, with the project’s real code, in the order it was built. It begins with the most basic: the problem the gateway solves.

The problem: one screen, three services

In the capstone, the system had three microservices, each with its own data and REST endpoints: Users, Orders and Products. A microservice is a small, independent program that takes care of one part of the business and talks to the others over the network.1

Now picture a screen that shows the users, each user’s orders and the products in each order. With nothing in between, the browser has to talk to the three services:

Browser making 1 call to the Users service, 3 to Orders and 4 to Products
Without a gateway: with the capstone data (3 users, 3 orders, 4 products), the browser makes 8 calls to build one screen.

That is 8 trips over the internet: 1 for the user list, 1 for each user’s orders and 1 for each product. Each trip pays the network latency, the round-trip time to the server. On a phone, on a bad connection, you feel it.

What a gateway is

A gateway is a program that sits in front of the services and talks to the client on their behalf. Think of the reception desk of an office building: instead of going floor by floor looking for each room, you ask at the desk, and reception fetches everything and hands it over at once.

Browser making 1 request to the gateway, which talks to the three services over the internal network
With a gateway: the browser makes 1 request; the gateway talks to the services over the internal network, which is fast.

The gain comes from where each trip happens. The slow trip, over the internet, becomes a single one. The others happen between the gateway and the services, inside the same network, where each call costs much less. The pattern has a name in the microservices literature: API gateway.2

There is a variation often mentioned alongside GraphQL, the Backend for Frontend (BFF): instead of one gateway for everyone, one backend for each interface, one for the app and another for the website, each tailored to its own screens. The term came from SoundCloud and was popularized by Sam Newman in 2015.3 The capstone’s gateway is not a BFF: it’s a single one, with a schema that serves any client. And that’s exactly what GraphQL allows: since each client asks for the shape it needs, a single schema can play the role of several BFFs.

The capstone’s gateway was written in Python, with FastAPI (opens in a new tab) (the web server) and Strawberry (opens in a new tab) (the GraphQL library). And it speaks GraphQL to the client.

What GraphQL is

GraphQL is a query language for APIs and a specification of how a server must answer it. It was created at Facebook in 2012, open-sourced in 2015, and is now maintained by the GraphQL Foundation.4

The core idea fits in one sentence: the client says exactly which data it wants, and the response comes back in the same shape as the request. Three pieces make it work.

1. The schema: the contract

The schema describes everything that can be requested: the types, the fields of each type and how they connect. A simplified version of the capstone’s schema:

type Produto {
  nome: String!
  preco: Float!
}

type Pedido {
  id: ID!
  produtos: [Produto!]!
}

type Usuario {
  nome: String!
  pedidos: [Pedido!]!
}

type Query {
  usuarios: [Usuario!]!
}

String, Float and ID are basic types. The ! means “never empty”. [Produto!]! is a list of products. Query is the entry point: everything that can be queried starts there. (The names are in Portuguese, as in the capstone: usuario is user, pedido is order, produto is product.)

2. The query: the request

The client writes a query in the shape it wants to receive. For the example screen:

query {
  usuarios {
    nome
    pedidos {
      id
      produtos {
        nome
        preco
      }
    }
  }
}

And the response comes in the same shape, just filled in (illustrative values):

{
  "data": {
    "usuarios": [
      {
        "nome": "…",
        "pedidos": [{ "id": "…", "produtos": [{ "nome": "…", "preco": 0 }] }]
      }
    ]
  }
}

Nothing more, nothing less. If the screen doesn’t show the price, just remove preco from the query, and it doesn’t travel.

3. Resolvers: who fetches each piece of data

For each field in the schema there is a function, the resolver, that knows how to fetch that data. The usuarios resolver calls the Users service; the pedidos resolver, the Orders service; and so on.

Flow: query, validation against the schema, execution with one resolver per field, and a JSON response
How a GraphQL server handles a query. If validation fails, no resolver runs.

The server does four things, in this order:

  1. Receives the query text, almost always in a POST to a single address, such as /graphql.
  2. Validates the query against the schema: a field that doesn’t exist, a wrong type or a query that is too big are rejected here, before any data access.
  3. Executes, calling the resolvers from top to bottom, like walking a tree.
  4. Responds with JSON in the shape of the query.

Step 3 hides GraphQL’s most famous trap: the produtos resolver runs once for each order. If each run makes a network call, the number of calls grows with the size of the lists. That is the N+1 problem, the subject of a whole post in the capstone series.

What changes compared to REST

REST is not a technology, it is an architectural style, described by Roy Fielding in 2000: each resource has an address (/usuarios, /pedidos/42) and the client uses HTTP verbs on them.5

REST GraphQL
Addresses one per resource usually a single one (/graphql)
Who decides the fields the server the client
Too much or too little data common (overfetching and underfetching, explained below) the client asks for what it needs
Several entities on one screen several requests one request
HTTP caching natural (GET per address) harder (POST with a body)
Errors HTTP status code (404, 500…) almost always 200, with errors in the body
Cost of a call predictable from the URL depends on the query

Too much data and too little data

Two English expressions show up in every discussion about GraphQL:

  • Overfetching is receiving data the screen doesn’t use. In the capstone, GET /produtos/101 returns id, nome and preco. If the screen only shows the name, the rest travels for nothing. With three fields that’s little; in a real API a resource often has dozens of fields, and the waste grows.
  • Underfetching is receiving too little data and needing another call. In the capstone, GET /pedidos returns only the IDs of each order’s products, not the products. To show the name and the price, the client has to call the Products service again, once for each product. The 8 calls in Figure 1 are exactly that.

With GraphQL, both disappear from the client’s point of view: it asks for exactly the fields it wants, and the links (order → products) come in the same response.

GraphQL’s price

The last two rows of the table are GraphQL’s price. Since the client builds the query, a query that is small as text can be expensive on the server, and the cost doesn’t show in the URL. That is why a GraphQL server needs its own defenses: depth limits, cost analysis and rate limiting. They also get posts in the series.

Academic research measured both sides. Brito, Mombach and Valente migrated seven systems from REST to GraphQL and saw the JSON documents shrink by 94% in number of fields and 99% in bytes (medians).6 In a controlled experiment with 22 students, Brito and Valente saw queries done in 6 minutes with GraphQL against 9 with REST (medians), with a bigger gap on the more complex REST endpoints.7 That doesn’t mean GraphQL is always better: it means it trades one kind of cost for another.

The cache REST gets for free

A cache is a stored copy of a response, so it doesn’t have to be fetched again. On the web, it happens in several places: in the browser, on intermediate servers spread around the world (CDNs, content delivery networks) and on the server itself.

With REST, that cache comes almost for free. Each resource has an address, and GET /produtos/101 is always the same question. The server can answer with a header like Cache-Control: max-age=60 (“you may keep this for 60 seconds”), and the browser or the CDN store the response under that address. Next time, they don’t even ask the server.8

With GraphQL, everything goes to the same address, /graphql, almost always via POST, with the query in the request body. The web’s cache identifies responses by address and, in practice, doesn’t store POST responses. To it, two different queries look the same. That’s why this cache doesn’t work on its own.

There are ways out, each in a different layer:

  • In the client: libraries like Apollo Client store each object received by type and ID (Produto:101) and reuse it on other screens.
  • At the edge: persisted queries replace the query text with a short identifier, sent via GET. The URL identifies the question again, and the CDN works again.
  • In the gateway: the gateway can store the services’ responses. In the capstone, the services are REST, so the conversation between the gateway and the services still has addresses and could use the ordinary HTTP cache.

The capstone used no cache on either side, and that kept the comparison fair: neither the REST client nor the gateway reused responses. With a cache, the load test, which repeats the same queries all the time, would measure how often the cache hit, not the cost of the gateway, which was the capstone’s question.

Caching has its price too, even more so in a gateway. Stored data can go stale (the price changed, the stored response didn’t). Responses with one user’s data can’t go into a shared cache, or they leak to someone else. And since GraphQL answers 200 even when there’s an error, a careless cache stores errors as if they were good responses. In the capstone there was also the 1 GB limit per container: an in-memory cache would compete for space with the gateway itself.

Do the 8 calls still exist?

They do. The gateway doesn’t do magic: to build the response, it makes the same calls the browser would. What changes is where they happen and how much each one costs.

A round trip between machines in the same data center usually takes less than a millisecond. Over the internet, from a phone to the server, it takes tens or hundreds of milliseconds.9 The gateway trades 8 expensive trips for 1 expensive trip plus 8 cheap ones.

But “cheap” isn’t “free”. Each internal call still costs the gateway and the services time and processing. When lists grow, those calls multiply, and the gateway, which was there to help, becomes the bottleneck. That’s why DataLoader, which merges similar calls into one, was the most important piece of the capstone.

Who benefits

  • The people using the system: fewer trips over the internet and less data, which matters most on phones and bad networks.
  • The people building the interface (front end): the screen asks for data in the shape it needs, without waiting for someone to create a new endpoint for each screen.
  • The company: a single place for security rules, limits and metrics, without touching the services that already work.

The cost is the other side of the last item: that single place has to handle the load of every client and defend itself.

And in the capstone

In the capstone, the comparison was between the REST client making the 8 calls and the GraphQL gateway answering the same screen in one request. With the optimized gateway (DataLoader and an HTTP client that reuses connections), the two were practically tied in latency: from 18.7 to 41.7 ms for REST and from 20.8 to 43.5 ms for GraphQL, between 10 and 200 concurrent users. GraphQL pays the cost of interpreting the query and recovers it by trading 8 client calls for one.

What the capstone showed that is useful, in three sentences:

  1. Done well, the gateway doesn’t make the system slower: with DataLoader and reused connections, it tied with the REST client.
  2. Done badly, it collapses: without DataLoader, at 200 users, the average latency was 194 ms against 43 ms, and one request in twenty took more than half a second.
  3. The most cited defenses don’t always protect: the depth limit blocked nothing; cost analysis did.

One detail that has to be said: in the experiment, everything ran on the same machine, including the load generator. The advantage of making fewer trips over the internet did not enter the numbers. On a real network, it would add up in the gateway’s favor.

How this measurement was done, and what went wrong along the way, is in the capstone series, starting January 11, 2027.

Questions that may come up (and how I would answer)

Does GraphQL replace REST? No. In the capstone, the services stayed REST; GraphQL sat only at the edge, in the conversation with the client.

Why not call the services directly from the browser? Because each call over the internet is expensive, and the screen would need 8. The gateway concentrates those calls on the internal network.

If GraphQL solves the excess of calls, why does the N+1 problem exist? Because GraphQL solves the excess of calls from the client. The calls don’t disappear: they move from the browser to the gateway. There each one is cheaper, but if the code makes one call per item in the list, their number grows with the size of the data. DataLoader merges those calls into one.

So the internal calls cost nothing? They do cost. They’re cheaper than internet calls, but they take time and processing. Without DataLoader, at 200 users, they were what brought the gateway down.

Who gains from the GraphQL gateway? The user (fewer trips and less data), the people building the interface (they ask for the screen’s shape) and the company (a single place for security and metrics). The price is that this single place has to be well built and well protected.

Is REST better because it has caching? In some cases. For public, repeated data, like a catalog seen by thousands of people, REST’s address-based cache is a real advantage. For per-user data, like “my orders”, which can’t go into a shared cache, the advantage almost disappears. And part of it can be recovered in GraphQL, with persisted queries and client-side caching.

Is the capstone’s gateway a BFF? No. A BFF is built for one specific interface; the capstone’s gateway is a single one, for any client. It’s an aggregation gateway: it combines the responses of several services into one.

What is the main drawback? The cost of each request stops being predictable. A public GraphQL server needs to limit what it accepts.

Glossary

  • Cache: a stored copy of a response, so it doesn’t have to be fetched again.
  • CDN: a network of servers spread around the world that keep copies of content close to whoever accesses it.
  • API: the way a program offers its data and functions to other programs.
  • Latency: the round-trip time of a call over the network.
  • Microservice: a small, independent program that takes care of one part of the system.
  • Gateway: a program in front of the services that serves the client on their behalf.
  • Schema: the description of everything the GraphQL API offers.
  • Resolver: the function that fetches the data for a field.

References

Academic:

Documentation:

Notes

  1. The definition I use is Sam Newman’s: small, independent services organized around one part of the business. ↩

  2. Newman, S. Building Microservices. 2nd ed. O’Reilly, 2021. Chapters on API gateway and Backend for Frontend. ↩

  3. Newman, S. Pattern: Backends For Frontends (opens in a new tab). 2015. The text credits the pattern’s origin to SoundCloud. ↩

  4. GraphQL specification (opens in a new tab). The formal semantics was studied in Hartig, O.; Pérez, J. Semantics and Complexity of GraphQL (opens in a new tab). WWW, 2018. ↩

  5. Fielding, R. T. Architectural Styles and the Design of Network-based Software Architectures (opens in a new tab). PhD dissertation, UC Irvine, 2000. Chapter 5. ↩

  6. Brito, G.; Mombach, T.; Valente, M. T. Migrating to GraphQL: A Practical Assessment (opens in a new tab). SANER, 2019. ↩

  7. Brito, G.; Valente, M. T. REST vs GraphQL: A Controlled Experiment (opens in a new tab). ICSA, 2020. ↩

  8. MDN: HTTP caching (opens in a new tab). On the GraphQL case, the Caching (opens in a new tab) page in the official documentation. ↩

  9. These are orders of magnitude, not capstone measurements. The classic table is Jeff Dean’s, “Latency numbers every programmer should know” (opens in a new tab): a round trip within the same data center, about 0.5 ms. ↩

Who writes this

Eduardo Lira

I'm a software developer in Rio de Janeiro. I started this blog in 2012, in technical support at a hosting company, so I wouldn't have to figure out the same thing twice. Today, at Sofis Tecnologia, I build and maintain critical healthcare systems, focusing on SQL Server, data integration and legacy system migration.

Found a mistake in this post?

A command that no longer works, a broken link, wrong information: tell me what you saw. The message goes only to the author and is not shown on the site.