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.