Skip to main content
← CONCEPTS / DISTRIBUTED SYSTEMS & NETWORKING
An end-to-end domain learning journey

API Gateway &
Layer 7 Protocols.

An API gateway terminates external Layer 7 traffic (HTTP/1.1, HTTP/2, gRPC, WebSockets) at the edge, centralizing TLS termination, rate limiting, auth verification, and protocol translation before routing to internal services.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To bound blast radius during partial cluster failures, centralize cross-cutting edge concerns in a single L7 proxy, but keep business logic out of it so the gateway never becomes a monolithic bottleneck.

TL;DR30-second simplified summary
▾

Core Mechanics: An API gateway is a reverse proxy operating at OSI Layer 7 (Application Layer).

Visual & Structural Flow: Depicts Layer 7 API Gateway Request & Protocol Routing Pipeline (Edge Client -> L7 Gateway (Envoy) -> gRPC / REST Pool -> WebSocket Pool); HTTP/2 gRPC Transcoding & Per-RPC Upstream Balancing (Browser (JSON) -> Envoy Gateway -> gRPC Pod 1 -> gRPC Pod 2); Gateway Pod Graceful Drain & Keepalive State Machine (SERVING -> DRAINING -> TERMINATED).

Trade-Offs & Production: Compare connection models, payload formats, and load-balancing requirements across L7 protocols. Production platforms pair an Envoy edge gateway with per-domain BFF services and graceful GOAWAY draining during rolling deploys.

Failure Modes & Application: Dive into gRPC L7 balancing, keepalive timeout alignment, and preventing cascading gateway timeouts.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
PRIME Core Invariants & Workload Constraints
Establish concrete scale, latency, memory, and concurrency bounds for API Gateway & Layer 7 Protocols before selecting data structures or storage components.
Failure Boundaries & Operational Trade-Offs
Identify hot-key skew, partial failures, resource leaks, and when simpler single-node or standard alternatives outperform complex designs.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is an API Gateway.

Why this matters: The mechanism: understand how an API Gateway works from first principles.

Think of What is an API Gateway as the intuition layer for API Gateway & Layer 7 Protocols: The mechanism: understand how an API Gateway works from first principles.

An API gateway is a reverse proxy operating at OSI Layer 7 (Application Layer). Unlike a Layer 4 load balancer that forwards raw TCP/UDP packets by IP and port, an L7 gateway parses HTTP headers, paths, cookies, gRPC metadata, and WebSocket upgrade handshakes—terminating TLS 1.3 once at the edge, validating JWTs against a cached JWKS, enforcing token-bucket rate limits, and transcoding REST/JSON to internal gRPC/Protobuf.

Edge Filter Chain

Layer 7 API Gateway Request & Protocol Routing Pipeline

Edge ClientL7 Gateway (Envoy)gRPC / REST PoolWebSocket Pool1. HTTP/2, HTTP/3, WSS2. TLS + JWT + Rate Limit3. Stateless h2c upstreams

An L7 gateway terminates edge protocols once and routes stateless RPCs and stateful sockets to isolated upstream pools.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need L7 Gateways (and why L4 proxies break gRPC).

Why this matters: The problem: see what breaks without L7 Gateways under real concurrency or scale.

Think of Why we need L7 Gateways (and why L4 proxies break gRPC) as the intuition layer for API Gateway & Layer 7 Protocols: The problem: see what breaks without L7 Gateways under real concurrency or scale.

Layer 4 load balancers break HTTP/2 and gRPC: because gRPC multiplexes thousands of RPCs over one long-lived TCP connection, an L4 proxy pins all RPCs from a client onto a single backend pod. Gateways also prevent WebSocket reconnect storms, buffer bloat on large uploads, and timeout mismatches between REST (5s) and WebSocket routes (60s+ idle).

L7 Stream Balancing

HTTP/2 gRPC Transcoding & Per-RPC Upstream Balancing

Before · Workload & Constraints
  • Bounds & SLOs
  • Bounds & SLOs
After · Verified State
  • Bounded outcome
  • Deterministic invariant enforcement

Terminating HTTP/2 at the L7 gateway lets it balance individual gRPC streams across all backend pods.

Engineering Decision Framework
Problem
How to implement API Gateway & Layer 7 Protocols without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To bound blast radius during partial cluster failures, centralize cross-cutting edge concerns in a single L7 proxy, but keep business logic out of it so the gateway never becomes a monolithic bottleneck.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When API Gateway & Layer 7 Protocols experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Strip Untrusted Edge Headers

