API gateways
What belongs in an API gateway and what does not, how it differs from a load balancer, reverse proxy and service mesh, and the risks of putting one component in front of everything.
The problem
A company splits its monolith into 30 services and exposes each one to the internet. Six months later:
- Token validation has been written four times in three languages, and each copy handles expiry slightly differently.
- A vulnerability in a JWT library has to be patched and redeployed in 30 places.
- Some services have rate limits and some do not, so abusive clients find the ones that do not.
- The mobile app knows 30 hostnames. Moving an endpoint from one service to another needs an app release.
- Nobody can answer “which clients call what, and how often”, because every service logs differently.
The first fix teams try is a shared library. It works while everyone uses one language and upgrades promptly. In practice services pin old versions, the library has to be ported to each language, and the 30-way patching problem returns.
What works is moving the shared concerns out of the services and into one component that every request passes through: an API gateway. Netflix open-sourced its edge gateway, Zuul, in 2013, and Kong and Amazon API Gateway both launched in 2015.
What moves into the gateway
Step 1 of 7
The app sends a request for order 42, with a bearer token, to the one public hostname. The gateway terminates TLS, so no backend service has to hold the public certificate.
Read the steps as text
- The app sends a request for order 42, with a bearer token, to the one public hostname. The gateway terminates TLS, so no backend service has to hold the public certificate.
- Authentication comes first. The gateway verifies the token's signature and expiry using the identity provider's public keys. It fetched those keys earlier and cached them, so there is no network call per request.
- Next, is this caller within its quota? The counters live in a shared store, so every gateway instance sees the same count. A caller over the limit would get a 429 here and no service would be touched.
- Then routing. The path prefix matches the orders service. The gateway picks a healthy instance and forwards the request, adding headers that carry the verified user id and a trace id.
- The service does the business work, including the check that user 7 is allowed to see order 42. That decision needs knowledge of the domain, so it stays in the service and out of the gateway.
- On the way out, the gateway records the route, status and latency, so every API has the same metrics and access logs without each team building them. Then it returns the response to the app.
- Everything the gateway did was a concern shared by all services. That is the test for what belongs there. The moment it needs to know what an order is, logic has crept into the wrong place.
- TLS termination. One place holds the public certificates. See TLS.
- Authentication. Verify the token or API key once, then pass the verified identity to services. See authentication and authorisation.
- Rate limiting and quotas. Per client, per key or per route, with counters in a shared store. See rate limiting.
- Routing. Map host, path and version to a service, so clients see one stable API while services move behind it. This is also where canary releases and traffic splitting happen.
- Request shaping. Size limits, schema validation, header rewriting, CORS, compression, and protocol translation such as REST and JSON outside to gRPC inside.
- Observability. Uniform access logs, metrics per route and per client, and a trace id attached at the edge. See observability.
- Resilience. Timeouts, and sometimes retries and circuit breaking towards backends.
What stays in the services is everything that needs to understand the domain: business rules, validation that depends on data, and fine-grained authorisation such as “may this user refund this order?”. The gateway establishes who is calling. The service decides what they may do.
Gateway, load balancer, reverse proxy, service mesh
These terms overlap, and interviewers like to ask for the difference.
| Component | Its job | Typical position |
|---|---|---|
| Reverse proxy | The general term: a server that accepts requests on behalf of backends | Anywhere |
| Load balancer | Spread requests over identical instances of one service, and skip unhealthy ones | In front of each service or tier |
| API gateway | Apply API policy and route to many different services | The edge, between clients and services |
| Service mesh | Secure and control calls between services, through a proxy beside each one | Between internal services |
A load balancer asks “which copy of this service?”. A gateway asks “which service, and is this caller allowed to use it at this rate?”. The gateway is concerned with clients, API keys, quotas and versions, which a load balancer knows nothing about. A service mesh applies similar mechanics (mTLS, retries, telemetry) to traffic that never leaves your network.
They are often the same software in different roles. Envoy and NGINX are used as all four. A typical chain is CDN, then a load balancer, then several gateway instances, then services. In a cloud deployment the first two or three may be one managed product. Do not send internal service-to-service calls back out through the edge gateway. That adds a hop and makes the edge a dependency of everything.
Backend for frontend
One general-purpose API rarely suits every client. The mobile app wants one compact response per screen, because round trips on a mobile network are expensive. The web app wants different fields. Partners want a stable, documented, versioned API.
The backend for frontend (BFF) pattern gives each client type its own thin API layer. It came out of SoundCloud’s move to microservices and was popularised by Sam Newman. A BFF aggregates calls to several services, trims the response to what its client needs, and is owned by the team that builds that client, so they can change it without waiting for anyone.
The price is more deployables and some duplicated logic between BFFs. It is worth it when clients truly differ. With one client, or clients with near-identical needs, a single gateway is simpler. GraphQL is another answer to the same problem, discussed in REST vs gRPC vs GraphQL.
Risks
It is on the path of every request. If the gateway is down, everything is down. Run several stateless instances across zones behind a load balancer, and keep per-request dependencies few. The less obvious risk is configuration: redundant instances all receive the same bad routing rule. Validate changes, roll them out to a small share of traffic first, and make rollback fast.
Business logic creeps in. A gateway is a tempting place for “just one small transformation”. Over years it accumulates pricing rules and special cases, and becomes a monolith that every team must change and nobody owns. Keep to the test: if the logic needs to know what an order is, it does not belong there.
It becomes a team bottleneck. If every new route needs a ticket to the gateway team, the organisation slows down. Let service teams declare their own routes and limits in configuration that the gateway team reviews or validates automatically.
It adds a hop. Typically that is a few milliseconds or less, plus the work it does. That is small beside most requests, but measure it. Token verification with cached keys is cheap. A network call to an auth service on every request is not.
Shared state needs care. Rate limit counters held in each instance’s memory give every client several times its limit. Use a shared store, and decide what happens when that store is unavailable. For most APIs, allowing requests through is better than rejecting everything. For protecting a fragile backend it may be the reverse.
When to choose it and when not to
Use a gateway when several services share a public API, when you have external clients you cannot update at will, or when you need consistent authentication, quotas and metrics across teams.
Skip it, or keep it minimal, when you have a monolith or two or three services. A load balancer plus middleware in the application does the same job with one less moving part. It is also the wrong tool for internal calls, which belong to service discovery or a mesh, and for long-lived streaming connections unless the gateway is built to hold them.
In the interview
Draw the gateway between the load balancer and the services, and say in one sentence what it does for this design: “the gateway terminates TLS, authenticates the token, applies per-user rate limits and routes by path”. That sentence saves you from re-explaining auth and rate limiting for every service.
Expect two probes. The first is “isn’t that a single point of failure?” Answer with stateless instances across zones, a shared store for counters, and staged configuration rollouts. The second is “what would you not put there?” Answer with business rules and per-object authorisation, and explain why.
Key takeaways
- An API gateway is the single entry point that applies the concerns every service shares, such as TLS, authentication, rate limiting, routing and telemetry.
- The test for what belongs there is whether the concern is the same for every service. Anything that needs domain knowledge stays in the service.
- A load balancer spreads traffic over copies of one service. A gateway routes across different services and applies API policy. A mesh handles calls between services.
- A backend for frontend is a gateway per client type, owned by the client team, that shapes and aggregates responses for that client.
- The gateway is on the path of every request, so run it stateless and redundant, roll out its configuration in stages, and keep business logic out.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is an API gateway?
A single entry point in front of many services that handles shared concerns (TLS termination, authentication, rate limiting, routing, request shaping and observability) so that each service does not reimplement them.
What is the test for whether logic belongs in the gateway?
Is it the same for every service and free of domain knowledge? If yes, the gateway. If it needs to know what an order or a user is, it belongs in a service.
Gateway versus load balancer?
A load balancer spreads requests over identical instances of one service. A gateway chooses between different services and applies API policy such as keys, quotas and versions. Gateway instances usually sit behind a load balancer.
Gateway versus service mesh?
A gateway handles traffic entering the system from clients (north-south). A mesh handles calls between internal services (east-west), with a proxy beside each service for mTLS, retries and telemetry.
What is a backend for frontend?
A separate gateway or API layer per client type (web, mobile, partner), usually owned by that client's team, which aggregates backend calls and returns exactly what that client needs.
Name three risks of an API gateway.
It can become a single point of failure, especially through bad configuration. It tends to collect business logic. And one team owning it can become a bottleneck for every other team's changes.