AlgoViz

API gateway

medium 24 min

An API gateway is the single front door for client requests.

Video lesson · Chapter 1 of 6

Follow one cart request

0:00 / 3:47

API gateway

1:18Reel

Theory

Read or listen first. About 1 min.

What it is

An API gateway is a server that stands between clients and your services. Clients know one address. The gateway looks at each request, does the work that every request needs, and passes it to the service that can answer it.

It is a reverse proxy that understands your API: paths, methods, tokens and limits. A load balancer spreads calls over copies of one service; a gateway chooses which service.

Why it exists

With ten services and no gateway, every client must know ten addresses, and every service must repeat TLS, token checks, limits and logging. Moving or splitting a service breaks the clients.

A gateway puts those shared jobs in one place and hides the inside of the system. The price is an extra hop and a part that everything depends on, so it must be small, fast and redundant.

A short history

  1. 4 October 2004

    Igor Sysoev's NGINX is released. It becomes a widely used reverse proxy, the base of many gateways.

  2. 9 July 2015

    Amazon API Gateway is introduced as a managed service.

  3. 18 September 2015

    Phil Calçado describes the back-end for front-end pattern from work at SoundCloud.

  4. 18 November 2015

    Sam Newman writes up Backends For Frontends as an alternative to one general gateway.

  5. 31 October 2023

    The Kubernetes Gateway API reaches version 1.0.

Words to know

Reverse proxy
A server that receives requests for other servers and passes them on.
Edge
The border between the internet and your system.
TLS termination
Decrypting HTTPS at the gateway, which holds the certificate.
Upstream
The service behind the gateway that a request is sent to.
Cross-cutting concern
A job every service needs: authentication, limits, logging.
Aggregation
One client call that the gateway answers from several services.
BFF
Backend for frontend: a separate gateway made for one kind of client.

How it works

Step through the idea, or press Play.

Step 1 of 3

Receive and check. TLS, address rules, caller, limits, shape

Understand it

Start here

The clinic reception story

A gateway is like the receptionist of a clinic. Patients do not need to know which doctor sits where. They walk up to one desk.

One desk for every room
??

The receptionist checks and directs. They do not treat patients: business logic stays in the services.

With a gateway

  • One address for clients
  • Authentication checked in one place
  • The same limits everywhere
  • Simple client code

Without one

  • Clients manage many addresses
  • Each service repeats the checks
  • No shared limits
  • Complex client code

One front door, four services

A mobile app and a web app send requests to one API gateway. The gateway routes to four services: users, products, cart and orders, each in its own machine.
The thick borders are separate machines. Clients see only the gateway.

Routing

From a public path to a service

The shop's routes

Client asksGateway sends toPublic?
GET /api/productsproduct-service:8002/productsYes
POST /api/productsproduct-service:8002/productsNo
GET /api/cartcart-service:8003/cartNo
POST /api/ordersorder-service:8004/ordersNo
POST /api/auth/loginuser-service:8001/auth/loginYes, with a strict limit
GET /api/users/42user-service:8001/users/42No
The longest matching prefix wins. The public path can stay the same while services move.

Who owns which path

ServicePaths
User/users, /users/:id, /auth/login, /auth/register
Product/products, /products/:id, /categories, /search
Cart/cart, /cart/items, /cart/checkout
Order/orders, /orders/:id, /orders/:id/status

How does the gateway know which copies of a service are alive? From a registry or the platform's own names: see service discovery.

Jobs

What a gateway does

  • Routing

    By path, method, header or query. One entry point for all requests.

  • Authentication

    Verifies tokens, keys and certificates early. Services still check their own objects.

  • Rate limiting

    Stops single callers from using everything. It is one layer against floods, not full DDoS protection.

  • Load balancing

    Chooses a healthy copy of the target service.

  • TLS termination

    One place for certificates. Encrypt again towards services when the network is not trusted.

  • Caching

    Keeps frequent public answers close to the client.

  • Transforming

    Adds or removes headers, changes formats, maps old versions, REST to gRPC.

  • Logs, metrics, traces

    One record per request, with an ID that follows it everywhere.

The pipeline of one request

Cheap checks first. Limits per address can run before authentication, limits per user only after it.

When a check fails

CheckQuestionAnswer on failure
AddressIs this address on the block list, or missing from a private allow list?403
Limit per addressToo many requests from here?429
Token or keyValid?401
Limit per callerWithin the quota?429
ScopeDoes the token allow this endpoint?403
ShapeDoes it match the OpenAPI schema and size?400, or 413 when too large
UpstreamDid the service answer in time?502, 503 or 504
The object check (is this your order?) cannot be done here. It needs the order. See API authorization.

Aggregation

One call instead of three

A phone's home page needs profile, cart and recommendations. Over a slow mobile network three calls hurt. The gateway can ask all three services at once and send one answer.

Time saved

one after another=100+80+150=330 msin parallel=max⁡(100,80,150)=150 ms\text{one after another} = 100 + 80 + 150 = 330\,\text{ms} \qquad \text{in parallel} = \max(100, 80, 150) = 150\,\text{ms}
Example times. The slowest call sets the total, and the phone pays one round trip instead of three.

Aggregation with a partial answer

Optional parts may be missing. Required parts fail the request. Decide which is which per field.

More calls, more chances to fail

0.9993≈0.9970.999^3 \approx 0.997
If all three must answer and each works 99.9% of the time, about 3 in 1,000 pages fail. Optional parts and fallbacks take that away.

BFF

A gateway for each kind of client

A phone wants small answers. A website wants rich ones. Partners want something that never changes. One gateway for all of them grows special cases. The backend for frontend pattern gives each client type its own small gateway.

Three backends, the same services

Three clients, mobile app, web app and partner, each reach their own backend for frontend. All three backends call the same group of shared services: products, cart and orders.
Each arrow ends at the border of the shared services: every backend may call any of them.

What each one is made for

BFFGives
MobileSmall payloads, compressed images, data for offline use
WebRich data, server rendering, perhaps a GraphQL interface
PartnerA stable versioned API, limits per partner, webhooks
JSON
{"GET /mobile/home": {   "products": [{"id": 1, "name": "Desk lamp", "thumbnail": "50x50"}],   "cart_count": 3,   "unread_notifications": 2}, "GET /web/home": {   "products": [{"id": 1, "name": "Desk lamp, oak", "image": "400x400", "specs": {}, "reviews": []}],   "cart": {"items": []},   "recommendations": []}}
The same home page for two clients. Values are invented.

One gateway or BFF?

Single gatewayBFF
ClientsSimilarVery different
EffortLowerHigher: more to build and run
AnswersGeneralMade for each client
TeamsOne gateway teamEach client team owns its BFF
Best forSmall systemsLarge teams, different clients

Security

What the edge protects

AreaAt the gateway
IdentityVerify JWTs, partner keys and client certificates (mTLS)
TrafficLimits, address lists, bot rules; large floods belong to a CDN or DDoS service in front
RequestsSchema check, size limit, allowed methods and content types
DataTLS, browser origin rules (CORS), removing fields that must not leave

Should the service trust the gateway?

"Inside the network" is not proof. One broken service is inside too.

Failure

Keep the door open

  1. 1

    Run several copies

    At least two, in two zones, with no state of their own, behind a load balancer.

  2. 2

    Limit waiting

    A timeout per route, shorter than the client's. A slow service must not use up all connections: cap the calls in flight per upstream.

  3. 3

    Break the circuit

    Stop calling a service that keeps failing, and answer 503 quickly. See circuit breaker.

  4. 4

    Change configuration carefully

    A wrong route breaks everything at once. Review it, test it, roll it out to one copy first, and keep the previous version ready.

  5. 5

    Keep enough room

    If one of three copies dies, the other two carry 50% more each.

How many copies?

n=⌈9,0004,000⌉+1=3+1=4n = \left\lceil \frac{9{,}000}{4{,}000} \right\rceil + 1 = 3 + 1 = 4
Assumed: 3,000 requests a second on average, so 9,000 at peak (3 times), and 4,000 per copy as measured in a load test. One more copy covers a failure.

Advantages

  • One entry point simplifies clients
  • Shared security and monitoring
  • Request and response changes
  • Protocol translation, such as REST to gRPC
  • Balancing and discovery in one place
  • Easier versioning

Costs

  • A single point of failure if you run one
  • An extra hop and a little latency
  • Configuration that grows
  • Needs high availability
  • Can become the bottleneck
  • More to pay for and run

Neighbours

Gateway, load balancer, service mesh

API gatewayLoad balancerService mesh
TrafficFrom clients into the systemAny, to one poolBetween services
KnowsPaths, tokens, callersConnections or HTTPServices and their identity
Main jobOne API, edge checksSpread loadmTLS, retries, telemetry inside
Runs asA few shared copiesA managed service or pairA proxy beside each service, or per node
They work together: balancer in front, gateway behind it, mesh inside.

Tools

Popular gateways

Products

ProductKindOften chosen for
KongOpen source core, paid editionPlugins, Kubernetes
Amazon API GatewayManaged, pay per requestAWS systems, serverless
NGINXOpen source, paid edition (Plus)Speed, simple rules
EnvoyOpen sourceEdge and service mesh data plane
TraefikOpen source, paid editionDocker and Kubernetes
ApigeeManaged by Google CloudEnterprise API programmes, analytics
Products change. Check licences and prices on their own pages.

Decide

Do you need one?

Three questions

Use a gateway when

  • There are several services
  • Web, mobile and other clients call you
  • You want shared authentication and limits
  • You need versioning or translation
  • You want one place for logs

Consider less when

  • One simple monolith
  • One kind of client
  • Very little traffic
  • Nothing to translate
  • You cannot run more than one copy

Summary

The whole topic in one minute.

A gateway gives clients one address and services one place for shared work: TLS, token checks, limits, routing, logs. Keep business rules out of it.

It sits in front of everything, so run several copies, keep configuration safe to change, set timeouts, and let each service still check what it must. Split it per client type only when the clients truly differ.

  • One address outside, many services inside.
  • Shared jobs: TLS, identity, limits, routing, logs. No business rules.
  • Aggregate in parallel, with timeouts and optional parts.
  • Strip identity headers from outside, and let services check their own objects.
  • Run several copies and treat configuration like code. Use BFFs only for truly different clients.

Sources