Load balancers, proxies and API gateways

Between your users and your servers sits a layer of traffic components: load balancers, proxies and API gateways. People mix up the names because one product often does several of these jobs. In an interview you need to say clearly what each job is, where it sits, and what can go wrong. This lesson covers all three, with load balancing in the most detail because it is asked most often. Examples use an online shop.

1. Who Does What

  • Load balancer: spreads incoming requests across many servers and stops sending traffic to servers that fail. Its job is scale and availability.
  • Reverse proxy: sits in front of your servers and forwards client requests to them. It can also end TLS, compress responses, cache, and shield servers from slow clients. A load balancer is a reverse proxy that picks among several servers.
  • Forward proxy: sits in front of clients and forwards their requests to the internet, for example a company proxy that filters traffic. It is the opposite direction, and seldom a design topic.
  • API gateway: a reverse proxy at the front of your APIs that also handles API concerns: authentication, rate limits, routing to the right service, and monitoring. Its job is one controlled entry point.
flowchart LR
  C["Clients"] --> E["CDN or edge"]
  E --> LB["Load balancer"]
  LB --> GW1["API gateway"]
  LB --> GW2["API gateway"]
  GW1 --> S1["Order service"]
  GW1 --> S2["Catalog service"]
  GW2 --> S1
  GW2 --> S2

Traffic from outside to inside (clients to your system) is called north-south traffic, and these components handle it. Traffic between your own services is called east-west traffic. A service mesh handles that, and it is covered in the microservices lesson.

2. Load Balancers

2.1 Layer 4 vs Layer 7

Aspect Layer 4 (transport) Layer 7 (application)
What it sees IP addresses and ports only The full HTTP request: host, path, headers, cookies
Routing choices By connection By URL path, host name, header, or method
Speed and cost Very fast, low CPU, handles millions of connections More CPU, since it parses requests and often ends TLS
Protocols Any TCP or UDP traffic (databases, games, custom protocols) HTTP, HTTPS, HTTP/2, gRPC, WebSockets
Extra features Few TLS termination, retries, caching, redirects, compression, request limits
Example products AWS Network Load Balancer, HAProxy in TCP mode AWS Application Load Balancer, NGINX, Envoy

A common setup uses both: a layer 4 balancer at the very front for raw speed and a stable address, then layer 7 balancers behind it that route by path. Use layer 7 when you need content-based routing, for example sending /api/orders to the order service and /images to a static server. For gRPC, use a layer 7 balancer that understands HTTP/2, because gRPC keeps long connections that a layer 4 balancer would pin to one server.

2.2 Choosing the Next Server

  • Round robin: take servers in turn. Simple, and good when requests cost about the same and servers are equal.
  • Weighted round robin: bigger servers get more turns. Use it with mixed machine sizes, or to send 5% of traffic to a new version.
  • Least connections: send to the server with the fewest active connections. Better when request cost varies a lot or connections are long (WebSockets, streaming).
  • Least response time: send to the server answering fastest. It adapts, but it needs measurement.
  • Power of two choices: pick two servers at random and send to the less loaded one. It is almost as good as checking all servers and avoids many balancers all rushing to the same "least loaded" server.
  • Hash of a key (IP, user id, URL): the same key goes to the same server. Use consistent hashing so that adding or removing a server moves only a small share of keys. It suits caches and stateful servers.

A concrete case: if 90% of requests take 10 ms and 10% take 500 ms, round robin can pile slow requests onto one unlucky server, while least connections steers new work away from it.

Sticky sessions send a user back to the same server, usually by cookie. They hide a design problem: if that server dies, the user loses their session, and traffic spreads unevenly. Prefer stateless servers with the session kept in a shared store such as Redis. Use stickiness only when you must, for example for WebSocket connections that are bound to one server (see the real-time lesson).

2.3 Health Checks

  • Active checks: the balancer calls an endpoint such as /health on every server every 5 to 10 seconds. It removes a server after several failures in a row (for example 3) and adds it back after several successes. Several failures in a row avoid removing a server because of one dropped packet.
  • Passive checks: the balancer watches real traffic. A server that returns errors or times out is marked bad automatically.
  • Shallow vs deep checks. A shallow check says "the process is alive". A deep check also tests dependencies such as the database. Deep checks are dangerous: if the database slows down, every server fails its check, the balancer removes all of them, and a database slowdown becomes a total outage. Keep health checks shallow, or check only what that one server truly needs. Many balancers also fail open: if all servers look unhealthy, they send traffic to all of them instead of none.
  • Slow start: a new server gets traffic gradually, so it can warm its caches and connections.
  • Connection draining: before removing a server (a deploy or a scale-down), stop sending it new requests and let current ones finish. On AWS this wait is called the deregistration delay, and the default is 300 seconds.

