SD System Design In Depth
0%
lesson system-designapigateway

API gateway vs load balancer

Module 3.1: Network Protocols & Service Communication Updated Sep 17, 2026
📄 Cheat Sheet
API Gateway vs Load Balancer vs Reverse Proxy: when to use what?
Software Developer Diaries API Gateway vs Load Balancer vs Reverse Proxy: when to use what? Watch on YouTube ↗

Directly answers this unit's question with clear diagrams: what each component does, where the responsibilities overlap, and when you need one, two or all three.

0:00 / --:--

Under the Hood: L4/L7 Traffic Management Primitives

Engineers often conflate Load Balancers and API Gateways because modern proxies (like Envoy, Nginx, and Traefik) can perform both roles. However, in enterprise architecture, they operate at distinct layers of the OSI stack with different performance profiles and responsibilities.

The Multi-Layer Ingress Architecture

flowchart TD Client["Client Traffic"] --> L4LB["Layer 4 Load Balancer (AWS NLB / Maglev: TCP/UDP Wire Speed)"] L4LB --> L7GW["Layer 7 API Gateway (Envoy / Kong: HTTP Parsing)"] subgraph GatewayFunctions ["API Gateway Cross-Cutting Concerns"] L7GW --> Auth["JWT Auth & OAuth2 Verification"] L7GW --> RateLimit["Distributed Rate Limiter (Redis Token Bucket)"] L7GW --> Transform["Payload Transformation & Header Injection"] L7GW --> Routing["Path-Based Routing (/v1/users -> User Service)"] end GatewayFunctions --> S1["User Microservice"] GatewayFunctions --> S2["Order Microservice"] GatewayFunctions --> S3["Payment Microservice"]

Comparison: Load Balancer vs API Gateway

DimensionLayer 4 / 7 Load Balancer (AWS NLB/ALB)API Gateway (Envoy, Kong, Zuul)
OSI LayerLayer 4 (TCP/UDP, e.g. AWS NLB) or Layer 7 (HTTP, e.g. AWS ALB, which also routes by host/path and can authenticate users via OIDC)Layer 7 (Application Layer)
Primary GoalDistribute raw network traffic evenly across serversProvide unified business API orchestration & security
Cross-Cutting FeaturesHealth checks, TLS termination, round-robinJWT validation, rate limiting, request transformation, monetization
Throughput & LatencyVery high throughput at L4 (microsecond overhead); L7 balancers that terminate TLS pay similar TLS costsLower per-instance throughput; TLS plus JWT validation, policy plugins and transformations add CPU per request

Worked example: a request through both

A mobile client calls GET /v1/orders/123.

  1. DNS resolves api.example.com to an L4 load balancer (for example AWS NLB or Google Maglev). It picks a gateway instance by hashing the connection 5-tuple and forwards packets without reading HTTP. Overhead is microseconds.
  2. The gateway (for example Envoy, Kong or AWS API Gateway) terminates TLS, validates the JWT signature and expiry, checks the caller's rate limit, and matches the path /v1/orders/* to the order service.
  3. The gateway picks one of the order service's healthy instances (its own L7 load balancing, for example least-requests) and forwards the request, adding headers such as the authenticated user ID and a trace ID.
  4. If the order service returns 503, the gateway may retry once on another instance, within a retry budget.

Rate limit arithmetic: if a partner is allowed 100 requests per second and the gateway fleet has 10 instances, either each instance enforces 10 per second locally (cheap, but uneven if traffic is not spread evenly) or all instances consult a shared counter (accurate, but an extra network hop of about 1 ms per request).

Responsibility table

CapabilityL4 load balancerL7 load balancerAPI gateway
SeesIP, port, TCP or UDPHTTP method, path, headersHTTP plus API identity and policy
Spread load across instancesPer connectionPer requestPer request, often delegated
TLS terminationOptional (pass-through common)CommonCommon
Path or host routingNoYesYes
Authentication and API keysNoLimitedYes
Rate limiting and quotas per clientNoBasicYes, often per plan
Request or response transformationNoHeadersYes
ExamplesAWS NLB, Google Maglev, IPVSAWS ALB, NGINX, HAProxy, EnvoyKong, Apigee, AWS API Gateway, Envoy-based gateways

Failure modes

  • Gateway as bottleneck: CPU for TLS and JWT validation scales with request rate; autoscale it and keep policies cheap.
  • Timeouts that do not nest: if the gateway times out at 30 s but clients give up at 10 s, the gateway keeps work alive that nobody is waiting for.
  • Health checks that lie: a TCP health check passes even when the HTTP application returns 500 for every request; use an HTTP health endpoint that checks the app's real readiness.
Check yourself Question 1 of 3
Local rate limits and skew apply
From: Worked example: a request through both

A partner's quota is 100 requests per second. Ten gateway instances each enforce 10 per second locally. The partner sends 80 per second, but 40% of that lands on a single instance. What happens?

Load-Balancing Algorithms (one slow server)

Each server handles one request at a time (FIFO queue, mean service 50 ms). Server 1 (amber bar) is f× slower. All four balancers get exactly the same request stream. Random and Round-robin ignore load and keep sending the slow node 1/N of the traffic; Least-connections and Power-of-two-choices see its growing in-flight count and route around it. Bars show in-flight requests (queued + in service) per server.

Press Run to stream requests.

Key Takeaways

Load balancers focus on traffic distribution, connection routing, and high-throughput health checking.
API gateways handle application-level cross-cutting concerns: authentication, token buckets, and path routing.
High-scale architectures place high-speed L4 load balancers in front of distributed L7 API gateway clusters.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue