Load balancing in system design

A load balancer spreads incoming requests across a pool of servers so no single server is overloaded, and it stops sending traffic to servers that fail health checks. Layer 4 balancers route by IP address and port and are fast; layer 7 balancers read the HTTP request and can route by path, header or cookie. In an interview, say where balancing happens (DNS, edge, between services), which algorithm you chose and why, and how the balancer itself avoids being a single point of failure.

By Published 7 min read

1. What a load balancer does

Once a service runs on more than one machine, something has to decide which machine handles each request. That something is a load balancer: a dedicated appliance, a software proxy, a managed cloud service, or a library inside the client. Beyond spreading load, it usually does four more jobs: removing unhealthy servers, terminating TLS, giving clients one stable address while servers come and go, and sometimes enforcing limits such as request rates or body sizes.

2. Why interviewers ask about it

Nearly every high-level design starts with "clients hit a load balancer". Interviewers then probe whether that box means anything to you. Typical follow-ups: what algorithm, what happens when a server dies mid-request, how you deploy without dropping traffic, how a WebSocket service balances long-lived connections, and what happens when the balancer itself fails.

3. Layer 4 vs layer 7

Where the balancer looks, and what that allows
Layer 4 (transport)Layer 7 (application)
Routes onSource and destination IP and portHTTP method, path, host, headers, cookies, gRPC service
Sees request contentNo; it forwards bytes of a connectionYes; it parses each request
Speed and costVery fast, little CPU per connectionMore CPU per request, especially with TLS
BalancesConnectionsIndividual requests, even several on one HTTP/2 connection
Can doSimple, protocol-agnostic forwarding (databases, game servers, raw TCP)Path routing (/api to one pool, /images to another), canary splits, retries, header rewrites, auth checks
Typical useIn front of layer 7 proxies, or for non-HTTP trafficAPI gateways, ingress, service mesh sidecars
Where the balancer looks, and what that allows. Scroll sideways on a small screen.

A detail worth knowing: with HTTP/2 or gRPC, many requests share one long-lived connection. A layer 4 balancer pins all of them to one backend, which can leave a new server idle for a long time. Balancing these protocols per request needs layer 7 or client-side balancing.

4. Balancing algorithms

Common algorithms and when each fits
AlgorithmHow it picksGood whenWeak when
Round robinNext server in orderServers are equal and requests cost about the sameSome requests are much heavier, or servers differ
Weighted round robinLike round robin, with more turns for bigger serversMixed machine sizes, or shifting a small share to a canaryLoad per request varies
Least connectionsServer with the fewest open connectionsLong or uneven requests, WebSocketsNeeds a shared view of counts across several balancer instances
Least response timeLowest recent latency, often combined with connection countBackends degrade unevenlyCan send a flood to a server that just looked fast
Power of two choicesPick two at random, send to the less loadedMany balancers with partial information; large poolsSlightly worse than perfect least connections with full information
Hash (IP, user, key)Same input goes to the same serverAffinity: caches, session state, per-user countersUneven keys create hot servers; use consistent hashing so pool changes move few keys
Common algorithms and when each fits. Scroll sideways on a small screen.
import random

def smooth_weighted_rr(weights: dict):
    # add each weight to a running total, pick the largest,
    # then subtract the sum of weights from the winner
    current = {s: 0 for s in weights}
    total = sum(weights.values())
    while True:
        for s, w in weights.items():
            current[s] += w
        best = max(current, key=current.get)
        current[best] -= total
        yield best

def least_connections(active: dict) -> str:
    return min(active, key=active.get)

def power_of_two(active: dict) -> str:
    a, b = random.sample(list(active), 2)
    return a if active[a] <= active[b] else b

picker = smooth_weighted_rr({"A": 5, "B": 1, "C": 1})
print("".join(next(picker) for _ in range(14)))  # AABACAAAABACAA
print(least_connections({"A": 12, "B": 3, "C": 7}))  # B
Sketches of three pickers (run with python3; outputs in comments)

Why power of two choices is popular: in a quick simulation of 100 servers and 100,000 requests, picking one server at random left the busiest one 85 requests above the average, while picking the less loaded of two random servers left it only 2 above. Two samples get most of the benefit of checking every server, without any balancer needing the full picture.

5. Health checks, draining and slow start

  • Active health checks. The balancer calls an endpoint such as /healthz every few seconds and removes a server after several failures in a row. Keep the check honest but shallow: if it also tests the database, one database blip can mark every server unhealthy at once.
  • Passive checks (outlier detection). The balancer watches real traffic and ejects a server whose error rate or latency spikes.
  • Connection draining. Before a server is removed for a deploy, stop sending it new requests and let in-flight ones finish within a timeout.
  • Slow start. A freshly added server with cold caches gets a gradually increasing share instead of its full share at once.
  • Retries with care. Retrying a failed request on another server hides blips, but only for idempotent requests, and with a retry budget so retries do not double the load during an outage.

6. Sessions, state and long-lived connections