2.4 The Load Balancer Is Also a Risk

One load balancer is a single point of failure. Fix this at three levels:

  • Managed cloud balancers run across several availability zones for you.
  • Self-run balancers use two or more in an active-passive pair with a floating virtual IP address, or several active ones behind DNS or anycast.
  • Capacity: balancers have limits too (new connections per second, bandwidth, requests per second). Managed balancers scale on their own, but not instantly. A sudden spike of ten times the normal traffic can be throttled, so plan ahead or ask the provider to prepare capacity before big events.

For multiple regions, use DNS or a global anycast service to send users to the nearest healthy region, and a regional load balancer inside each one.

2.5 Timeouts, Retries and Ejecting Bad Servers

A balancer also decides what to do when a request goes wrong:

  • Timeouts should shrink as you go deeper. If the client waits 30 seconds, the gateway waits 10 and the service waits 5, then the inner call gives up first and the outer layers can still answer. If the inner timeout is longer, the outer layers keep working on a request nobody is waiting for any more.
  • Retry carefully. A balancer or proxy can retry a failed request on another server, which hides a single server failure from the user. Retry only safe, repeatable requests (such as GET) by default. Retrying a POST can create a duplicate unless the request has an idempotency key.
  • Limit retries with a budget. If every layer retries three times, one user request can become 27 calls to a struggling service. Allow retries only up to a small share of traffic (for example 10% extra) so a slowdown does not turn into a retry storm.
  • Eject bad servers. If a server returns several 5xx errors in a row, remove it for a cool-down period (for example 30 seconds), then try it again. This reacts faster than waiting for the next health check.

2.6 Sizing Example

The shop gets about 650 million requests a day, which is about 7,500 a second on average. Peak is 4x the average: 30,000 requests per second. One app server (Tomcat on an m5.xlarge) handles about 2,000 simple requests per second, so you need 30,000 ÷ 2,000 = 15 servers. To survive the loss of one of three zones, you need 15 × 1.5 = 22.5, so 24 servers, 8 per zone. The load balancer must be spread across all three zones, with cross-zone balancing so a zone with fewer healthy servers does not get overloaded.

2.7 What to Monitor

Watch the request rate, the 4xx and 5xx error rates, and the number of healthy servers (alert when it drops below what peak traffic needs). Separate errors made by the balancer itself (502, 503, 504) from errors returned by your servers, because they point to different problems. Track backend response time at p99, active and rejected connections, and the certificate expiry date.

3. Reverse Proxies

A reverse proxy does more than forward requests:

  • TLS termination: it handles the encrypted connection with the client, so app servers deal with plain HTTP (see the HTTP versions lesson for where to end TLS).
  • Buffering slow clients: a phone on a bad network sends a request over several seconds. The proxy waits for the whole request, then forwards it quickly. Without the proxy, an app server thread would be tied up for that time.
  • Connection pooling: it keeps a few long-lived connections to the backend and shares them among many clients.
  • Compression and caching: it compresses responses and can serve cached static content.
  • Headers: it adds the client's real IP in X-Forwarded-For and a request id for tracing. Trust these headers only when they come from your own proxy.
  • Protection: it hides the backend addresses, limits request sizes and applies basic rate limits. A web application firewall (WAF) often runs here too. It blocks known attack patterns such as SQL injection, and works together with DDoS protection at the edge.

4. API Gateways

An API gateway is the front door of your APIs. It handles the concerns that every service would otherwise repeat:

  • Authentication: check the API key or token (for example verify a JWT) once, at the edge, and pass the user's identity to the service (see the authentication lesson).
  • Rate limiting and quotas: per user, per API key or per route (see the rate limiter lesson).
  • Routing and versioning: map /v1/orders to the order service, and send a share of traffic to a new version.
  • Translation: turn REST calls into gRPC calls for internal services, or change request and response formats.
  • Aggregation: combine results from several services into one response for a client (the backend-for-frontend pattern from the API design lesson).
  • Resilience: timeouts, retries and circuit breakers for calls to services.
  • Observability: logs, metrics and trace ids for every request.

