Design an API gateway
An API gateway is the single front door to a microservice backend, handling cross-cutting concerns — auth, rate limiting, routing, observability — so individual services don't each reimplement them.
Infrastructure, 10 components, about 30 min
1. Scope
In scope
- • Auth/token validation
- • Rate limiting
- • Routing to services
- • Observability
- • Circuit breaking
Out of scope
- • Service mesh (sidecars)
- • Business logic
- • Data transformation deep-dive
2. Functional requirements
Must have
- • Authenticate every request
- • Route to the right service
- • Enforce rate limits
- • Emit traces/metrics
Nice to have
- • Request/response transformation
- • Canary routing
- • Response caching
3. Non-functional requirements
4. Back-of-envelope estimation
Assumptions
- • 100K req/s ingress
- • JWT validated locally
- • Routing table from discovery
- • 1% trace sampling
Derived numbers
5. API design
All client traffic flows through the gateway
6. High-level design
What each box in the reference diagram is responsible for:
7. Data model
8. Deep dives
Middleware chain
A gateway is a composable pipeline: terminate TLS → authenticate → rate-limit → route → collect observability. Each stage can short-circuit (e.g., 401 on bad auth, 429 on limit) before forwarding to the upstream service. Keeping it ordered and composable makes behavior predictable and testable.
Local JWT validation
Calling the auth service on every request would add latency and a hard dependency. Instead, validate JWTs locally using cached public keys (JWKS), refreshed periodically. For revocation (logout, compromised token), keep a small short-TTL revocation list in Redis the gateway checks.
Dynamic routing
Service instances come and go (autoscaling, deploys). The gateway subscribes to service discovery (Consul/k8s) so its routing table updates as instances register/deregister — no manual config or redeploy.
Resilience
Per-route circuit breakers stop hammering a failing service and let it recover; the gateway can degrade gracefully (cached or empty responses). Trace sampling (e.g., 1%) gives observability without overwhelming the collector.
9. Bottlenecks
- Gateway is a SPOF → run many stateless instances behind an LB
- Auth round-trips → local JWT + cached JWKS
- Cascading failures → per-route circuit breakers
10. Trade-offs
Where to validate tokens
Choose: Verify JWT signatures locally at the gateway using cached signing keys (JWKS); pass identity downstream.
Instead of: Call the auth service on every request: easy revocation, but adds a hop and a dependency.
Local verification keeps the gateway fast; short token lifetimes (~15 min) bound revocation delay.
One gateway or several
Choose: A thin edge gateway for cross-cutting concerns, with backend-for-frontend layers per client type.
Instead of: One gateway holding business logic for all clients: becomes a bottleneck team and a monolith.
Keeps the shared component simple and lets client teams move independently.
Gateway or service mesh
Choose: Gateway for north-south (external) traffic; mesh sidecars for east-west (service to service) mTLS and retries.
Instead of: Route internal traffic through the gateway: extra hop and a single point of failure.
Each layer does the job it is placed for.
11. Failure modes
Retry storm
A slow backend gets 3× traffic from retries and collapses.
Mitigation: Retry budgets (for example at most 10% extra requests), exponential backoff, and circuit breakers per upstream.
Bad routing config pushed
Global outage.
Mitigation: Validated config, staged rollout by region, and automatic rollback on error-rate increase.
Gateway itself saturates
Everything fails.
Mitigation: Stateless nodes autoscaled behind an L4 load balancer, with load shedding by priority.
12. What interviewers probe
Answer each one yourself before opening it.
How do you revoke a stolen token before it expires?Show a strong answer
Keep lifetimes short and maintain a small revocation list (token id or user id plus timestamp) pushed to gateways and checked locally.
How much latency does the gateway add?Show a strong answer
Target under 10 ms at p99, typically 1–3 ms: local JWT check, in-memory routing, connection pooling to upstreams.
How do you do canary releases through the gateway?Show a strong answer
Weighted routing (for example 1% to v2) or header-based routing, with automated analysis of error rate and latency.
Where does rate limiting happen?Show a strong answer
At the gateway per API key and route, backed by a shared store, before any expensive backend work.
Sign in to track this guide in your curriculum progress.