Library / Documentation

Learn GraphQL

The official introduction to queries, schemas and resolvers.

BeginnerAPI Gateway

By GraphQL Foundation · GraphQL · Added 2026-10-12

Open the docs

All content belongs to GraphQL Foundation / GraphQL. We only link to it and give credit. Report a problem

Learn this doc

About 30 min left. Your work is saved as you go.

What you want from these docs

GraphQL documents a tool you may use. Decide what you want to do with it, then read only what answers that.

Ideas you will meet

API Gateway
A single entry point for routing, auth and throttling.

What we already know about this

Our own lessons on these ideas. Read them here before you start, so it makes sense.

  • Advanced Distributed Systems · 12 minLoad balancing: layer 4, layer 7 and gatewaysWhat a load balancer can see and do at each layer, the algorithms behind it, and how API gateways add routing, aggregation and policy.Read here

    What a load balancer sees

    A load balancer spreads incoming work across servers, removes failed servers and makes scaling invisible to clients. What it can do depends on which layer it works at.

    Layer 4 (transport)Layer 7 (application)
    SeesIP addresses, ports, TCP/UDP connectionsHTTP method, URL, headers, cookies, body
    Decides byConnection detailsRequest content
    TLSPasses through, or terminates in some productsUsually terminates TLS
    Speed and costVery fast, low overheadMore work per request
    Typical featuresSpread connections, health checksPath routing, header rules, sticky sessions, rewrites, caching, WAF rules
    ExamplesNetwork load balancers, LVS, HAProxy in TCP modeNGINX, Envoy, HAProxy HTTP mode, cloud application balancers

    Figure SDA-ADS-05-1 · Layers of balancing in front of an app · © forcsguy.com

    Many designs use both: an L4 tier for raw scale and an L7 tier for smart routing.

    Before: layer 4: ports and addresses

    After: layer 7: reads the request

    What changed

    • Layer 7 can route by path, header or cookie
    • Layer 7 can terminate TLS and retry safely
    • Layer 4 is simpler and faster, with less to configure

    Choosing a target: algorithms

    • Round robin / weighted round robin: simple rotation; weights favour bigger machines.
    • Least connections (and weighted): send to the server with fewest active requests; good when requests vary in length.
    • Least response time: combine active load with measured latency.
    • IP hash / consistent hashing: the same client or key goes to the same server, useful for caches and sticky state (see consistent hashing).
    • Resource-based: servers report load and the balancer follows.

    Health checks (active probes and passive error tracking) remove unhealthy servers; connection draining lets in-flight requests finish before a server is removed during a deploy.

    Global and DNS balancing

    Across regions, DNS-based or global server load balancing directs users to the nearest or healthiest region (see the DNS and CDN lessons). DNS answers are cached, so failover takes as long as the TTL; anycast and global balancers react faster.

    API gateway: policy at the edge

    An API gateway is an L7 component specialised for APIs. Beyond routing it commonly provides:

    • Authentication and authorisation (validate tokens, apply scopes),
    • Rate limiting and quotas (see the rate-limiter lesson),
    • Request and response transformation, versioning, and protocol translation,
    • Aggregation: one client call fans out to several services and merges results, saving round trips for mobile clients,
    • Caching, logging, metrics and tracing in one place.

    Figure SDA-ADS-05-2 · Gateway routing and aggregation · © forcsguy.com

    Risks: the gateway is a single entry point (run several instances, keep it stateless) and can become a bottleneck or a place where business logic piles up. Keep it to cross-cutting concerns. A variation is a backend for frontend: one gateway per client type (web, mobile) tailored to its needs.

    Inside the cluster

    Between services, balancing is done by client-side libraries or sidecar proxies that know the healthy instances from service discovery, so no central balancer is needed for east-west traffic. See the microservices lessons for service mesh ideas.

    Failure habits

    • Run at least two of every balancer and gateway instance across zones.
    • Keep timeouts and retry budgets (see the resilience lesson) so the balancer does not amplify an outage.
    • Use slow start for new instances so they warm up before taking a full share.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Core Concepts: How Things Actually Work · 9 minSOAP, REST, GraphQL and gRPC comparedFour ways to build an API, what each is good at, and how to choose without following fashion.Read here

    The same job, four ways

    An API lets one program ask another to do something. The main styles differ in format, contract and how the client asks for data.

    SOAPRESTGraphQLgRPC
    FormatXML envelopesJSON (usually) over HTTPJSON over HTTP, one endpointBinary Protocol Buffers over HTTP/2
    ContractWSDL, very formalOpenAPI (optional)A typed schemaA .proto schema, required
    Client asks byCalling named operationsResource URLs and HTTP verbsSending a query describing the fields wantedCalling typed methods
    CachingHardNatural (HTTP caching)Harder (usually one POST endpoint)Not HTTP-cache friendly
    StreamingNoLimited (SSE, WebSockets separately)SubscriptionsBuilt in (four modes)
    Browser usePossible, heavyNativeNativeNeeds a proxy (gRPC-Web)
    Typical homeBanks, enterprise, older systemsPublic and general-purpose APIsClient-driven apps, mobileInternal service-to-service

    SOAP

    An older, XML-based protocol with a formal contract (WSDL) and a family of standards (WS-Security, transactions, reliable messaging). Verbose and tooling-heavy, but still common where strict contracts and built-in enterprise standards matter, such as banking, telecom and government. You will mostly meet it when integrating with existing systems.

    REST

    Design around resources identified by URLs (/orders/42), manipulated with standard HTTP verbs (GET, POST, PUT/PATCH, DELETE), and described with status codes. Strengths: simple, cacheable, works with every tool. Weaknesses: over-fetching (you get fields you do not need), under-fetching (several calls to assemble a screen), and no enforced schema unless you add one.

    Figure SDA-CORE-20-1 · Three ways to call an API · © forcsguy.com

    GraphQL

    A single endpoint and a typed schema. The client sends a query naming exactly the fields it wants, even across related objects, and receives exactly that shape. It removes over- and under-fetching and suits varied clients (web, mobile). Costs: query cost control (a client can ask for something expensive), more complex caching, and server complexity (resolvers, the N+1 problem solved with batching).

    gRPC (a form of RPC)

    Remote procedure call: call a method on another service as if it were local. gRPC uses Protocol Buffers (compact binary, generated typed clients in many languages) over HTTP/2 with streaming. It is fast and has strong contracts, which is why it is popular between internal services. It is awkward to call straight from a browser and harder to debug by eye.

    Choosing

    1. Who are the clients? Public developers and the broad ecosystem: REST. A few first-party apps with varied screens: GraphQL. Your own services: gRPC. A partner or legacy system: whatever they provide, often SOAP.
    2. How sensitive is performance and payload size? Internal high-volume calls favour gRPC.
    3. Do you need HTTP caching? REST makes it easy.
    4. Do you need streaming? gRPC, or WebSockets and server-sent events.
    5. Team skills and tooling: the best style is one your team can run well.

    Many systems mix styles: REST publicly, gRPC internally, and GraphQL as a gateway layer over both.

    Good habits in any style

    • Version the API and avoid breaking changes.
    • Use consistent errors and clear status codes.
    • Paginate lists, and make unsafe operations idempotent with keys.
    • Document with a machine-readable schema (OpenAPI, GraphQL SDL, .proto).
    • Apply authentication, authorisation and rate limits at the edge (see the API security lesson).

    Real-world reading

    Open this lesson with its quiz and exercise

Go deeper on this

A path through videos, articles, other case studies and code on the same ideas as Learn GraphQL.

  1. Warm upGet the vocabulary first.

  2. WatchHow others solve the same problem, on video.

    Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)

  3. ReadEngineers explain it in their own words.

  4. See it in another companyThe same ideas, a different system.

  5. Read the codeSee how it looks when it is real.

Keep learning

Loading community…