API Gateway
One front door for many services, so cross-cutting concerns live in one place instead of being copy-pasted everywhere.
API gateway in 30 seconds
- What: one front door for many services, so cross-cutting concerns live in one place, not copy-pasted everywhere.
- Handles: routing, auth, rate limiting, TLS termination, request shaping, and observability — before traffic hits the backends.
- BFF variation: a tailored gateway per client type (mobile vs web) so each gets responses shaped for its needs.
- Keep it thin: cross-cutting plumbing only — the moment it holds business logic it becomes a coordination bottleneck.
- It's a SPOF: a critical dependency, so run it redundantly; an extra hop adds a little latency.
- Not a load balancer: the gateway owns API concerns; a load balancer just spreads traffic across servers.
The front desk of an office building
Think about a big office building with dozens of companies inside. Visitors don't wander the halls trying each door — there's one front desk in the lobby. The receptionist checks your ID, signs you in, tells you the fire exits, and points you to the right floor. Every visitor goes through that single desk, so security and sign-in happen once, consistently, no matter which company you're visiting. An API gateway is that front desk for your backend services: one entrance where identity is checked, visitors are logged, and each request is directed to the right internal service — instead of every service running its own ad-hoc door policy.
The problem it solves
Once you split a system into many services, every one of them needs the same boring-but-critical things: authentication, rate limiting, logging, TLS, request routing. Making each service implement these is duplicated effort and inconsistent security. An API gateway is a single entry point that handles these cross-cutting concerns once, then forwards each request to the right backend service.
The gap that letting each service fend for itself can't fill
The naive design is: skip the gateway, let clients call each service directly, and have every service handle its own auth, limits, and logging. It seems simpler — fewer moving parts. But at more than a couple of services it quietly falls apart, and the ways it falls apart are exactly what the gateway fixes.
- Security drifts out of sync. Five teams each write their own token-checking code. One team gets it subtly wrong, and now you have a hole — and no single place to fix it. Consistent security means one implementation, not five.
- Clients must know your internal map. If the mobile app calls each service directly, it has to know every service's address and which one owns what. Reshuffle the services and every client breaks.
- The same plumbing is copy-pasted everywhere. Rate limiting, TLS, logging, tracing — rewritten in each service, each a little different, each a maintenance burden that rots at its own pace.
A gateway closes all three: one consistent security boundary, one stable address clients talk to (so the internal layout can change freely behind it), and one implementation of the shared plumbing. That's the core trade — a little extra infrastructure in exchange for consistency and a clean edge.
Gateway vs reverse proxy vs load balancer
These three sit near each other at the edge and get muddled constantly, so let's pin them down. They're not competitors — they're layers of specialization. A load balancer spreads traffic across identical copies of a service. A reverse proxy is a server-side front that can terminate TLS, cache, and forward. An API gateway is a reverse proxy that also understands your API — it knows which service owns /orders, checks auth, and enforces per-client limits.
| Component | Core job | Knows about... |
|---|---|---|
| Load balancer | Spread requests across identical servers. | Server health and connection counts — not your API. |
| Reverse proxy | A server-side front: TLS, caching, forwarding. | HTTP, but not your service map or auth rules. |
| API gateway | Govern and route API traffic for many services. | Routes, auth, rate limits, tenants — your whole API. |
What it actually does
- Routing — maps a public path (
/orders) to the right internal service. - Authentication & authorization — validates tokens once, so services trust the gateway.
- Rate limiting & quotas — enforces fair usage before load hits the backends.
- TLS termination — decrypts HTTPS at the edge.
- Request/response shaping — aggregates calls, transforms formats, adds headers.
- Observability — a single place to log, trace, and measure every request.
def handle(request):
# 1. AuthN/AuthZ once, at the door, so services can trust the gateway
user = verify_token(request.headers.get("Authorization"))
if not user:
return Response(401, "unauthorized")
# 2. Rate limit before any load reaches the backends
if not rate_limiter.allow(user.id):
return Response(429, "slow down")
# 3. Route the public path to the right internal service
service = ROUTES.match(request.path) # "/orders" -> orders-svc
return service.forward(request, trace_id=new_trace_id())Notice the order of that pipeline, because it's a design principle in itself: the cheapest rejections happen first. An unauthenticated request is turned away before any rate-limit bookkeeping; a rate-limited request is rejected before it ever touches a backend. The gateway's job is to shed bad or excess traffic at the edge — the earliest, cheapest point — so your valuable backend capacity is spent only on legitimate work.
Why services can trust the gateway: the private network
A natural worry: if the gateway checks auth and then forwards the request, what stops someone from skipping the gateway and calling a service directly, unauthenticated? The answer is network boundaries. The backend services live on a private network that isn't reachable from the public internet — only the gateway can talk to them. So the single public door really is the only door, and a service can safely trust that any request reaching it already passed the gateway's checks.
This is why the gateway can validate a token once and let services treat the caller as already-authenticated. The services aren't being naive; they're relying on the fact that the only path in runs through the gateway. In higher-security setups you add a second layer (services verify a signed internal token or use mutual TLS) so a breach of one service can't impersonate the gateway — defense in depth — but the baseline model is 'one public door, everything else private.'
The Backend-for-Frontend variation
A single gateway for every client type can get awkward — a mobile app and a web dashboard want very different responses. The Backend-for-Frontend (BFF) pattern runs a tailored gateway per client type: one shapes compact, battery-friendly responses for mobile; another returns richer payloads for the web. It trades a bit more infrastructure for cleaner, client-specific APIs.
// One mobile-home call fans out, then returns a compact, tailored payload
async function mobileHome(userId) {
// Fetch from independent services in parallel
const [profile, orders, feed] = await Promise.all([
usersSvc.get(userId),
ordersSvc.recent(userId, { limit: 3 }),
feedSvc.top(userId, { limit: 10 })
]);
// Shape for a battery- and bandwidth-constrained client
return {
name: profile.name,
recentOrders: orders.map(o => ({ id: o.id, total: o.total })),
feed: feed.map(f => f.title)
};
}The win here is subtle but real: without a BFF, a mobile client often has to make three separate calls (profile, orders, feed) over a flaky cell connection and then stitch the results together itself — slow and battery-draining. The BFF makes those three calls server-side, where the network is fast, and hands the phone a single compact response. Fewer round trips over the slow last mile is a big deal for mobile.
Trade-offs to name
| Benefit | Cost |
|---|---|
| Cross-cutting logic lives in one place. | The gateway becomes a critical dependency — a potential SPOF, so run it redundantly. |
| Services stay simple and focused. | An extra network hop adds a little latency. |
| One consistent security boundary. | Risk of a 'god gateway' that accumulates business logic it shouldn't own. |
An API gateway is where a microservices architecture gets a coherent edge — the one place that turns a sprawl of internal services into a single, governed, secure front door.
Why it matters
- It gives you one consistent security boundary instead of per-service auth that drifts out of sync.
- It lets services stay small and focused by lifting the boring-but-critical plumbing out of each of them.
- It's the natural home for rate limiting, quotas, and observability that span every request.
If ignored
- Every team reimplements auth, TLS, and rate limiting — inconsistently, and that's where security holes live.
- A 'god gateway' that quietly accumulates business logic until every change needs its own release train.
- An unprotected single instance that takes the whole API down when it fails.
Where it fits
- Sits at the edge of the request path, in front of the service mesh and behind the load balancer or CDN.
- Often terminates TLS and enforces rate limits here, at the cheapest place to shed bad traffic.
- Pairs with service discovery so it can route to healthy instances as they come and go.
Related topics
- Load balancing: spreads traffic across instances; the gateway owns API-level concerns on top
- Rate limiting: the gateway is the usual place to enforce per-client limits
- Proxies: a gateway is a reverse proxy specialised for API traffic
- Service discovery: how the gateway finds healthy backends to route to
Interview lens
Questions it unlocks
- How do you handle auth and rate limiting across many microservices?
- What's a Backend-for-Frontend and when would you use one?
- What are the downsides of an API gateway?
60-second answer
I put an API gateway as the single front door so auth, rate limiting, TLS, routing, and logging live in one consistent place instead of being reimplemented per service. The services sit on a private network so the gateway really is the only way in. I'd note it becomes a critical dependency, so I run it redundantly and keep it thin — cross-cutting plumbing only, no business logic. If clients differ a lot, I'd use a Backend-for-Frontend per client type. For AI backends, I'd mention a model gateway variant that adds token budgets, response caching, and provider failover.
Common traps
- Letting the gateway accumulate business logic and become a coordination bottleneck.
- Forgetting it's a SPOF unless deployed redundantly.
- Confusing the gateway (API concerns) with a plain load balancer (traffic spreading).