Building at scale · L1Load balancing

Load balancing

A load balancer decides which server gets each request. Learn to pick the rule, check health and remove servers without dropping users.

L1 Must-knowBuilding at scale18 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
Senior at work · lesson 11 of 26
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This story is made up, but it is common. A food delivery app runs six API servers behind one load balancer. The load balancer uses round-robin: each server gets one request in turn.

On a Friday evening, one server starts to read from a failing disk. Its requests take 3 seconds instead of 80 ms. Its health check is a simple /health page, and it still answers "OK" in 2 ms.

The load balancer sees a healthy server. It keeps sending it one request in six. Users who land there wait, give up and tap "Order" again.

The dashboards show normal average latency, because five servers are fine. But p99 latency is over 3 seconds, and support gets angry messages. It takes the team an hour to find the one bad server.

Nothing was down. The load balancer did exactly what it was told. It just did not know that "healthy" and "fast" are not the same thing.

Section 2 of 8

The idea in simple words

A load balancer is one address in front of many servers. Clients talk to the load balancer. For each new connection or request, it picks a server.

It has three jobs:

  1. Pick a server. Follow a rule, such as "next in turn" or "least busy".
  2. Skip bad servers. Use health checks to stop sending traffic to servers that fail.
  3. Change the pool safely. Add and remove servers without breaking requests that are still running.

The key idea. The goal is not to spread requests evenly. The goal is that no server is overloaded and no user waits on a failing server. Equal counts are not equal work.

Section 3 of 8

How it works

L4 or L7

A layer 4 (L4) load balancer sees TCP connections, not HTTP requests. AWS's Network Load Balancer works this way. It picks a server with a hash of the protocol, addresses, ports and TCP sequence number. Each TCP connection stays on one server for its whole life. 5 It is fast and simple, but it cannot read URLs or headers.

A layer 7 (L7) load balancer reads each HTTP request. AWS's Application Load Balancer can send /api to one group of servers and /images to another, by path, host or header. 6 It does more work per request, but it can balance requests, not just connections. This matters with HTTP/2 or gRPC, where one connection carries many requests.

Choosing a server

Round-robin gives each server the next request in turn. It is the default on the AWS Application Load Balancer. 7 It works well when requests cost about the same. In practice they often do not. Google found that the most expensive requests can use 1,000 times more CPU than the cheapest. Round-robin gave a spread of up to 2x in CPU use between the least and most loaded servers. 1

Least connections sends the request to the server with the fewest requests in progress. AWS calls this "least outstanding requests". It suggests it when requests vary in cost or servers vary in power. 7

Step through what happens to one slow server under each rule. Use Next and Back, or the ← and → keys.

One slow server: round-robin keeps feeding it, least connections does notLoad balancer Server A Server B Server C gets 1, 4, 7gets 2, 5, 8gets 3, 6, 9A · round-robin: A, B, C, A, B, C… 80 ms80 ms3 s0 waiting0 waiting6 waiting 1 in 3 users waits seconds B · least connections1 open1 open6 opennext request: A or B, not C most requestsmost requestsonly a few✓ few users wait on C SeniorPath
  1. Path A, round-robin. The load balancer sends requests to A, B and C in turn. Each server gets one request in three, no matter how busy it is.
  2. Server C has a problem, such as a noisy neighbour, and each request now takes 3 seconds, not 80 ms. A and B finish their work fast. Requests pile up on C.
  3. Round-robin does not look at load, so C still gets one request in three. About one user in three now waits seconds for a page.
  4. Path B, least connections. Before each request, the load balancer checks how many requests are still open on each server. C has 6 open, A and B have 1, so the next request goes to A or B.
  5. C gets a new request only when its count drops. A and B take most of the traffic. Few users wait on the slow server while you find out what is wrong with it.
Step 1 of 5

Least connections has one trap. A broken server that returns errors very fast has few open requests. So it looks "least busy" and gets even more traffic. Google calls this a sinkhole. Its fix was to count recent errors as if they were open requests. 1

Power of two choices (P2C) picks two servers at random and sends the request to the less busy one. Mitzenmacher showed that two random choices are far better than one, while a third choice helps only a little. 3 Envoy uses this for its least request balancer. Its docs say it is nearly as good as checking every server. 4 It is cheap, because it looks at only two servers per request.

