FullStack AI Hub
Studio
System Design · 06. Architecture
10 min
10 steps
Beginner

API Gateways

Centralize TLS termination, auth, rate limiting, L7 routing, request coalescing, and BFF aggregation at the edge without creating a bottleneck.

System Design06. ArchitectureLesson 2 of 4
10 minBeginner10 steps

API Gateways

Centralize TLS termination, auth, rate limiting, L7 routing, request coalescing, and BFF aggregation at the edge without creating a bottleneck.

TLS HANDSHAKES
3–4× / Load
AUTH IMPLS
3 Copies
MOBILE P95
340 ms
PUBLIC PORTS
Exposed
TLS #1TLS #2TLS #3Mobile AppsUsers Svc54%Public IPCatalog Svc58%Public IPOrders Svc48%Public IP
client API request
authenticated mutation
coalesced / cached reply
BFF fan-out / upstream
rate-limited (429) / blocked
In This LessonStep 1 of 10
What You Will Master
  • ✓Eliminate duplicated auth, TLS, CORS, and rate-limiting code across services with a single L7 API Gateway
  • ✓Design Backend-for-Frontend (BFF) gateways tailored for mobile vs desktop payloads without chatty round trips
  • ✓Protect origins using token-bucket rate limits, request coalescing (singleflight), and circuit breakers at the gateway
  • ✓Keep the gateway thin (no business logic) and horizontally redundant across availability zones

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
L7 API Gateway (Kong / Envoy / AWS APIGW)Centralizing TLS, JWT validation, per-tenant rate limits, path routing, and access logs at the edgeBecomes a critical blast radius if overloaded with domain logic or deployed without multi-AZ HA
Backend for Frontend (BFF)Shaping lean mobile JSON vs rich web dashboards from multiple microservices in 1 client round tripAdds one BFF codebase per client surface (iOS/Android vs Web vs Partner API)
Request Coalescing (Singleflight)Collapsing 5,000 identical concurrent cache-miss requests for a hot product into 1 upstream callApplies strictly to idempotent GET requests and requires careful timeout sharing
Thin Gateway PrincipleKeeping routing, auth, and throttling fast in C++/Rust/Go proxies while leaving domain rules in servicesComplex cross-service workflows belong in dedicated orchestrators, never gateway plugins

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for API Gateways.

STEP 01 · PROBLEMJump to step →

Before a gateway: chatty clients & duplicated middleware

Without an **API Gateway**, mobile apps call 4 microservices directly over the public internet (`api-users`, `api-orders`, `api-catalog`, `api-pay`)—opening 4 separate TLS handshakes on slow 4G.

Worse, every team re-implements JWT verification, CORS, and rate limiting in 4 different languages—and one missed security patch exposes an internal endpoint to the entire internet.

watch:Exposing raw internal microservices directly couples mobile clients to your internal topology and duplicates security logic everywhere.

Cross-Cutting ConcernsPublic Topology CouplingMiddleware Duplication
STEP 02 · SOLUTIONJump to step →

Introduce an L7 API Gateway: 1 TLS edge & clean routing

Placing an **L7 API Gateway** (`Envoy`, `Kong`, `NGINX`) at `api.shop.com` gives clients **one TLS 1.3 connection** while keeping every backend service hidden on a private VPC subnet.

The gateway inspects HTTP paths and headers (`/users/*`, `/catalog/*`, `/orders/*`) to route cleanly to aligned internal services—freeing you to refactor backend hosts without ever breaking mobile apps.

good:One public entry point decouples external API contracts from internal microservice URLs, ports, and language stacks.

L7 Path RoutingTLS TerminationPrivate VPC Isolation
STEP 03 · TECHNIQUEJump to step →

Offload JWT validation & identity headers at the edge

Instead of 20 services calling the Auth database on every request, the gateway caches public **JWKS signing keys** locally in RAM and verifies `Authorization: Bearer <JWT>` in `< 0.3 ms`.

Valid requests get trusted internal headers (`X-User-Id`, `X-Tenant-Role`) injected before forwarding; forged or expired tokens are dropped with `401` right at the perimeter.

idea:Always strip any client-supplied `X-User-Id` header at the gateway before injecting verified identity claims—preventing header spoofing!

Edge JWT VerificationJWKS Key CacheHeader Sanitization
STEP 04 · SOLUTIONJump to step →

Enforce per-tenant rate limits & API quotas at the perimeter

One buggy enterprise integration loop or scraper can burn 100% of your backend capacity in seconds. Backing the gateway with a fast **Redis Token Bucket** enforces per-API-key quotas (`Free: 60 rpm`, `Pro: 6,000 rpm`).

