Skip to main content
Cloud Native & Microservices

Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy)

Staff / Principal

Complete FAANG-level system design blueprint for API Gateway & Reverse Proxy (Kong / Envoy).

Production Scale: 1 Million RPS • 5,000 Microservices

Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy): Request Topology

5 Stages · 4 Sizing Benchmarks

Request traversal order for Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy) (Cloud Native & Microservices) under target workload 1 Million RPS • 5,000 Microservices:

Stage 1

Thread-Per-Core Edge Data Plane (Envoy / Pingora)

Stage 2

xDS Control Plane & Route Registry

Stage 3

JWT & Policy Filter Chain

Stage 4

Active Health Check & Circuit Breaker Manager

Functional Requirements

  • •Terminate TLS 1.3 and route incoming HTTP/2 and gRPC traffic across 5,000 backend microservices
  • •Authenticate JWT and OAuth2 bearer tokens using cached JWKS public keys at the edge
  • •Apply dynamic per-route rate limiting, header transformations, and weighted canary traffic splitting
  • •Propagate hot route, cluster, and endpoint configuration updates without dropping active connections

Non-Functional Requirements

  • •Sub-1ms p99 proxy routing and token verification overhead at 1 Million RPS
  • •Zero-downtime configuration reloads across edge proxy worker threads
  • •Cascading-failure isolation via per-upstream circuit breakers and outlier detection

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Production Scale Target1 Million RPS
Peak Throughput5,000 Microservices
Read-to-Write Ratio10 : 1
Availability Target99.999% SLA (Five 9s)

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

+---------------------------------------------------------------------------------------------------+
| [INTERNET INGRESS] Public API Clients, SDKs, Third-Party Developers (TLS 1.3 & mTLS Support)      |
+-------------------------------------------------+-------------------------------------------------+
                                                  |
                                                  v
+-------------------------------------------------+-------------------------------------------------+
| [EDGE ENVOY PROXY] Multi-Threaded C++ Event Loop (epoll/kqueue) | Downstream Connection Pooling    |
+-------------------------------------------------+-------------------------------------------------+
                                                  |
                        +-------------------------+-------------------------+
                        |                                                   |
                        v                                                   v
+-----------------------+-----------------------+   +-----------------------+-----------------------+
| [AUTHENTICATION & RATE LIMITING FILTER]       |   | [OBSERVABILITY & TRACING TIER]                |
| - JWT & OAuth 2.1 Token Validation (EdDSA)    |   | - Distributed OpenTelemetry Tracing           |
| - Global Redis Leaky Bucket Rate Limiting     |   | - Prometheus Metric Extraction (P99 latency)  |
+-----------------------+-----------------------+   +-----------------------+-----------------------+
                                                  |
                                                  v
+-------------------------------------------------+-------------------------------------------------+
| [UPSTREAM MICROSERVICES] Internal Kubernetes Cluster Pods via gRPC / HTTP/2 Keep-Alives           |
+---------------------------------------------------------------------------------------------------+

1Thread-Per-Core Edge Data Plane (Envoy / Pingora)

Terminates TLS 1.3 with session resumption and runs lock-free epoll/io_uring event loops pinned to CPU cores for non-blocking L7 proxying.

2xDS Control Plane & Route Registry

Streams incremental route, cluster, and endpoint diffs over persistent bidirectional gRPC streams to all proxy nodes within milliseconds.

3JWT & Policy Filter Chain

Verifies asymmetric JWT signatures against in-memory JWKS caches and evaluates WAF, CORS, and quota rules inline before upstream dispatch.

4Active Health Check & Circuit Breaker Manager

Tracks upstream connection pools, ejects unhealthy endpoints via passive outlier detection, and trips circuit breakers to shed load.

5Access Telemetry & Trace Exporter

Buffers structured access logs, RED metrics, and W3C TraceContext spans asynchronously to ClickHouse and OpenTelemetry collectors off the request path.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy) at a scale of 1 Million RPS • 5,000 Microservices requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureAP (Maximum Availability & Zero-Drop Edge Routing)CP (Synchronous Control Plane Route Validation per Request)Reverse proxies prioritize ultra-low latency routing and 100% uptime; if the central control plane (xDS) partitions, edge proxies serve cached route configurations rather than dropping client requests.
Proxy Architecture ModelAsynchronous Event-Driven C++ (Envoy/Kong)Thread-Per-Request Gateway (Java Spring)Enables handling 500,000 concurrent idle connections with minimal memory footprint (under 30MB per proxy instance) using non-blocking epoll.
Configuration DiscoveryDynamic xDS gRPC Protocol (Envoy)Static Configuration Reloads (Nginx reload)Allows zero-downtime hot-reloading of routes, endpoints, and TLS certificates without dropping active TCP connections.
Rate Limiter TopologyTwo-Tier Local Token Bucket + Central RedisStrict Global Redis Calls for Every RequestEvaluates 90% of requests against local in-memory thread tokens, querying Redis only on burst spikes to avoid network latency penalties.
Authentication StrategyEdge Stateless JWT Signature Verification (Ed25519)Introspection API Calls to Auth ServerValidates caller claims in sub-millisecond local CPU operations, shielding the central OAuth provider from billions of daily queries.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 1 Million RPS • 5,000 Microservices demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy):