Always overwrite X-User-* and untrusted X-Forwarded-For hops at the outermost listener to prevent header spoofing.

Retry Budgets <= 20%

Allow automatic retries only on idempotent GET/HEAD requests, bounded to <=20% of active traffic.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where API Gateways fit (and when to split BFFs).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where API Gateways fit (and when to split BFFs) as the intuition layer for API Gateway & Layer 7 Protocols: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Use an API gateway at the north-south ingress boundary for cross-cutting concerns; split UI aggregation into a BFF and high-volume /ws sockets into a dedicated pool.

ChoiceWhat it buysWhat it costs
North-South Edge Ingress (REST + gRPC)Centralizes TLS, WAF, JWKS auth, rate limiting, and observability (X-Request-ID).Adds 1–3 ms proxy hop; misconfigured plugins affect all routes globally.
Dedicated /ws WebSocket Pool (>50k sockets)Isolates memory-heavy persistent sockets from latency-sensitive REST/gRPC workers.Requires gradual connection draining (5–10 min) + jittered client reconnects on deploy.
Avoid: Domain Business Logic in Gateway PluginsMove fan-out joins and DB lookups into a separate Backend-for-Frontend (BFF) service.Heavy Lua/Wasm orchestration turns the gateway into an unmaintainable monolith.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Gateway Timeouts, Pools, and Rate Limits are managed.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of How Gateway Timeouts, Pools, and Rate Limits are managed as the intuition layer for API Gateway & Layer 7 Protocols: Operational control: configure bounds, failure handling, and safe production defaults.

Separate timeouts by route (5s for REST/gRPC, 60s idle for WebSockets), enable h2/h2c upstream pools, and align keepalive timeouts.

Lifecycle & Failure Recovery

How Gateway Timeouts, Pools, and Rate Limits are managed

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
# Envoy / Gateway route policy separating REST/gRPC timeouts from WebSockets
routes:
 - match: { prefix: "/v2/payments" }
 route:
 cluster: payments_grpc_h2
 timeout: 5s
 retry_policy:
 retry_on: "connect-failure,reset"
 num_retries: 1
 - match: { prefix: "/ws/ticker" }
 route:
 cluster: ws_stateful_pool
 timeout: 0s
 idle_timeout: 60s
 upgrade_configs:
 - upgrade_type: websocket
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: REST vs. gRPC vs. WebSockets.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: REST vs. gRPC vs. WebSockets as the intuition layer for API Gateway & Layer 7 Protocols: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Compare connection models, payload formats, and load-balancing requirements across L7 protocols.

ChoiceWhat it buysWhat it costs
REST (HTTP/1.1 & HTTP/2 + JSON)Native browser support, human-readable, cacheable via ETag/Cache-Control.Verbose JSON parsing and larger payloads at high RPS.
gRPC (HTTP/2 + Protobuf)5–10x smaller binary payloads, strict.proto contracts, bidirectional streaming.Requires L7 stream balancing and grpc-web/JSON transcoding for browsers.
WebSockets (RFC 6455)Full-duplex persistent TCP tunnel for real-time tickers, chat, and collaboration.Sticky per-connection state; vulnerable to thundering-herd reconnects on deploy.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: Envoy Edge + Graceful HTTP/2 GOAWAY Drain.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: Envoy Edge + Graceful HTTP/2 GOAWAY Drain as the intuition layer for API Gateway & Layer 7 Protocols: Production architecture: see how the components compose end to end under real load.

Production platforms pair an Envoy edge gateway with per-domain BFF services and graceful GOAWAY draining during rolling deploys.

Ingress Health & Drain

Gateway Pod Graceful Drain & Keepalive State Machine

Before · Workload & Constraints
  • Bounds & SLOs
  • Bounds & SLOs
After · Verified State
  • Bounded outcome
  • Deterministic invariant enforcement

Sending HTTP/2 GOAWAY frames during preStop drains in-flight RPCs cleanly without dropping active clients.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by API Gateways & System Design Deep Dives.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by API Gateways & System Design Deep Dives as the intuition layer for API Gateway & Layer 7 Protocols: Applied problems: connect these internals to concrete system design and debugging scenarios.

Dive into gRPC L7 balancing, keepalive timeout alignment, and preventing cascading gateway timeouts.

Request & State Flow

Problems solved by API Gateways & System Design Deep Dives

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

You place a Layer 4 Network Load Balancer in front of 10 gRPC backend pods. During a traffic spike, 1 pod hits 100% CPU while 9 pods sit idle. Why?

Recommended Learning Flow