Mental model
An API Gateway sits logically one layer above a raw TCP/HTTP reverse proxy: it presents a unified external API facade across fractured backend microservices while centralizing cross-cutting edge policies—JWT verification, tenant rate limiting, request/response header normalization, Distributed Trace ID injection (traceparent), and fault-isolating Circuit Breakers + Bulkheads. Done well, internal services stay lean and isolated from public chaos; done carelessly—stuffing complex business joins, DB lookups, or un-budgeted auto-retries inside the gateway—turns the gateway into a slow single-point-of-failure "distributed monolith" that amplifies small brownouts into platform-wide outages.
Theory
Understanding where an edge Reverse Proxy ends and a domain-aware API Gateway / Edge Router begins prevents redundant security layers and cascading retry storms:
| Control Plane Concern | Owned Cleanly by API Gateway (Envoy / Kong / BFF) | Must Stay Inside Downstream Domain Microservice |
|---|---|---|
| Coarse Authentication & Token Edge Verification | Signature/expiry check (JWKS verification), inject X-User-ID / X-Org-ID downstream | Fine-grained BOLA / object ownership (Can user 42 mutate invoice 991?) |
| Per-Tenant Rate & Quota Enforcement | Global token/request caps per API key (429 + Retry-After) | Domain billing ledger atomic credit deductions |
| Fault Isolation & Load Shedding | Circuit Breaking, upstream timeout budgets, concurrency Bulkheads, passive outlier ejection | Domain fallback responses (serving cached recommendations vs hard failure) |
| Protocol & Version Translation | REST/gRPC-Web transcoding, /v1 vs /v2 canary traffic splitting | Complex multi-step orchestration & Saga compensation logic |
Circuit Breakers, Outlier Detection, and Avoiding the Retry-Storm Multiplier
Naive error handling tries every failing backend call 3 times blindly. Across a 3-hop chain (Gateway -> Orchestrator -> VectorDB), 3 x 3 x 3 = 27x retry amplification hits an already-overloaded VectorDB precisely when it is gasping for breath! Protect downstream clusters using two complementary primitives:
- Stateful Circuit Breakers (
CLOSED->OPEN->HALF-OPEN): Monitor sliding failure ratios (not just raw error counters, which flip wildly at different QPS!) or consecutive5xx/timeouts; once breached, tripOPENand fail fast locally (503 Service Unavailable) forrecovery_timeoutseconds so upstream worker pools don't exhaust connections waiting on 30-second socket hangs. After cooldown, enterHALF-OPENcarefully (allowing only bounded concurrent probes, serialized cleanly so 50 concurrent threads don't stampede through a single half-open test gate!). - Thread-Safe Bulkheads & Retry Budgets (
<= 20%of Active Traffic): Cap active concurrent in-flight requests per upstream cluster (Envoymax_requests/max_pending_requests) so one dying Recommendation Service cannot consume100%of the Gateway's socket pool and kill Billing endpoints alongside it.
pythonimport asyncioimport timefrom enum import StrEnumclass BreakerState(StrEnum):CLOSED = "CLOSED"OPEN = "OPEN"HALF_OPEN = "HALF_OPEN"class AsyncCircuitBreaker:"""Thread/coroutine-safe circuit breaker preventing thundering HALF-OPEN probe storms."""def __init__(self, failure_threshold: int = 5, recovery_seconds: float = 20.0) -> None:self.failure_threshold = failure_thresholdself.recovery_seconds = recovery_secondsself.state = BreakerState.CLOSEDself.consecutive_failures = 0self.opened_at = 0.0self._lock = asyncio.Lock()self._half_open_probe_in_flight = Falseasync def allow_request(self) -> bool:async with self._lock:if self.state == BreakerState.CLOSED:return Trueif self.state == BreakerState.OPEN:if time.monotonic() - self.opened_at >= self.recovery_seconds:self.state = BreakerState.HALF_OPENself._half_open_probe_in_flight = Truereturn Truereturn False# Serialize single probe while HALF_OPEN instead of leaking concurrent requestsif not self._half_open_probe_in_flight:self._half_open_probe_in_flight = Truereturn Truereturn Falseasync def record_outcome(self, ok: bool) -> None:async with self._lock:self._half_open_probe_in_flight = Falseif ok:self.consecutive_failures = 0self.state = BreakerState.CLOSEDelse:self.consecutive_failures += 1if self.state == BreakerState.HALF_OPEN or self.consecutive_failures >= self.failure_threshold:self.state = BreakerState.OPENself.opened_at = time.monotonic()
Alternatives and trade-offs
- Infrastructure API Gateway (
Envoy/Kong/TraefikEnterprise /AWS API Gateway): High-throughput native C++/Go/Nginx data planes enforcing TLS, JWKS JWT verification, outlier ejection, and per-route rate limits consistently across all languages without duplicating middleware libraries per repo; weak at complex screen-specific JSON reshaping. - Backends for Frontends (
BFFin FastAPI / Next.js): Separate lightweight client-tailored gateways (web-bff,mobile-bff) aggregating downstream microservices into clean UI responses while leaving low-level L7 proxy concerns at the edge gateway; avoids bloating one central enterprise gateway with frontend business rules. - Service Mesh East-West Proxies (
Istio/LinkerdSidecars): Moves circuit breaking, mTLS, and outlier ejection directly alongside every internal pod-to-pod call rather than concentrating fault tolerance solely at the north-south external edge—essential once internal fan-out depths grow, though heavier on sidecar memory and ops complexity.
Failure modes and misconceptions
- Cascading Retry Amplification (
retryOn: 5xxAcross Multiple Hops): Retrying aggressively at both the API Gateway and downstream internal services turns a brief overload into an unrecoverable retry storm (N^k). Restrict retries strictly to idempotentGET/idempotency-keyed operations with backoff + jitter and retry budgets (<= 10%–20%), preferably only at the outermost failing hop! - Half-Open Probe Stampede Without Probe Concurrency Cap: Transitioning naive
CircuitBreaker.state = "HALF-OPEN"on timeout without locking_half_open_probe_in_flightlets500queued requests slam the recovering microservice simultaneously the exact millisecond cooldown ends. Serialize or bound probes strictly. - Gateway Coupling ("Distributed Monolith Anti-Pattern"): Embedding customer SQL queries, multi-step workflow orchestration, or shared domain model validation inside gateway plugins makes every tiny team deploy require a risky central gateway release. Keep gateway rules strictly generic (identity, routing, quotas, telemetry, resilience).
- Trusting Spoofed
X-User-IDHeaders Internally Without Gateway Boundary Isolation: If internal microservices accept pre-authenticatedX-User-IDheaders injected by an API Gateway while still reachable directly inside a permissive container network, lateral compromise lets attackers impersonate any user cleanly (zero-trust internal mTLS or signed internal JWTs prevent header spoofing).
Decision scenario
Your microservice AI platform exposes /v1/chat, /v1/rag, and /v1/billing across Python and Go internal services and suffered a cascading outage when slow VectorDB queries backed up connection pools across the entire gateway. Deploy a stateless, horizontally scaled Envoy-based API Gateway enforcing cached JWKS signature verification, Redis-backed per-tenant rate limits (429 + Retry-After), per-cluster concurrency bulkheads (max_requests isolating /v1/rag from /v1/billing), passive outlier detection + locked HALF-OPEN circuit breaking (503 fast-fail after consecutive 5xx/timeout thresholds), strict 2 s upstream timeouts on non-streaming paths, and internal mTLS so microservices trust identity headers exclusively from verified gateway certificates.
Learning outcomes
- Partition responsibilities cleanly between edge API Gateways (coarse auth, quotas, routing, resilience) and domain microservices (BOLA checks, business rules).
- Implement three-state Circuit Breakers (
CLOSED,OPEN,HALF-OPEN) without triggering probe-recovery stampedes. - Prevent platform-wide brownouts using per-upstream Bulkheads and bounded Retry Budgets.
- Avoid turning a central API Gateway into a fragile business-logic distributed monolith.
Trade-offs
Centralized API Gateways unify external security policies, observability, and circuit-broken fault isolation across polyglot teams, yet require strict high-availability redundancy, mTLS internal boundary protection, and discipline against creeping domain logic inside gateway configs.