1. Upstream Service Cascading Brownout

Blast Radius: A slow backend microservice exhausts gateway connection pools and worker threads.

Remediation Protocol: Envoy Outlier Detection ejects failing service endpoints from the load balancer pool after 5 consecutive 5xx errors for a 30-second cooldown.

2. Distributed Denial of Service (DDoS) Flood

Blast Radius: SYN flood and HTTP/2 rapid reset attacks overwhelm gateway CPU resources.

Remediation Protocol: Kernel-level SYN cookies and BPF filters drop malicious IP packets before socket buffer allocation.

3. xDS Configuration Server Partition

Blast Radius: Gateway instances cannot receive updated route definitions during cloud network partition.

Remediation Protocol: Envoy retains the last known good configuration in memory and continues serving existing routes safely.

4. Memory Leak from Buffer Accumulation

Blast Radius: Large request body uploads consume proxy RAM leading to OOM termination.

Remediation Protocol: Hard streaming buffers limit maximum request headers to 16KB and stream large payloads directly to disk storage.

Production Algorithm Implementation: Envoy Dynamic Health Check & Circuit Breaker Filter

YAML

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy):

# Envoy Cluster Circuit Breaker Configuration
clusters:
- name: payment_service_cluster
  connect_timeout: 0.25s
  type: STRICT_DNS
  lb_policy: ROUND_ROBIN
  circuit_breakers:
    thresholds:
    - priority: DEFAULT
      max_connections: 1024
      max_pending_requests: 256
      max_requests: 2048
      max_retries: 3
  outlier_detection:
    consecutive_5xx: 5
    interval: 10s
    base_ejection_time: 30s
    max_ejection_percent: 50

Design API Gateway & Dynamic Reverse Proxy (Kong / Envoy): Design Scope & Constraints Summary

This staff / principal blueprint balances 4 core functional workflows against 3 availability and latency constraints tailored for 1 Million RPS • 5,000 Microservices. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Cloud Native & Microservices.

Architectural FAQs & Interview Deep Dives

1How does an Envoy-style control plane push dynamic route updates across 5,000 microservices without dropping active requests?

A centralized xDS management server streams incremental route, cluster, and endpoint diffs over persistent gRPC bidirectional streams to every proxy worker. Each proxy validates the incoming configuration snapshot, atomically swaps thread-local Read-Copy-Update (RCU) routing tables so in-flight HTTP/2 streams finish on the previous snapshot, and drains retired upstream connections gracefully after a configurable grace period.

2Why do high-throughput proxies adopt a thread-per-core event-loop architecture instead of thread-per-request blocking I/O at 1M RPS?

Allocating one OS thread per incoming connection exhausts memory and incurs heavy kernel context-switching overhead under high concurrency. Pinning one non-blocking epoll or io_uring event loop per CPU core keeps socket state, upstream connection pools, and TLS buffers lock-free within L1/L2 CPU caches, allowing a single proxy fleet to sustain sub-millisecond forwarding overhead at 1M RPS.

3How can the gateway perform TLS termination and JWT verification inside a sub-1ms latency budget?

Edge nodes terminate TLS 1.3 using session ticket resumption and OCSP stapling to eliminate extra round trips, preferring ECDSA certificates for faster asymmetric handshakes. For authorization, workers cache downstream JWKS public keys in local shared memory with background refresh timers so signature checks execute purely in CPU without synchronous calls to an identity provider.

4Which overload controls prevent a single degraded upstream service from exhausting gateway sockets and causing cascading timeouts?

Every upstream cluster enforces strict circuit-breaker thresholds on max active connections, pending queue depth, and active retries, failing fast with HTTP 503 when saturated. Passive outlier detection ejects unhealthy endpoints returning consecutive 5xx errors from the load-balancing ring, while retry budgets cap aggregate retries at a small fraction (e.g., 10-20%) of total request volume.