API Gateways
With many back-end services, you don't want every client to know every service's address, and you don't want every service to re-implement authentication, rate limiting and logging. An API gateway is a single entry point in front of the services that handles these cross-cutting concerns and routes each request to the right place.
mobile app --+ +--> users service
web app -----+--> [ API gateway ] ---+--> orders service
partners ----+ auth, rate limit, +--> catalog service
routing, logging, +--> (legacy monolith)
caching, transforms| Responsibility | What the gateway does |
|---|---|
| Routing | /api/orders/* → orders service; versioned or canary routes |
| Authentication | Validates tokens once; passes a trusted user id downstream |
| Rate limiting / quotas | Per API key, per user, per IP |
| Request shaping | Header injection, protocol translation (REST → gRPC), payload limits |
| Aggregation | One client call fans out to several services and merges the result |
| Observability | Access logs, metrics and a trace id for every request |
| Caching | Short-lived caching of public GET responses |
Popular choices: Kong, Envoy, NGINX, AWS API Gateway, Azure API Management, Apigee. A service mesh (Istio, Linkerd) handles similar concerns for traffic between services.
A gateway as a middleware pipeline
Gateways are usually built as a chain of filters. Each filter can reject the request early or pass it on. Here's a small one:
import hashlib
API_KEYS = {"key-mobile": "mobile-app", "key-partner": "acme-corp"}
ROUTES = [("/api/orders", "orders-svc"), ("/api/users", "users-svc"), ("/api/catalog", "catalog-svc")]
LIMIT_PER_WINDOW = 3
usage = {}
def authenticate(req):
client = API_KEYS.get(req.get("api_key"))
if not client:
return 401, "invalid API key"
req["client"] = client
def rate_limit(req):
count = usage.get(req["client"], 0) + 1
usage[req["client"]] = count
if count > LIMIT_PER_WINDOW:
return 429, "rate limit exceeded"
def route(req):
for prefix, service in ROUTES:
if req["path"].startswith(prefix):
req["upstream"] = service
return
return 404, "no route"
def add_trace_id(req):
raw = f"{req['client']}{req['path']}{usage[req['client']]}"
req["trace_id"] = hashlib.sha1(raw.encode()).hexdigest()[:8]
PIPELINE = [authenticate, rate_limit, route, add_trace_id]
def gateway(req):
for step in PIPELINE:
rejected = step(req)
if rejected:
return f"{rejected[0]} {rejected[1]} (stopped at {step.__name__})"
return f"200 forwarded to {req['upstream']} trace={req['trace_id']} as {req['client']}"
requests = [
{"api_key": "key-mobile", "path": "/api/orders/7"},
{"api_key": "bogus", "path": "/api/orders/7"},
{"api_key": "key-mobile", "path": "/api/users/me"},
{"api_key": "key-mobile", "path": "/api/unknown"},
{"api_key": "key-mobile", "path": "/api/catalog/42"},
{"api_key": "key-partner", "path": "/api/catalog/42"},
]
for r in requests:
print(f"{r['path']:<17} {gateway(r)}")/api/orders/7 200 forwarded to orders-svc trace=ad867211 as mobile-app
/api/orders/7 401 invalid API key (stopped at authenticate)
/api/users/me 200 forwarded to users-svc trace=721298e1 as mobile-app
/api/unknown 404 no route (stopped at route)
/api/catalog/42 429 rate limit exceeded (stopped at rate_limit)
/api/catalog/42 200 forwarded to catalog-svc trace=9e206f02 as acme-corp
Order matters: authentication runs first so that anonymous junk is rejected cheaply, and the rate limiter counts per authenticated client. Notice the 404 request still used up one of the mobile app's three requests, because rate limiting ran before routing.
Aggregation and Backend-for-Frontend
A product page might need data from five services. Instead of five round trips from a phone on a slow network, the gateway (or a Backend-for-Frontend, a small service per client type) calls them in parallel inside the data centre and returns one combined response:
services = { # latency inside the data centre (ms) and the data each returns
"catalog": (12, {"title": "Desk lamp", "price": 39.0}),
"stock": (8, {"in_stock": 14}),
"reviews": (25, {"rating": 4.6, "count": 182}),
"shipping": (15, {"eta_days": 2}),
}
MOBILE_RTT = 120 # one round trip from the phone
client_side = sum(MOBILE_RTT + ms for ms, _ in services.values()) # one call per service
aggregated = MOBILE_RTT + max(ms for ms, _ in services.values()) # one call, parallel fan-out
page = {}
for _, data in services.values():
page.update(data)
print(page)
print(f"client calls each service: {client_side} ms")
print(f"gateway aggregates: {aggregated} ms"){'title': 'Desk lamp', 'price': 39.0, 'in_stock': 14, 'rating': 4.6, 'count': 182, 'eta_days': 2}
client calls each service: 540 ms
gateway aggregates: 145 ms
Even if the phone made its four calls in parallel, it would still pay its slow round trip and the cost of four connections. Aggregation moves the chattiness to the fast network.
Canary routing
Gateways are also where new versions are rolled out gradually: send 5% of traffic to orders-v2, watch error rates, then increase. Hashing the user id keeps each user on one version, so nobody bounces between them:
import hashlib
from collections import Counter
def version_for(user_id, canary_percent):
bucket = int(hashlib.md5(user_id.encode()).hexdigest(), 16) % 100
return "orders-v2" if bucket < canary_percent else "orders-v1"
for percent in [5, 25, 50]:
split = Counter(version_for(f"user-{i}", percent) for i in range(10_000))
print(f"canary {percent:2}%: {dict(sorted(split.items()))}")
print("user-42 at 5% and at 25%:", version_for("user-42", 5), version_for("user-42", 25))canary 5%: {'orders-v1': 9528, 'orders-v2': 472}
canary 25%: {'orders-v1': 7492, 'orders-v2': 2508}
canary 50%: {'orders-v1': 4928, 'orders-v2': 5072}
user-42 at 5% and at 25%: orders-v1 orders-v1
Pitfalls
- Single point of failure: run several gateway instances behind a load balancer; keep them stateless (rate-limit counters in Redis).
- Business logic creep: a gateway that knows about discounts and inventory becomes a new monolith. Keep it to cross-cutting concerns.
- Latency: every filter adds time to every request; measure the gateway's own p99.
- Trusting headers: downstream services must accept identity headers only from the gateway (mTLS or a private network), never directly from the internet.
Tip: Generate a request id (trace id) at the gateway and pass it through every service call and log line. When something fails, that id is how you find all the pieces of one request.
Test yourself
Which concern is a good fit for an API gateway?
- Calculating order discounts
- Authenticating requests and enforcing rate limits
- Storing product data
- Running database migrations
Why does aggregation in a gateway or BFF help mobile clients?
- It removes the need for services
- It replaces several slow client round trips with one, while fan-out happens on the fast internal network
- It encrypts the data
- It caches everything forever
Why hash the user id for canary routing instead of choosing randomly per request?
- Hashing is faster than random numbers
- Each user consistently sees one version
- It sends more traffic to the canary
- Random numbers are not allowed in gateways