System design concepts · Talking Over the Network

Load Balancers, API Gateways and Service Discovery Explained

Between the user and your code sit a few layers whose whole job is deciding where each request goes. Get them right and the rest of the system can fail gracefully.

What you'll be able to explain
  • Distinguish L4 and L7 load balancing
  • Choose a balancing algorithm for a workload
  • Explain health checks, draining and sticky sessions
  • Describe what an API gateway does (and shouldn't do)
  • Explain service discovery and the service mesh

The front door, layer by layer

CLIENTUsersNETWORKGlobal LB / DNSpick regionNETWORKL4 load balancerTCP, fastNETWORKAPI gateway / L7auth, routesSERVICEOrders svcSERVICEUsers svcSERVICESearch svc/orders/users/search
A typical request path. Each layer has a different job.

L4 vs L7

Layer 4 (transport) Layer 7 (application)
Sees IPs, ports, TCP/UDP HTTP: paths, headers, cookies, bodies
Can route by Connection URL path, host, header, user, version
Speed Very fast, cheap More CPU per request
TLS Usually passes through Terminates (decrypts)
Examples AWS NLB, IPVS, Maglev Nginx, Envoy, HAProxy, AWS ALB

Balancing algorithms

Algorithm How Best for
Round robin Next server in turn Identical servers, similar requests
Weighted round robin Bigger servers get more Mixed hardware, canaries (5% weight)
Least connections Fewest open connections Long or variable requests, WebSockets
Least response time / EWMA Fastest recent latency Mixed latency backends
Power of two choices Pick 2 random, choose less loaded Huge fleets; near-optimal with little state
Consistent hash Hash(key) → server Cache affinity, sticky routing (Sharding and Consistent Hashing Explained)
Tip

Power of two random choices is a lovely interview detail. Picking the better of just two random servers avoids the herd effect of everyone choosing the single "least loaded" server, while getting most of the benefit.

Health checks, draining and stickiness

  • Health checks: the LB pings /healthz every few seconds. Liveness ("process is up") differs from readiness ("can serve traffic now: DB reachable, caches warm"). Route only to ready instances.
  • Connection draining: before removing an instance (deploy, scale-in), stop sending new requests and let in-flight ones finish within a timeout.
  • Sticky sessions: pin a user to one server via a cookie. Useful for legacy stateful apps, but it ruins even balancing and makes failures lose sessions. Prefer stateless servers with shared session storage.
Common trap

A health check that calls the database. If the DB has a hiccup, every instance reports unhealthy and the LB removes the whole fleet — turning a small blip into a total outage. Keep liveness checks shallow and readiness checks tolerant.