Do not confuse an API gateway with the WebSocket gateways in the real-time lesson, which only hold client connections. The costs of an API gateway:

  • An extra hop, usually a few milliseconds.
  • A single point of failure and a bottleneck. Run several instances behind a load balancer, and monitor them closely.
  • A temptation to put business logic in it. A gateway with order and pricing rules becomes a hidden monolith that every team must change. Keep it thin: security, routing and policies, not business decisions.

4.1 How They Compare

Component Where it sits Main job Examples
Load balancer In front of identical servers Spread traffic, remove failed servers AWS ALB and NLB, HAProxy
Reverse proxy In front of servers TLS, buffering, caching, compression NGINX, Envoy
API gateway At the front of your APIs Authentication, rate limits, routing, monitoring Kong, AWS API Gateway, Apigee
Service mesh Beside each service (east-west) Service-to-service security, retries, telemetry Istio, Linkerd

In small systems, one NGINX or one cloud load balancer does all of these jobs. In large systems you separate them. Say which jobs your design needs, and then which component does them.

4.2 Managed or Self-Run?

A managed balancer (AWS ALB or NLB, Google Cloud Load Balancing) needs no patching, spans zones for you and scales automatically. It is the default answer at the edge. Choose self-run software (NGINX, Envoy, HAProxy) when you need routing features the managed service lacks, or when you run on-premises or in Kubernetes (as an ingress). You then own patching, scaling and high availability.

5. Following One Request

Here is a request to GET /v1/orders/456 from a customer, from start to finish:

  1. DNS turns the name into an address: instant if cached, 20 to 120 ms if not.
  2. CDN or edge near the user ends the TLS connection. Static content is answered here. Everything else is passed on.
  3. Load balancer in your region picks a healthy gateway. This adds about 1 to 2 ms.
  4. API gateway checks the token, applies the rate limit, picks the order service and forwards the call. This adds about 2 to 5 ms.
  5. Order service reads the order, perhaps calling other services, and replies. This is usually most of the time.
  6. The response goes back along the same path.

The balancer and gateway together add roughly 3 to 7 ms to a request budget of 100 to 300 ms, which is small. The bigger cost is availability. Hops in a chain multiply: three components at 99.99% each (0.9999 as a fraction, meaning each works 9,999 times out of 10,000) give 0.9999 × 0.9999 × 0.9999 = 0.9997, or 99.97%, about 2.6 hours of downtime a year instead of 52 minutes. Each extra layer must earn its place.

6. Common Pitfalls

  • A single load balancer or gateway with no redundancy.
  • Deep health checks that remove every server when a shared dependency slows down.
  • Sticky sessions as a fix for servers that keep state, instead of making them stateless.
  • No connection draining, so deployments cut off in-flight requests.
  • Wrong algorithm for the traffic: round robin for long, uneven connections.
  • Idle timeouts out of order, so the balancer sends requests on connections the backend already closed (see the HTTP versions lesson).
  • Business logic in the gateway.
  • No spare capacity for the loss of a zone, or for a sudden traffic spike.
  • Trusting X-Forwarded-For from anyone, which allows clients to fake their IP address.
  • Retries at every layer with no budget, which multiply load on a server that is already struggling.
  • Retrying non-idempotent requests such as POST without an idempotency key.

7. Interview Questions This Lesson Prepares You For

  • What is the difference between a layer 4 and a layer 7 load balancer? Layer 4 routes by IP and port and is very fast. Layer 7 reads HTTP, so it can route by path or header, end TLS and retry, at more CPU cost. Use layer 7 for content-based routing, and layer 4 for raw speed or non-HTTP traffic.
  • Which load balancing algorithm would you use? Round robin for similar short requests, least connections when request cost or connection length varies, and consistent hashing when the same key must reach the same server, for example a cache.
  • How does the load balancer know a server is down? Active health checks on an endpoint, plus passive checks on real traffic. Remove a server after several failures. Keep checks shallow so a database problem does not remove every server.
  • How do you avoid the load balancer being a single point of failure? Run it across zones (managed) or as an active-passive or active-active group with a virtual IP, DNS or anycast. Plan its capacity for spikes.
  • Load balancer, reverse proxy and API gateway: what is the difference? The load balancer spreads traffic. The reverse proxy shields and optimizes servers. The gateway adds API policies such as authentication and rate limits. One product can do several of them.
  • The load balancer retries a failed POST on another server. What can go wrong? The first server may have processed it, so the order or payment is created twice. Retry only safe, repeatable requests by default, require an idempotency key for the rest, and cap retries with a budget.
  • Why not put all logic in the API gateway? It becomes a bottleneck and a hidden monolith. Keep it to security, routing and policies, and leave business logic to the services.