FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

API Gateway Pattern & Circuit Breaking

Request routing, dynamic service discovery, rate limiting, and circuit breaker fault tolerance.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Centralize authentication and routing at the API Gateway layer
  • ✓Implement circuit breakers to isolate failing microservices
Full Technical Reference Document

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.

External Client Request
API Gateway Ingress Policy
Authenticate JWT & Enforce Rate Limit
Evaluate Circuit Breaker & Bulkhead
Route to Scoped Upstream Microservice
Conceptual teaching model synthesized from:envoy-proxy-repo,traefik-docs,nginx-docs

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 ConcernOwned Cleanly by API Gateway (Envoy / Kong / BFF)Must Stay Inside Downstream Domain Microservice
Coarse Authentication & Token Edge VerificationSignature/expiry check (JWKS verification), inject X-User-ID / X-Org-ID downstreamFine-grained BOLA / object ownership (Can user 42 mutate invoice 991?)
Per-Tenant Rate & Quota EnforcementGlobal token/request caps per API key (429 + Retry-After)Domain billing ledger atomic credit deductions
Fault Isolation & Load SheddingCircuit Breaking, upstream timeout budgets, concurrency Bulkheads, passive outlier ejectionDomain fallback responses (serving cached recommendations vs hard failure)
Protocol & Version TranslationREST/gRPC-Web transcoding, /v1 vs /v2 canary traffic splittingComplex 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:

  1. Stateful Circuit Breakers (CLOSED -> OPEN -> HALF-OPEN): Monitor sliding failure ratios (not just raw error counters, which flip wildly at different QPS!) or consecutive 5xx/timeouts; once breached, trip OPEN and fail fast locally (503 Service Unavailable) for recovery_timeout seconds so upstream worker pools don't exhaust connections waiting on 30-second socket hangs. After cooldown, enter HALF-OPEN carefully (allowing only bounded concurrent probes, serialized cleanly so 50 concurrent threads don't stampede through a single half-open test gate!).
  2. Thread-Safe Bulkheads & Retry Budgets (<= 20% of Active Traffic): Cap active concurrent in-flight requests per upstream cluster (Envoy max_requests / max_pending_requests) so one dying Recommendation Service cannot consume 100% of the Gateway's socket pool and kill Billing endpoints alongside it.
python
import asyncio
import time
from enum import StrEnum
​
class 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_threshold
self.recovery_seconds = recovery_seconds
self.state = BreakerState.CLOSED
self.consecutive_failures = 0
self.opened_at = 0.0
self._lock = asyncio.Lock()
self._half_open_probe_in_flight = False
​
async def allow_request(self) -> bool:
async with self._lock:
if self.state == BreakerState.CLOSED:
return True
if self.state == BreakerState.OPEN:
if time.monotonic() - self.opened_at >= self.recovery_seconds:
self.state = BreakerState.HALF_OPEN
self._half_open_probe_in_flight = True
return True
return False
# Serialize single probe while HALF_OPEN instead of leaking concurrent requests
if not self._half_open_probe_in_flight:
self._half_open_probe_in_flight = True
return True
return False
​
async def record_outcome(self, ok: bool) -> None:
async with self._lock:
self._half_open_probe_in_flight = False
if ok:
self.consecutive_failures = 0
self.state = BreakerState.CLOSED
else:
self.consecutive_failures += 1
if self.state == BreakerState.HALF_OPEN or self.consecutive_failures >= self.failure_threshold:
self.state = BreakerState.OPEN
self.opened_at = time.monotonic()

Alternatives and trade-offs

  • Infrastructure API Gateway (Envoy / Kong / Traefik Enterprise / 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 (BFF in 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 / Linkerd Sidecars): 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

  1. Cascading Retry Amplification (retryOn: 5xx Across 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 idempotent GET/idempotency-keyed operations with backoff + jitter and retry budgets (<= 10%–20%), preferably only at the outermost failing hop!
  2. Half-Open Probe Stampede Without Probe Concurrency Cap: Transitioning naive CircuitBreaker.state = "HALF-OPEN" on timeout without locking _half_open_probe_in_flight lets 500 queued requests slam the recovering microservice simultaneously the exact millisecond cooldown ends. Serialize or bound probes strictly.
  3. 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).
  4. Trusting Spoofed X-User-ID Headers Internally Without Gateway Boundary Isolation: If internal microservices accept pre-authenticated X-User-ID headers 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).
Reflect before revealing the guide

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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next