Course contents

11. Microservices Lesson 4 of 10

API Gateway

One front door for your services: routing, auth at the edge, rate limiting and aggregation, and why the gateway can become a bottleneck or SPOF.

17 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An API gateway is the single public entry point: it routes by path, terminates TLS and hides the internal layout.
  • The gateway authenticates once at the edge; services still authorize each action.
  • Rate limits at the gateway reject excess cheaply (429) before it overloads services.
  • Aggregation replaces several slow client round trips with one call and parallel internal calls.
  • Every request crosses the gateway: keep it thin, run it as a redundant fleet, roll out its config carefully.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An API gateway is a reverse proxy that is the single public entry point to a set of services. Clients call one host (api.example.com); the gateway applies cross-cutting policies (TLS, authentication, rate limits, logging) and forwards each request to the service that owns its route. Some gateways also compose responses from several services.

Why it exists

Without a gateway, every service that clients use must be public and must implement TLS, token validation, CORS, rate limiting and request logging on its own, usually slightly differently. Clients must know which service lives where, so every internal split or rename becomes a client release. The gateway moves those concerns to one place and gives clients a stable API that does not change when the services behind it do.

How it works

Routing. A route table maps host, path, method or header to an upstream service: /orders/* to Orders, /products/* to Catalog. Upstreams are found through service discovery and balanced across instances. Routing also enables versioning (/v2), canary releases (send 5% of a route to a new version) and moving a route to a new service without clients noticing.

Authentication at the edge. The gateway validates access tokens on every request. For JWTs it fetches the identity provider's public signing keys (JWKS) once, caches them, and verifies signature, expiry, issuer and audience locally, which costs microseconds rather than a network call. Invalid requests get 401 before reaching any service. The gateway then forwards the verified identity (the original token or signed claims). Services still authorize: whether this user may read this order depends on domain data only the service has. In zero-trust networks services also verify the token themselves instead of trusting anything inside the network.

Rate limiting. A token bucket (or sliding window) per API key, user, IP or route admits a sustained rate with a burst allowance and answers the rest with 429 Too Many Requests, ideally with a Retry-After header. Rejecting at the edge is cheap and protects the services behind it. With several gateway instances, counters are either kept in a shared store (Redis) or split per instance (approximate).

Aggregation (API composition). For a screen that needs data from several services, the gateway can accept one request, call the services in parallel and return one combined response. This saves round trips on slow client links. Heavy, client-specific composition is better placed in a Backend for Frontend.

Other edge duties. Request IDs and trace context, access logs and metrics, request size limits, CORS, response caching, and protocol translation (HTTP/JSON to gRPC).

When to use it

  • Any system that exposes several services to external clients (apps, browsers, partners).
  • When you need uniform authentication, rate limiting and observability at the edge.
  • When the internal service layout should be free to change without client releases.

When not to

  • A single service: a plain reverse proxy or load balancer does the job.
  • For service-to-service traffic inside the cluster: routing every internal call through a central gateway adds a hop and a bottleneck; a service mesh or direct calls with discovery fit better.
  • As a home for business logic: workflows and domain rules belong in services.

Trade-offs

Choice You gain You pay
Single entry point One place for edge policy, stable public API An extra hop and a critical component to run
Token validation at the gateway Services skip repeated authentication; invalid traffic stops early Services must still authorize; the gateway must be trusted and kept current
Rate limiting at the gateway Spikes rejected cheaply before backends Shared counters across instances, tuning per client
Aggregation in the gateway Fewer client round trips Gateway becomes heavier and coupled to client screens
Managed gateway No servers to run, built-in auth and limits Per-request cost, provider limits and lock-in

Alternatives

  • Plain reverse proxy / load balancer (NGINX, HAProxy, cloud L7 LB) with path routing: enough when you do not need per-client policies.
  • Backend for Frontend: one gateway per client type, owned by the client team, for client-specific composition.
  • Service mesh for internal traffic: mTLS, retries and routing between services without a central hop; often combined with an edge gateway.
  • GraphQL gateway or federation: clients ask for exactly the fields they need; the gateway plans calls to subgraphs.

Failure modes

  • Bottleneck: every request crosses the gateway. Heavy transformations, synchronous aggregation and verbose logging raise the cost per request until the gateway caps the whole API.
  • Single point of failure: one instance, one zone or one bad configuration push takes down every route. Gateway config changes need staged rollouts and fast rollback.
  • Retry amplification: gateway retries on top of client and service retries multiply load during an incident.
  • Timeouts that do not fit: a gateway timeout shorter than a slow route causes errors for work that completes; one longer than the client's wastes capacity.
  • Logic creep: business rules accumulate in gateway plugins, and every team now has to coordinate changes to one shared component.
  • Noisy neighbours: one client or route exhausts shared capacity when limits are global instead of per key.

In production

Run the gateway as a stateless fleet across zones behind an L4 load balancer or anycast, with health checks and autoscaling. Version gateway configuration in Git, validate it in CI and roll it out gradually. Set per-route timeouts and per-client limits, propagate trace context, and watch gateway latency, saturation and error rate per route. Kubernetes increasingly standardises gateway configuration through the Gateway API resources, implemented by Envoy-based and other controllers. Keep composition simple; when clients need very different shapes, add BFFs rather than growing one gateway.

Common misconceptions

  • "The gateway handles security, so services do not need to." It authenticates; services still authorize and should not trust every internal caller.
  • "A gateway makes requests faster." It adds a hop; it saves time only where it removes client round trips (aggregation) or serves from cache.
  • "When the API is slow, scale the gateway." Measure first: a saturated service behind it is at least as likely.
  • "A gateway is just a load balancer." It applies per-request policy (auth, limits, routing by content, composition); a load balancer only distributes.

Interview angle

Put a gateway at the edge of any multi-service design and say what it does: TLS, auth, rate limiting, routing, maybe aggregation. Expect follow-ups: how it avoids being a SPOF (stateless fleet, multi-zone, careful config rollout), where authorization happens (services), how rate limits work across gateway instances (shared counters or per-instance budgets), and when you would add BFFs. Mention that internal service-to-service traffic does not need to pass through it.

Model assumptions

The simulation is a simplified model, not a benchmark. The gateway is modelled as a server whose 64 workers stand for concurrent request slots: it spends 4 ms on each request (70 ms in the bottleneck step) and keeps the slot while the request is proxied. Its route table is a separate balancer that sends each request to one service by the request's key (standing in for its path), so the route mix is roughly even. Each service has 8 workers at 20 ms (about 400 req/s) and room for 10 waiting requests. Apps are 25 ms from the gateway; internal hops take 0–2 ms. The rate limit is a single token bucket for all traffic; real gateways keep one per client or route. The edge balancer checks gateways every 500 ms and ejects after 2 failures. The direct calls, the identity provider key fetch, the rejected token and the aggregation comparison are scripted illustrations, not simulated. Arrivals are random (Poisson). Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every client talks to every service

    The apps call each service directly. Every service is exposed to the internet, so each one terminates TLS, checks tokens, handles CORS and needs its own public address. Three teams implement the same edge concerns three slightly different ways.

    The clients are coupled to the internal layout too: split Orders in two and every app release has to learn the new address. *(Scripted illustration: one request to each service.)*

    Scene: The apps call Users, Orders and Catalog directly. Each service is public and implements TLS, authentication and CORS on its own.

    Key idea: Without a single entry point, every service carries edge concerns and every client knows the internal topology.

  2. 2. One front door

    An API gateway becomes the only public entry point. Clients call api.example.com; the gateway terminates TLS once and its route table forwards each request to the one service that owns the route: /users/* to Users, /orders/* to Orders, /products/* to Catalog.

    The services move to a private network. 150 requests per second now pass through the gateway, which adds a few milliseconds and spreads them over the services by route.

    Scene: The apps send 150 requests per second to the API gateway, which routes each one to Users, Orders or Catalog by its path. The services are no longer public.

    Key idea: A gateway gives clients one stable API and hides how the system is split behind it.

  3. 3. Authenticate once, at the edge

    The gateway checks every request’s access token. It fetches the identity provider’s signing keys once and caches them, then verifies each token’s signature and expiry locally, in well under a millisecond. A request with an invalid token gets 401 straight from the gateway and never reaches a service.

    Services still decide authorization: may *this* user see *this* order? The gateway passes the verified identity along (the token or signed claims), and in a zero-trust network services verify it again cheaply rather than trusting any caller inside. *(Key fetch and the rejected request are scripted; the traffic is simulated.)*

    Scene: The gateway fetches the identity provider’s signing keys once, then verifies tokens locally. A request with a bad token is rejected by the gateway and never reaches a service.

    Key idea: The gateway authenticates (who is calling); each service still authorizes (what they may do).

  4. 4. A traffic spike hits the services

    At 1 s a buggy app release starts retrying in a tight loop: traffic jumps from 150 to 1,500 requests per second. The gateway passes it all on. The three services can handle about 1,200 between them, so their queues fill and they reject about one request in five, from well-behaved clients as much as from the broken one.

    The gateway is the one place that sees all traffic before it reaches the services. It should be shedding the excess, not forwarding it.

    Scene: Traffic jumps to 1,500 requests per second. The services are overloaded and reject about a fifth of all requests, from every client.

    Key idea: A gateway that forwards everything passes every spike straight to the services.

  5. 5. Shed the excess at the gateway

    The gateway gets a rate limit: a token bucket that admits 600 requests per second (with a short burst allowance). Requests above it get 429 Too Many Requests immediately, at almost no cost, and well-behaved clients back off and retry later.

    The services now receive only what they can handle: they stop rejecting, and admitted requests are fast again. Real gateways keep a bucket per API key, user or route, so one misbehaving client is limited without slowing the others; this model uses one bucket for all traffic.

    Scene: The gateway admits 600 requests per second and answers the rest with 429 at once. The services are no longer overloaded and admitted requests are fast.

    Key idea: Rate limiting at the edge rejects excess cheaply before it can overload the services behind.

  6. 6. One call instead of three

    The mobile home screen needs the profile, recent orders and featured products. Calling three endpoints one after another over a 60 ms cellular link takes three full round trips: about 440 ms.

    With aggregation, the app makes one call; the gateway calls the three services in parallel over the fast internal network and returns one combined response: about 150 ms. The gain comes from saving round trips on the slow link. *(Scripted comparison: first one by one, then aggregated.)*

    Scene: First the mobile app makes three calls one after another, each a full round trip over the cellular link. Then it makes one call and the gateway queries the three services in parallel and returns one response, much sooner.

    Key idea: Aggregation trades several slow client round trips for one, plus fast parallel calls inside the data centre.

  7. 7. The gateway becomes the bottleneck

    Over time the gateway has collected work: aggregation, payload transformation, detailed request logging. Each request now occupies the gateway for about 70 ms of its own time (transformations, logging, waiting on aggregated calls) instead of 4. For a sale the limit is raised and traffic grows to 700 requests per second.

    The gateway saturates: its queue grows and latency climbs, while the services still have headroom. Every request crosses the gateway, so its capacity caps the whole API, and business logic placed there makes it heavier and couples every team to one deployment.

    Scene: The gateway now spends 70 ms on each request. At 700 requests per second it is saturated and requests queue there, while the services behind it still have spare capacity.

    Key idea: Everything crosses the gateway: keep it thin, or it caps the capacity of the whole system.

  8. 8. One gateway, one point of failure

    At 1 s the gateway instance crashes. Users, Orders and Catalog are all healthy, yet every request fails: there is no other way in.

    A single gateway instance is a single point of failure for the entire API. A bad gateway config deploy has the same effect, which is why gateway changes deserve the most careful rollout of all.

    Scene: The only gateway instance goes down. Every request fails although all services are healthy.

    Key idea: If all traffic enters through one gateway instance, its failure is a total outage.

  9. 9. Run the gateway as a fleet

    The gateway is stateless (rate-limit counters aside), so it scales horizontally: three instances behind a simple layer-4 load balancer with health checks. Together they have three times the capacity, so the 700 requests per second no longer queue.

    At 1 s one instance crashes. For about a second its share of requests fails, until health checks eject it; then the two survivors carry the load. Shared state such as rate-limit counters lives in a fast shared store or is split per instance.

    Scene: Three gateway instances sit behind an edge load balancer and carry 700 requests per second without queueing. Gateway 1 crashes; requests sent to it fail for about a second until it is ejected, then the other two handle all traffic.

    Key idea: Scale the gateway horizontally behind a health-checked balancer: more capacity and no single point of failure.

  10. 10. What belongs in the gateway

    The gateway is the system’s front door: routing, TLS, authentication, rate limiting, request IDs and metrics, and sometimes aggregation for chatty clients. Those are cross-cutting concerns that every request needs.

    Keep business logic out of it: logic in the gateway couples every team to one deployment and makes it heavier. Run it as a fleet, roll out its configuration carefully, and watch its latency and saturation like any critical service. For very different client needs, see Backend for Frontend.

    Scene: Three healthy gateway instances behind an edge load balancer route traffic to Users, Orders and Catalog. Everything is healthy.

    Key idea: A thin, redundant gateway for cross-cutting edge concerns; business logic stays in the services.