Consistent hashing sends the same key, such as a user ID, to the same server. A simple hash mod N breaks when N changes: almost every key moves to a new server. With consistent hashing, adding or removing a server moves only a small share of keys. 2 Envoy offers it as "ring hash" and "Maglev". 4 Use it when a server keeps a local cache per key.

Health checks

The load balancer tests each server on a schedule. On an AWS Application Load Balancer, the defaults are a check every 30 seconds, with a 5 second timeout. Two failures in a row mark a server unhealthy. Five passes in a row bring it back. 8

With those defaults, a dead server fails two checks 30 seconds apart. So it can get traffic for about a minute before it is removed. Our advice: shorten the interval for important services.

What should the check test? A shallow check ("the process is up") misses the slow disk in our story. A deep check that calls the database can mark every server unhealthy at once when the database has a short problem. Our advice is a middle path: check the server's own parts, and watch latency and errors with alerts.

Health checks can also hurt you. If every target fails, an Application Load Balancer "fails open" and sends traffic to all of them anyway. 8 In October 2025, health checks for AWS's Network Load Balancer in us-east-1 kept flipping between failing and healthy. Healthy capacity was removed, and customers saw connection errors. Engineers turned off automatic health check failover to stop it. 9

Connection draining

You remove servers all the time: deploys, scale-in, repairs. If you cut a server off at once, its open requests fail.

Connection draining fixes this. The load balancer stops sending new requests to the server, but lets open ones finish. On an AWS Application Load Balancer, this is the "deregistration delay", and the default is 300 seconds. If the server closes connections before the delay ends, clients get 500-level errors. 7 Google's version is a "lame duck" state: the server still serves, but asks clients to stop sending new requests. 1

New servers can need the opposite: a slow start. AWS can raise traffic to a new target step by step, so it can warm up first. 7

Sticky sessions, and why to avoid them

Sticky sessions send all requests from one user to the same server, often with a cookie. On AWS, the load balancer's own cookie is named AWSALB, and it skips the normal algorithm after the first request. 7

This is useful when a server keeps session data in memory. But it has costs. If that server dies, those users lose their session. Load becomes uneven: AWS warns that after a big scale-up, stickiness can spread load unequally. 7 Deploys get slower, because you must drain long sessions.

The better fix is to make servers stateless. Keep sessions in a shared store, such as Redis or a database, so any server can serve any user.

Global load balancing

To spread users across regions, you balance before traffic reaches any one data centre.

DNS. The DNS server returns a different IP address for each region. It is simple, but slow to change. Resolvers cache answers for the TTL, and not all resolvers respect it. The DNS server also sees the resolver's address, not the user's, so it can guess the user's location wrong. 2

Anycast. Many sites announce the same IP address. The network sends each user to the nearest one. Google's book describes giving DNS servers an anycast address, so DNS queries flow to the closest one. 2

Section 4 of 8

Trade-offs

RuleHandles a slow server?CostUse it when
Round-robinNo Every server gets the same share.Almost none.Requests cost about the same and servers are the same size.
Least connectionsYes Busy servers get less.Must track open requests. Watch for fast-failing sinkholes.Request cost varies a lot.
Power of two choicesYes , mostly.Checks only two servers per request.Many load balancers or proxies, each with its own view.
Consistent hashingNo The key decides, not the load.Hot keys can overload one server.Each server caches data per key.
Sticky sessionsNo Users stay on the same server even when it is busy.Lost sessions when a server dies. Uneven load.Old apps that keep state in memory, while you move it out.

Simple rule: start with least connections or P2C for HTTP services. Use hashing only when local data needs it.

Section 5 of 8

At work: how a senior uses this

  • Ask: "What does our health check really test?" A check that passes while users wait is not a health check.
  • Watch p99 latency and errors per server, not just the average. One bad server hides inside a good average.
  • Set the draining time longer than your slowest normal request. Make sure the app stops cleanly on SIGTERM, the signal that asks a process to shut down.
  • Know what happens when every server fails its check. Does the load balancer fail open, or send nothing?
  • Remove sticky sessions when you touch old code. Move session data to a shared store.
  • For long-lived connections, like gRPC or WebSockets, check that load is spread by request, not just by connection.
  • Test it: kill one server during a load test, and slow one down. Watch what the users see.
Section 6 of 8

With AI

