← Building blocks

Spread traffic across servers

Scaling & loadfundamental

One server cannot handle the request rate, or a single server is a single point of failure.

Say it like this

The API tier is stateless, so I put it behind a load balancer that health-checks each instance and spreads requests, which gives me horizontal scaling and no single server as a point of failure.

Basic solution

Run several stateless servers behind a load balancer that distributes requests and health-checks them.

nginxHAProxyAWS ALB / NLBEnvoy

Balancer with health checks and draining

Requests spread over healthy instances by least-connections. The failed instance is out of rotation after two missed checks; the draining one finishes in-flight work and receives nothing new.

How it works

  1. DNS points the service name at the load balancer's address. For redundancy that address is a floating IP shared by a pair of balancers, or an anycast address announced from several, so the balancer itself is not a single machine.
  2. The balancer either accepts the client's connection and makes its own connection to a backend (L7, which lets it read the HTTP request) or forwards the packets as they are (L4, which only sees TCP). It picks the backend with an algorithm: round robin takes turns, least connections picks the backend with the fewest requests in flight, and hashing picks by a field such as the client IP.
  3. It calls a health endpoint on every backend every few seconds. After a backend fails a couple of checks in a row the balancer stops sending it traffic, and after a couple of successes it adds the backend back.
  4. When a new instance starts, it registers with the balancer (the orchestrator adds it to a target group) and starts receiving traffic once its health checks pass.
  5. Removing an instance is a drain: the balancer stops sending it new connections, lets the requests already in flight finish, then withdraws it.

L4 vs L7

  • L4 balances TCP connections: fast and works for any protocol, but it cannot see URLs or headers, so it cannot route by path or retry a request. L7 balances HTTP requests: it can route by path, add headers, terminate TLS and retry idempotent requests, at the cost of more CPU per request.

Worked example

URL shortener redirect tier

  • 40K redirects/s at peak. One Node or Go instance serves ~5K req/s of this shape comfortably, so 8 instances carry peak; run 12 so losing a zone (a third) still leaves capacity.
  • Health check: GET /healthz every 5 s, 2 failures to mark unhealthy, 2 successes to recover. A crashed instance is out of rotation within ~10 s; the balancer retries idempotent GETs that failed at connection time, so users see few errors.
  • Algorithm: least-connections, because redirect latency varies with cache hits and misses; round robin would pile requests onto an instance that is slow on a miss.
  • Rate limiter: limits are per user key, so the balancer does not need stickiness; any instance can serve any request and the counter lives in Redis.
  • The balancer itself: a managed ALB spans three zones and scales automatically, or two HAProxy nodes with a virtual IP and keepalived.

Variants and when each wins

Round robin / weighted round robin

  • Each new request goes to the next backend in turn, with weights letting a bigger instance take more turns. It wins when requests cost about the same and instances are equal.

Least connections / least load

  • Each new request goes to the backend with the fewest requests in flight. It wins when request cost varies, because a backend busy with a slow request is not handed more.

Consistent hashing on a key

  • Requests with the same user or key always go to the same instance. It wins when an instance keeps something per client, such as a local cache or a WebSocket, and it concentrates hot keys on one instance.

Client-side balancing (service mesh)

  • Each client holds the list of backends and picks one itself, as gRPC and Envoy sidecars do. It wins by removing a network hop and a central choke point, and it needs service discovery so clients learn the current list.

Recommendation: a managed L7 balancer with least-connections for HTTP APIs; consistent hashing only where stickiness is needed; L4 for raw throughput or non-HTTP protocols.

Failure modes

Balancer as the single point of failure

  • You notice the whole service is down even though every backend is healthy. It happens because there was one balancer instance and it failed. Fix it with a managed balancer spread over zones, or two nodes sharing a virtual IP, and health-check the balancer itself from outside.

Health check that lies

  • You notice traffic going to an instance that returns errors, or every instance pulled at once during a brief dependency outage. It happens because the check only tests that the process is alive, or because it calls every dependency and fails when any of them blips. Fix it by checking the instance's own readiness, keeping dependency checks separate, and never letting a shared dependency failure remove every instance.

Uneven load

  • You notice one instance at 90% CPU while the others idle. It happens because long-lived connections (HTTP/2, WebSockets) stay pinned to the instances that were up first, or because sticky sessions concentrate users. Fix it by balancing per request at L7 and capping connection lifetime so clients reconnect and spread out.

Thundering herd on scale-up

  • You notice a freshly started instance times out under full traffic. It happens because the balancer sent it a full share while its caches were empty and its runtime was still warming. Fix it with slow-start weighting so a new instance ramps up over a minute.

Lost client IP

  • You notice rate limits and logs only ever see the balancer's address. It happens because the balancer made its own connection to the backend, so the backend sees the balancer as the client. Fix it by having the balancer pass the real address in the X-Forwarded-For header or the PROXY protocol, and trusting that header only when it comes from the balancer.

Interviewer follow-ups

Answer out loud before you open each one.

What stops the load balancer from being a single point of failure?

Run it as a redundant pair or a managed service spread over zones, reached through a floating IP, DNS with health checks, or anycast. The balancer is small and stateless, so two of them with failover is enough.

When do you need sticky sessions and how do you avoid needing them?

You need them when an instance holds state for a client: an in-memory session or a WebSocket. Avoid them for HTTP by moving session state to Redis or a signed cookie; for WebSockets accept affinity and keep a registry of which server holds which user.

How do you deploy without dropping requests?

Drain each instance: mark it unhealthy or deregister it, wait for in-flight requests to finish within a timeout, then replace it. Do this one batch at a time so capacity stays above peak throughout.

What should a health check test?

That this instance can serve: the process is up, it has finished warming, and it can reach what it strictly needs. It should not fail because an optional dependency is slow, or a shared dependency outage will remove every instance at once.

Connections

Built on
Consistent hash ring
Pairs with
Keep servers stateless · Pull broken instances out of rotation · Scale out, not up · One front door for many services · Put a reverse proxy in front
Pulls against
Push to the browser in real time
Used in
URL Shortener (TinyURL / bit.ly) · Distributed Rate Limiter

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Application Load BalancerLoad balancerCloud Load BalancingApplication Gateway, Azure Load BalancerNGINX, HAProxy, Envoy