Abusive traffic receives instant `429 Too Many Requests` + `Retry-After` at the edge—**never consuming a single backend worker thread or DB query**.

good:Edge rate limiting turns a noisy-neighbor outage into a harmless 429 response for only the misbehaving tenant.

Per-Tenant QuotasToken Bucket at EdgeNoisy Neighbor Shield
STEP 05 · TECHNIQUEJump to step →

Backend for Frontend (BFF): tailor payloads per device

A desktop dashboard needs 40 fields across 4 services, while an iOS home screen wants 6 compact fields in **one round trip** over cellular 4G. One generic REST API either over-fetches for mobile or forces 6 chatty calls.

Deploy thin, aligned **BFF Gateways** (`Mobile BFF`, `Web BFF`, `Partner API`) that fan out in parallel internally over fast gRPC and return exact screen-shaped responses.

idea:Netflix, Spotify, and Airbnb use dedicated BFFs so mobile teams evolve screens rapidly without bloating web or partner contracts.

Backend for Frontend (BFF)Payload TrimmingParallel Fan-Out Aggregation
STEP 06 · SOLUTIONJump to step →

Stop thundering herds with request coalescing & edge caching

At 9:00 AM sharp, a flash-sale link goes live and **5,000 users simultaneously request `GET /products/drop-1`** while its cache entry just expired.

With **Request Coalescing (Singleflight)** at the gateway, only **1** upstream request hits `Catalog Svc` while the other 4,999 wait 18 ms and share the exact same response!

good:Singleflight request coalescing turns a 5,000-rps stampede for one hot key into a single calm upstream query.

Request CoalescingSingleflightStampede Prevention
STEP 07 · TECHNIQUEJump to step →

Protocol translation (REST → gRPC) & zero-break API versioning

Browsers and public partners love readable **REST JSON** (`/v2/orders`), while internal microservices run fastest on binary **gRPC Protobuf**. The gateway transparently transcodes external JSON into internal gRPC.

It also routes `/v1/*` and `/v2/*` cleanly—allowing internal teams to ship breaking v2 schemas while older mobile apps keep working seamlessly.

idea:Envoy gRPC-JSON transcoding gives you public REST ergonomics and internal binary gRPC performance from a single Protobuf definition.

REST-to-gRPC TranscodingAPI VersioningSchema Evolution
STEP 08 · SOLUTIONJump to step →

Trip circuit breakers & timeouts at the gateway

If `Reviews Svc` hangs for 30 seconds, an unprotected gateway fills every connection slot waiting on Reviews—starving `Checkout` across the entire company.

Configure **per-route timeouts (`500 ms`), bulkheads, and circuit breakers** at the gateway: when `Reviews` crosses 50% errors, the breaker snaps **OPEN**, returning a fast cached fallback (`2 ms`) so Checkout stays untouched.

watch:Always enforce per-upstream connection pools (bulkheads) inside your API Gateway so one slow service cannot steal sockets from healthy ones.

Edge Circuit BreakerConnection BulkheadsGraceful Fallback
STEP 09 · TRADE-OFFJump to step →

Avoid the "Smart Gateway" trap & eliminate the edge SPOF

Two classic gateway disasters: first, running a single gateway instance (instant **SPOF** for your whole company); second, stuffing pricing math and SQL queries into gateway plugins until it morphs into an untestable monolith.

Keep the gateway **stateless and thin** (routing, auth, limits, observability only) and run **3 aligned multi-AZ nodes** behind an L4 Network Load Balancer.

watch:Keep the gateway dumb on business logic and smart on networking—deploy across 3 AZs so losing a whole zone causes zero downtime.

Multi-AZ Gateway FleetThin Gateway PrincipleZero Edge SPOF
STEP 10 · RECAPJump to step →

Complete Edge Gateway & BFF reference architecture

A production **API Gateway** forms a razor-thin, multi-AZ perimeter: terminating TLS 1.3, verifying JWTs against local JWKS, enforcing Redis per-tenant rate limits, coalescing hot GETs, routing into dedicated Mobile/Web BFFs, and tripping circuit breakers before slow services cascade.

good:Gateway Checklist: Multi-AZ HA · TLS 1.3 · Local JWKS Auth + Header Strip · Redis Token Bucket · Singleflight Coalescing · BFF Aggregation · Per-Route Bulkheads.

Production API GatewayEdge Defense-in-DepthBFF + Singleflight

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h 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.