Case Study 24 β API Gateway
Design an API Gateway in front of microservices: single entry point for clients with routing, authentication, rate limiting, and optional response aggregation.
1. Problem
Mobile and web clients should not call dozens of internal services directly. A gateway terminates TLS, validates identity, enforces quotas, routes to the correct backend, and can combine multiple backend calls into one client response.
2. Requirements
Functional (MVP)
- Route requests by path/host to backend services
- Authenticate requests (JWT validation)
- Rate limit per user/API key/IP
- Request/response logging and correlation IDs
- Optional aggregation: one endpoint calls multiple services and merges JSON
- Health-aware routing (skip unhealthy backends)
Out of scope (initially)
- Full GraphQL federation, WebSocket gateway for all products
- WAF/DDoS at L7 (assume CDN/WAF upstream)
- Developer portal and API key self-service UI
- Complex transformation (XML β JSON)
Non-functional
- Low added latency (< 10β20 ms P95 at gateway itself)
- Stateless gateway instances β horizontal scale
- Fail closed on auth failures
- Rate limits accurate enough for abuse prevention (not perfect global sync required for MVP)
- High availability β gateway is on every request path
3. Back-of-the-envelope estimates
These numbers are rough order-of-magnitude math β not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained β 86,400 requests/day. The gateway sits on every request path β peak is often 2β5Γ average, and a bad gateway takes down all services.
Why we estimate
An API gateway is pure infrastructure β it adds latency to every call but offloads cross-cutting work (auth, rate limits, routing) from backends. Estimates tell us:
- How many stateless gateway instances we need
- Whether Redis can hold rate-limit counters at our key cardinality
- How much log volume we generate (often the hidden cost)
Assumptions
| Assumption | Value | Why it matters |
|---|---|---|
| Aggregate traffic through gateway | 50K RPS | All client traffic enters here |
| Backend services | 10 | Routing table complexity |
| Gateway processing overhead | ~5 ms P95 | Must stay thin |
| Average backend latency | ~100 ms | Gateway is small fraction of total |
| Active API keys / users for rate limiting | 1M | Redis memory for counters |
| Log sampling rate | 1% of requests | Cost control |
Step A β Traffic (QPS) with labeled arithmetic
Total gateway throughput:
Aggregate RPS = 50,000 requests/second (given peak design point)
Daily requests = 50,000 Γ 86,400
β 4.3 billion requests/day
This is already a peak-ish number in many designs; average might be 15β20K RPS with 50K at peak.
Per-backend share (uniform rough split):
RPS per backend = 50,000 Γ· 10 services
β 5,000 RPS each (varies β one hot service may get 20K)
Auth validation (JWT verify β every request):
JWT validations/s = 50,000/s (same as ingress β no skip on authenticated routes)
CPU cost β 0.1β0.5 ms per verify β must use local JWKS cache
Rate-limit checks:
Counter lookups/s = 50,000 Redis GET/INCR operations/second
β Redis cluster or local token bucket with async sync for MVP
Step B β Storage
Rate-limit state (Redis):
Active API keys = 1M
Bytes per key state β 100 B (token count, window expiry, metadata)
Redis memory = 1M Γ 100 B β 100 MB β trivial; even 10M keys β 1 GB
Routing config:
Routes = ~200 path β backend mappings
Config size β 50 KB β loaded at startup, hot-reloaded from etcd/Consul
Access logs (if stored 30 days):
Requests/day β 4.3B (at 50K RPS sustained β upper bound)
Log row size β 500 B (timestamp, path, status, latency, trace_id)
Full logs/day = 4.3B Γ 500 B β 2 TB/day β too expensive
Sampled 1% β 20 GB/day β ~600 GB/month to log pipeline (Elasticsearch/S3)
Step C β Bandwidth and other resources
Gateway instance capacity:
Each gateway node β 5,000β10,000 RPS (depends on TLS, JWT, aggregation)
Required instances = 50,000 Γ· 5,000 = 10 instances
Add N+1 for HA β 11β12 instances minimum
Latency budget:
Client total budget β 200 ms (typical mobile API)
Gateway overhead β 5 ms (routing + auth + rate limit)
Backend β 100 ms
Network + client β 95 ms remaining
Gateway must stay under 10β20 ms P95 β no heavy aggregation in hot path unless cached.
Aggregation endpoints (optional):
One aggregated call = 3 backend hops Γ 100 ms = 300 ms sequential (bad)
Parallel fan-out = max(100 ms) + 5 ms gateway β 105 ms (good)
Peak aggregated RPS β 5,000/s β 15,000 internal backend calls/s
Step D β Read:write ratio table
| Operation | Type | QPS @ 50K ingress | Notes |
|---|---|---|---|
| Route + proxy request | Read (pass-through) | ~45,000 | Simple path β backend |
| JWT validation | Read (crypto) | ~50,000 | Cache JWKS keys |
| Rate-limit counter | Read/write | ~50,000 | Redis INCR |
| Aggregation (multi-backend) | Read | ~5,000 | Fan-out parallel |
| Config / route reload | Read | ~1/min | Not per-request |
| Access log emit | Write (async) | ~50,000 events | Sample 1% to storage |
Ratio: gateway is ~100% read/proxy β it should almost never write business data.
What the numbers tell us
- ~10β12 stateless gateway instances at 50K RPS β scale horizontally behind a load balancer
- Keep gateway thin β auth, route, rate limit, log; business logic stays in services
- Redis ~100 MB for 1M rate-limit keys β use sliding window or token bucket per
(user_id, route) - Full logging at 50K RPS = ~2 TB/day β sample, structured logs, ship to async pipeline
- JWT verify at 50K/s β cache public keys; avoid introspection call per request
- Aggregation multiplies backend load β cache merged responses where possible (e.g., home feed)
Common mistake for this problem
Putting business logic in the gateway (discount calculation, DB queries) β adds latency and couples deployment. Another mistake: synchronous global rate limit with perfect accuracy β local counters + Redis sync is enough for MVP. Finally, sizing gateway for average RPS when 50K is already peak β always leave headroom for 2Γ spikes.
4. High-Level Design (HLD)
Components
| Component | Role |
|---|---|
| Gateway (Envoy/Kong/custom) | HTTP proxy + plugins/middleware chain |
| Router | Path β upstream service mapping |
| Auth middleware | JWT verify, scopes, API key lookup |
| Rate limiter | Token bucket / sliding window in Redis |
| Service registry | Consul/K8s DNS/upstream health |
| Aggregation layer | Parallel backend fan-out + merge |
| Logging pipeline | Access logs, trace IDs, metrics |
Flows
Simple proxied request
- Client
GET /api/v1/users/mewithAuthorization: Bearer <jwt> - Gateway assigns
X-Request-Id - Auth middleware validates JWT signature + expiry
- Rate limiter checks key
user:{sub} - Router forwards to User Service with internal headers
- Response streamed back; access log emitted
Aggregated request
- Client
GET /api/v1/dashboard - After auth, aggregation handler fans out:
GET user-service/profileGET order-service/recent?limit=5GET product-service/recommendations
- Wait for all (or partial with timeout policy)
- Merge JSON
{ profile, orders, recommendations } - Return single response
Rate limit exceeded
- Limiter returns 429 with
Retry-After - Request never hits backend
Trade-offs
- Central gateway vs sidecar per service β central simpler for clients; sidecar better per-team isolation at scale
- Sync JWT verify vs introspection β JWT local verify is fast; introspection handles instant revocation
- Global vs local rate limits β Redis cluster β global; per-node counters are faster but uneven
- Aggregation in gateway vs BFF service β gateway OK for small merges; complex BFF deserves its own service
5. Low-Level Design (LLD)
Route configuration (declarative)
routes:
- match: { pathPrefix: "/api/v1/users" }
upstream: user-service
auth: jwt
rateLimit: { key: userId, rpm: 600 }
- match: { pathPrefix: "/api/v1/orders" }
upstream: order-service
auth: jwt
rateLimit: { key: userId, rpm: 300 }
- match: { path: "/api/v1/dashboard" }
handler: aggregateDashboard
auth: jwt
rateLimit: { key: userId, rpm: 120 }
APIs (client-facing)
GET /api/v1/users/me
Authorization: Bearer <jwt>
β proxied to user-service
GET /api/v1/orders?status=open
β proxied to order-service
GET /api/v1/dashboard
β 200 {
"profile": { "name": "Ada", "tier": "pro" },
"recentOrders": [...],
"recommendations": [...]
}
GET /health
β 200 { "status": "ok" }
Internal headers added by gateway:
X-Request-Id: req_abc123
X-User-Id: 42
X-User-Scopes: orders:read,users:read
X-Forwarded-For: <client-ip>
Schema (API keys β optional)
api_keys (
id BIGSERIAL PRIMARY KEY,
key_hash VARCHAR(64) UNIQUE NOT NULL,
owner_id BIGINT NOT NULL,
tier VARCHAR(32) NOT NULL,
rpm_limit INT NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL
)
rate_limit_buckets (
bucket_key VARCHAR(128) PRIMARY KEY, -- e.g. "user:42" or "ip:1.2.3.4"
tokens INT NOT NULL,
last_refill TIMESTAMPTZ NOT NULL
)
Modules
GatewayServer
MiddlewareChain
- RequestIdMiddleware
- LoggingMiddleware
- AuthMiddleware
- RateLimitMiddleware
- RouterMiddleware
UpstreamClient
AggregateHandlers
- DashboardHandler
RouteConfigLoader
HealthCheckPoller
MetricsExporter
Algorithm β middleware chain
function handle(request):
ctx = newContext(request)
for mw in middlewareChain:
result = mw.process(ctx)
if result.shortCircuit:
return result.response -- e.g. 401, 429
upstreamResponse = router.forward(ctx)
return upstreamResponse
Algorithm β JWT auth (fail closed)
function authMiddleware(ctx):
token = parseBearer(ctx.headers.Authorization)
if token is null:
return shortCircuit(401, "missing token")
try:
claims = jwt.verify(token, jwksUrl, audience="api")
catch Expired:
return shortCircuit(401, "token expired")
catch InvalidSignature:
return shortCircuit(401, "invalid token")
ctx.userId = claims.sub
ctx.scopes = claims.scope.split(" ")
return continue
Algorithm β token bucket rate limit (Redis)
function rateLimitMiddleware(ctx):
key = "rl:user:" + ctx.userId
limit = tierLimit(ctx.userId) -- e.g. 600 requests/minute
refillRate = limit / 60 -- tokens per second
-- Lua script in Redis for atomicity
allowed, remaining, retryAfter = redis.tokenBucket(
key, capacity=limit, refillRate, cost=1
)
if not allowed:
return shortCircuit(429, headers={ Retry-After: retryAfter })
ctx.headers["X-RateLimit-Remaining"] = remaining
return continue
Algorithm β dashboard aggregation
function aggregateDashboard(ctx):
userId = ctx.userId
timeout = 2 seconds
results = parallelWithTimeout(timeout, [
() => upstream.get("user-service", "/users/" + userId + "/profile"),
() => upstream.get("order-service", "/orders/recent?userId=" + userId),
() => upstream.get("product-service", "/recommendations?userId=" + userId)
])
if results.profile.failed and results.orders.failed:
return 503("critical upstream unavailable")
return 200({
profile: results.profile.value or null,
recentOrders: results.orders.value or [],
recommendations: results.recommendations.value or []
})
Concurrency & correctness
- Gateway instances are stateless; shared state only in Redis/JWKS cache
- Circuit breaker per upstream avoids cascade failures
- Aggregation uses bounded thread pool + per-upstream timeouts
- Propagate same
X-Request-Idto all backends for distributed tracing
6. Scale evolution
| Stage | Change |
|---|---|
| MVP | Single region; NGINX/Envoy; Redis rate limits; static routes |
| Many services | Dynamic config from control plane; K8s service discovery |
| Global | Regional gateways; geo-routing; JWT keys cached locally |
| High security | mTLS gatewayβservice; OAuth2 introspection for sensitive routes |
| Heavy aggregation | Extract BFF services; gateway routes only |
7. Recap
- Gateway = cross-cutting edge: route, auth, limit, observe
- Fail closed on bad/missing credentials
- Rate limits in Redis with atomic token bucket
- Keep aggregation simple; push complex orchestration to BFF
Practice: redraw HLD from memory, then write middleware chain + token bucket pseudocode without looking.