Sticky sessions (affinity by cookie or IP) keep a user on the same server so in-memory session data works. They make scaling and deploys harder: a server cannot leave without logging its users out, and one heavy user can overload a server. The cleaner design is stateless app servers with sessions in a shared store such as Redis, or in a signed token. Affinity still has good uses: keeping a user's cache warm, or routing chat users to the server holding their WebSocket. For WebSocket and streaming services, balance on connection count, and plan for reconnection storms after a deploy by spreading disconnects over time.

7. Layers of balancing, and keeping the balancer up

  1. Global
    • DNS with health checks or anycast
    • Nearest healthy region
  2. Regional
    • Layer 4 balancers (redundant)
    • Layer 7 proxies / API gateway
  3. Service to service
    • Client-side balancing or sidecars
    • Service registry
Balancing at three levels. A user's DNS lookup or an anycast address sends them to the nearest healthy region. In that region, a redundant pair or fleet of layer 4 balancers forwards connections to layer 7 proxies, which route requests by path to service pools. Inside the system, services call each other through client-side balancing or sidecar proxies that read a service registry.
  • The balancer is not a single point of failure if you say how. Common answers: an active-passive pair sharing a virtual IP that moves on failure, a horizontally scaled fleet behind DNS or anycast, or a managed cloud balancer that handles this for you.
  • DNS balancing is coarse. Clients and resolvers cache answers, so failover takes as long as the TTL and some clients ignore it.
  • Client-side balancing removes a hop: each caller gets the list of healthy instances from a registry and picks one itself. It is common for internal gRPC traffic and in service meshes.

8. How it shows up in common prompts

Balancing decisions in well-known prompts
PromptBalancing questionReasonable answer
URL shortenerSpread redirect trafficLayer 7 round robin over stateless servers; caches do the heavy lifting
WhatsAppLong-lived connectionsLeast connections at connect time, a registry mapping user to gateway server
Rate limiterWhere limits liveAt the gateway, with counters in a shared store so every balancer instance agrees
Netflix-style streamingGlobal usersRoute to the nearest region or CDN edge; balance origin requests behind it
MicroservicesService-to-service callsClient-side balancing or a mesh, with timeouts and retry budgets
Balancing decisions in well-known prompts. Scroll sideways on a small screen.

9. Mistakes to avoid

  • Drawing one balancer box and moving on. Say what kind, what algorithm and how it stays up.
  • Deep health checks. Checking every dependency can take the whole fleet out over one shared hiccup.
  • Retrying everything. Non-idempotent requests can run twice; unbudgeted retries multiply load during incidents.
  • Relying on sticky sessions for correctness. Servers will die; session data must survive that.
  • Forgetting HTTP/2 and gRPC. Connection-level balancing pins many requests to one server.

10. How to talk about it in the interview

  • Name the layers: global routing, regional balancer, internal balancing.
  • Pick an algorithm and tie it to the request shape: equal and short, or uneven and long.
  • Explain health checks, draining and what a deploy looks like.
  • Say how the balancer itself survives a failure.

Fictional example

Balancing a video upload service
Interviewer
Uploads take anywhere from a second to ten minutes. How do you balance them?
Candidate
Round robin would pile long uploads onto unlucky servers, so I'd use least connections at layer 7, or power of two choices if we run many balancer instances that can't share exact counts.
Interviewer
How do you deploy without breaking uploads in progress?
Candidate
Drain the server: stop new uploads, let current ones finish up to a timeout, and make uploads resumable in chunks so anything cut off continues on another server from the last chunk.
Interviewer
And if the balancer dies?
Candidate
It's a fleet behind DNS, or a managed balancer across zones, so losing one instance only drops the connections it held, and resumable uploads cover those.

Practicing with Natively

Load balancing questions reward specifics, and specifics are what slip away under time pressure. When you run a mock round with Natively open, it transcribes the conversation and can suggest points to cover as each question arrives, so you can compare later whether you named an algorithm, a health check strategy and a failover plan. A screenshot of an architecture sketch or a prompt can be captured and explained. Reviewing the saved transcript afterwards shows exactly where your answer went vague.

Questions people ask

What is the difference between layer 4 and layer 7 load balancing?

A layer 4 balancer forwards connections based on IP address and port without reading the content, so it is fast and works for any TCP or UDP traffic. A layer 7 balancer parses each HTTP request and can route by path, host, header or cookie, retry requests and split traffic for canaries.

Which load balancing algorithm should I use?

Round robin works when servers are equal and requests cost about the same. For uneven or long requests use least connections, or power of two choices when many balancer instances lack a shared view. Use hashing when the same user or key should reach the same server.

How do you avoid the load balancer being a single point of failure?

Run more than one: an active-passive pair sharing a virtual IP, a fleet of balancers behind DNS or anycast, or a managed cloud balancer spread across zones. Then say how traffic shifts when one instance fails.

Are sticky sessions a good idea?

Usually only as an optimization. They tie users to servers, which complicates deploys and scaling and logs users out when a server dies. Prefer stateless servers with session data in a shared store or a signed token.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP