System designDeep dives8 min read

Load Balancing in Depth

This lesson is for software engineers preparing for system design interviews who draw a load balancer in front of their servers and are then asked "Which algorithm? What happens to open connections when you deploy? What if the load balancer itself dies?" A load balancer is easy to draw and easy to get wrong in the details, and those details are where the deep dive points are.

By the end you will be able to choose between Layer 4 and Layer 7 balancing, pick an algorithm that fits the traffic, design health checks, handle long-lived connections such as WebSockets, remove the load balancer as a single point of failure, and route users across regions.

How load balancing shows up in the interview

Most candidates add a load balancer during the high-level design without comment. That is fine for short stateless requests. It becomes a deep dive when the system holds state per connection (chat, multiplayer games, live collaboration) or when the interviewer probes availability. On SmartIntervu's system design rubric the discussion counts toward "deep dive and scalability" and "trade-offs."

Layer 4 vs Layer 7

A Layer 4 balancer routes by IP address and port. It forwards TCP or UDP connections without reading their contents, so it is fast, protocol-agnostic and can handle very high connection counts. It cannot route by URL path or header, and if traffic is encrypted it passes TLS through untouched.

A Layer 7 balancer understands HTTP. It terminates TLS, reads the path, headers and cookies, and can route /api/upload to one pool and /api/search to another, retry a failed request on a different server, add headers, or rate-limit per client. The cost is more work per request and the need to hold certificates.

A common shape is both: a Layer 4 tier at the edge spreading connections across a fleet of Layer 7 proxies, which do the HTTP-aware routing to services.

Algorithms and when each fits

  • Round robin sends each new request to the next server in turn. It works when requests are short, similar in cost and servers are identical.

  • Weighted round robin gives larger servers proportionally more traffic, useful during a migration to bigger machines or when shifting a small percentage of traffic to a canary.

  • Least connections sends new work to the server with the fewest open connections. It fits long-lived connections or requests with very uneven duration, where round robin would keep piling work onto a server still busy with slow requests.

  • Least response time prefers servers that are answering fastest, combining connection count with observed latency. It reacts to a server that is degraded but not dead.

  • Power of two choices picks two servers at random and sends to the less loaded one. It sounds too simple, but it avoids a real problem: when many balancer nodes all chase the single least-loaded server based on slightly stale data, they flood it together. Sampling two keeps the load nearly as even as checking every server, without the herd.

  • Consistent hashing maps a key, such as a user ID or cache key, to a server so the same key always lands on the same server. It is the right choice when servers hold state per key (cache shards, per-user sessions). When a server is added or removed, only about 1/N of keys move, instead of almost all of them with hash mod N. Virtual nodes, many points per server on the hash ring, keep the spread even.

Tip

When asked "which algorithm?", answer with the traffic shape first: "Requests are short and uniform, so round robin is fine" or "Connections last hours, so least connections." The reasoning is what gets scored.

Health checks

The balancer must stop sending traffic to servers that cannot handle it.

Active health checks probe each server on a schedule, for example an HTTP request to /health every 5 seconds, marking it unhealthy after 3 consecutive failures and healthy again after 2 successes. With those settings, a dead server keeps receiving traffic for up to about 15 seconds, so state your detection window and whether that is acceptable.

Passive health checks, also called outlier detection, watch real traffic: a server returning a burst of 5xx errors or timeouts is ejected for a cool-down period. They react faster to partial failures that a simple probe misses.

Use both. One subtlety interviewers like: keep /health shallow. If every server's health check also checks the shared database, a brief database slowdown marks every server unhealthy at once, the balancer has nowhere to send traffic, and a small problem becomes a full outage. Report "this process can serve requests," and handle dependency failures in the request path.

Stateless servers vs sticky sessions

The easiest servers to balance are stateless: any server can handle any request because session data lives in a shared store or a signed token. Then servers can be added, removed and replaced freely.

Sticky sessions pin a client to one server, usually with a cookie set by a Layer 7 balancer. They let a server keep session state in memory, but they cost you: load becomes uneven when a few clients are heavy, and when a server dies its users lose their sessions. In an interview, default to stateless and use stickiness only when there is a reason, such as an in-memory game state or a WebSocket connection, which is sticky by nature.

Long-lived connections and draining

A WebSocket or gRPC stream stays open for minutes or hours on the server that accepted it. That changes several things.

  1. The algorithm is least connections, because the balancer only makes a decision when a connection opens, and you want those decisions to even out the long-running total.

  2. New servers start empty. After scaling out, old servers keep their connections while new ones fill slowly. Some systems periodically ask clients on the busiest servers to reconnect so the balancer can rebalance them.

  3. Deploys need connection draining. To replace a server, the balancer stops sending it new connections, then the server tells its clients to reconnect, and only then does it shut down. Without draining, every deploy drops all of its connections at once.

  4. Reconnects must be spread out. If a server holding 50,000 connections dies, 50,000 clients reconnect. Clients should use exponential backoff with random jitter, so the reconnects arrive over many seconds rather than in one spike that knocks over the next server.

The load balancer as a single point of failure

A single balancer in front of a perfectly redundant fleet is still one machine. Ways to remove it:

  • An active-passive pair sharing a floating IP. The passive node watches the active one with heartbeats, typically using a protocol such as VRRP, and takes over the IP when the active one stops responding.

  • A horizontally scaled tier, where several balancer nodes sit behind a Layer 4 tier, DNS or anycast, so losing one node removes only part of the capacity.

  • A managed cloud load balancer, which is itself built this way. Saying "I'd use the cloud provider's managed balancer, which runs redundantly across zones" is a fine answer, as long as you can explain what it does for you.

Global load balancing

With users on several continents, the first decision is which region serves them.

DNS-based routing answers the same hostname with different IPs depending on the user's location or region health. It is simple and widely used, but failover is only as fast as clients and resolvers honor the record's TTL. With a 60-second TTL, some clients keep using a failed region for a minute or longer, because some resolvers hold records past their TTL.

Anycast announces the same IP address from many locations, and internet routing delivers each packet to the nearest one. Failover is fast because a failed location stops announcing the address and routes converge. It is ideal for DNS servers and CDN edges. For long TCP connections there is a small risk that a routing change moves a connection mid-stream to a location that does not know it, which is one reason anycast edges usually terminate connections and proxy to the origin.

Worked example: the WebSocket tier of a chat system

The interviewer asks how 10 million concurrent users stay connected to your chat system, and what happens during deploys and failures.

Weak answer: "A load balancer distributes the WebSocket connections across chat servers using round robin, and we autoscale."

Strong answer:

Capacity. Assume each connection server comfortably holds 50,000 idle-heavy WebSocket connections, a figure we would confirm with a load test:

10,000,000 connections / 50,000 per server = 200 servers
plus 25% headroom for failures and deploys = 250 servers

Balancing. A Layer 4 tier spreads TCP connections across a pool of Layer 7 proxies that terminate TLS and complete the WebSocket upgrade, choosing a connection server by least connections. Each connection server registers "user U is on server S" in a session registry, so the chat service can route messages to the right server.

Health. Proxies probe each connection server's /health every 5 seconds and eject it after 3 failures; passive checks eject a server whose upgrades start failing. Health checks do not test the database.

Deploys. We replace servers in batches of about 5 percent. Each draining server stops accepting new connections, sends clients a reconnect message spread over several minutes, and exits when its count reaches zero. Five percent of 250 servers is about 12 servers, or roughly 600,000 connections per batch, which the remaining fleet absorbs within its 25 percent headroom.

Failure. If a server dies abruptly, its 50,000 clients reconnect with jittered exponential backoff, starting from a random delay of 0 to 5 seconds. They resync missed messages from the last sequence number they saw, so nothing is lost. The registry entries for that server expire through a short TTL heartbeat, so the chat service stops routing to it within seconds.

Regions. Users are routed by DNS to the nearest region; each region runs its own connection tier and a cross-region link delivers messages between users in different regions.

Mistakes that cost points

  • Round robin for long-lived connections. Say least connections and explain why.

  • Deep health checks. Checking the shared database in every health probe can turn a slowdown into an outage.

  • No plan for deploys. With persistent connections, every deploy is a reconnection event; describe draining.

  • Forgetting the balancer can fail. Name how the balancer tier itself is made redundant.

  • Ignoring reconnect storms. Jittered backoff on the client is part of the design, not an implementation detail.

Practice it

Sketch the path of one request from a user's browser to your database for any system you know, naming every balancing decision, its algorithm and its health check. Time yourself to ten minutes.

To see how this fits into the full interview, go back to How to Run a Deep Dive.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Queues and Event Streams in Depth

    Choose between a message queue and an event log, state delivery semantics and ordering scope, size partitions and consumers, and handle lag, poison messages and the dual-write problem.

    9 min read

  • Search and Geospatial Indexes in Depth

    Explain inverted indexes, analyzers and ranking, keep a search index in sync with change data capture, support partial-word search, and size a find-nearby feature with geohashes or quadtrees.

    8 min read

  • How to Run a Deep Dive in a System Design Interview

    Pick the riskiest part of your design and work through it in five steps (numbers, options, trade-off, decision, failure mode), with a chat message fan-out as the worked example.

    9 min read

  • Choosing and Scaling a Database

    Choose a database from the data's access patterns, explain how indexes, replicas and shards change performance and what each costs, and walk through two storage decisions with numbers.

    8 min read