What to ask the agent

"Read this load balancer config. List the algorithm, health check path, interval, thresholds and draining time. Point out anything that could keep a slow server in the pool."

"Change our /health endpoint so it fails when the local disk or thread pool is unhealthy, but not when a shared database is slow. Explain each check."

"Write a shutdown handler for this service: on SIGTERM, fail the health check, stop taking new requests, finish open ones within 30 seconds, then exit."

What to check yourself

  • The health check is cheap and fast, and cannot overload the server itself.
  • A shared dependency failure does not mark every server unhealthy at once.
  • The draining delay in the load balancer matches the shutdown timeout in the app.
  • Any change to sticky sessions or hashing was tested with servers added and removed.
  • The agent did not invent config keys. Check them against the docs for your load balancer.
Section 7 of 8

Check yourself

1. One of your six servers becomes very slow, but its health check still passes. Which rule sends it the fewest new requests?

Show answer

Least connections. A slow server keeps many requests open, so least connections sends new requests elsewhere. Round-robin still gives it one in six.

2. What does power of two choices do?

Show answer

Picks two servers at random and sends the request to the less busy one. It checks only two servers, so it is cheap, and it still avoids most busy servers.

3. You remove a server from the load balancer during a deploy. What should happen to requests already running on it?

Show answer

The server stops getting new requests and finishes the open ones first. That is connection draining. On an AWS Application Load Balancer the default wait is up to 300 seconds.

4. Why do seniors try to avoid sticky sessions?

Show answer

If the server dies, its users lose their session, and load can become uneven. Stickiness ties users to one server. Keep session data in a shared store instead, so any server can serve any user.

5. Why can a DNS change take a long time to move all users to a new region?

Show answer

Resolvers cache answers for the TTL, and some ignore the TTL. The authoritative server cannot flush resolver caches, and not all resolvers respect the TTL.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 9 sources and related lessons
  1. Alejandro Forero Cuervo, “Load Balancing in the Datacenter”, Site Reliability Engineering (Google, O'Reilly 2016), chapter 20 (opens in a new tab)
    Why round-robin wastes capacity, least-loaded round-robin and its traps, lame duck state and weighted round-robin.
  2. Piotr Lewandowski, “Load Balancing at the Frontend”, Site Reliability Engineering (Google, O'Reilly 2016), chapter 19 (opens in a new tab)
    DNS load balancing and its limits, anycast, virtual IPs and consistent hashing in network load balancers.
  3. Michael Mitzenmacher, “The Power of Two Choices in Randomized Load Balancing”, IEEE Transactions on Parallel and Distributed Systems, 2001 (opens in a new tab)
    The paper behind power of two choices. Two random choices beat one by far; a third choice adds little.
  4. Envoy proxy documentation, “Supported load balancers” (opens in a new tab)
    Round-robin, least request with two random choices (P2C), ring hash and Maglev, in a real proxy.
  5. AWS documentation, “What is a Network Load Balancer?” (opens in a new tab)
    A layer 4 load balancer that picks a target per TCP connection with a flow hash.
  6. AWS documentation, “What is an Application Load Balancer?” (opens in a new tab)
    A layer 7 load balancer that routes by path, host and headers.
  7. AWS documentation, “Edit target group attributes for your Application Load Balancer” (opens in a new tab)
    Deregistration delay (draining), routing algorithms, slow start and sticky sessions, with defaults.
  8. AWS documentation, “Health checks for Application Load Balancer target groups” (opens in a new tab)
    Every health check setting with its default, and what happens when all targets fail.
  9. AWS, “Summary of the Amazon DynamoDB Service Disruption in the Northern Virginia (US-EAST-1) Region” (official, October 2025) (opens in a new tab)
    The section on Network Load Balancer shows health checks that flapped and took healthy capacity out of service.

Real incident: Amazon Web Services, 20 Oct 2025: AWS DynamoDB outage: an empty DNS record in us-east-1

Related: TCP/IP and the network stack · HTTP/1.1, HTTP/2 and HTTP/3 · DNS and service discovery · API gateways and edge concerns · Sharding and consistent hashing · Multi-region systems and data locality

Related lessons: DNS and service discovery, API gateways, Sharding and consistent hashing and Multi-region. How a cluster decides a node is dead, beyond simple health checks: Failure detection and membership.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper