Load balancing means spreading incoming requests across several servers behind one address, so that no single server becomes the bottleneck or the single point of failure. A load balancer receives every request, picks a healthy server using a rule, forwards the request and returns the reply. Clients never learn that more than one server exists.
We follow BusTrack, a city bus tracking app in Hyderabad. At the evening peak about 435 requests per second arrive, and one server cannot keep up. We measure what a single server does, add a balancer and watch the numbers change, then work through layers 4 and 7, health checks, safe deployments, sessions, balancer failure and how many servers to run. Six runnable programs in Java, with Python and C++ versions, give real numbers for each step.
Key takeaways
One server at 99% busy gave a median wait of 2,425 ms and left 18,711 of 20,000 requests over 500 ms. Two servers dropped the busy figure to 55% and the 99th percentile to 13.9 ms. Capacity matters, but so does the way requests are shared.
A layer 4 balancer chooses from IP addresses and ports; a layer 7 balancer reads the URL. In our test layer 4 spread route searches over 3 servers, layer 7 sent them all to the one large server.
Without health checks, 53 of 400 requests failed while a server was broken. Passive plus active checks cut it to 3.
Draining a server for 30 seconds before a restart dropped 0 requests; killing it at once dropped 49.
Keep sessions in a shared store: 0 extra logins, against 2,231 with no stickiness and 393 users logged out by a crash with sticky cookies.
BusTrack needs 7 servers: 6 carry the peak at 85% busy and one is spare. The balancer needs a pair too.
1. What Is Load Balancing?
A server has a fixed amount of CPU, memory and network. Once requests arrive faster than it can finish them, a queue builds, every user waits and eventually requests time out. Buying a bigger machine only delays that day. Adding more machines helps only if something divides the traffic among them, and that something is the load balancer.
A balancer gives you three things at once: more capacity, because the work is divided; availability, because a failed server is skipped; and freedom to change, because you can add, remove or upgrade servers without telling clients. These are the same ideas you saw in Scalability and Availability, now with a concrete component to deliver them.
The balancer sits after DNS, which you met in Domain Name System, and it is closely related to the reverse proxy from Proxy vs Reverse Proxy. A load balancer is a reverse proxy whose main job is choosing between several backends.
2. The Problem: One Server
At 7 PM, commuters open BusTrack to see when their bus arrives. Requests come in three kinds: a ping that checks the app is alive (1 ms of server work), an ETA lookup (3 ms) and a route search (9 ms). The mix is 55%, 35% and 10%, so a request costs 2.5 ms of work on average. At 435 requests per second that is 1.09 seconds of work arriving every second, more than one server can do.
One server at the evening peak: the queue grows and most requests time out.
The first program replays 20,000 requests against 1, 2, 3 and 4 identical servers. Requests are handed out in turn, and each server works through its queue one request at a time. Look at the busy column first, then the 99th percentile.
Output
BusTrack evening peak: 20000 requests, about 435 per second
Mix: 55% ping (1 ms), 35% eta (3 ms), 10% route (9 ms), mean 2.5 ms
servers busy% p50ms p95ms p99ms maxms over500ms
1 99 2425.6 4479.6 4622.2 4640.7 18711
2 55 3.0 9.0 13.9 21.4 0
3 36 2.3 9.0 9.7 17.4 0
4 27 1.0 9.0 9.0 13.9 0
With one server, 18,711 of 20,000 requests took more than 500 ms, and the median was 2,425.6 ms. Queues do not grow slowly near full load; they explode.
With two servers, busy time was 55% and the 99th percentile fell to 13.9 ms, about 330 times better, from only twice the hardware.
Going from three to four servers improved p99 by just 0.7 ms. After a point extra servers buy resilience, not speed, which is the subject of the last section.
3. How a Load Balancer Works
Clients know one address, the balancer's. Behind it sits a pool (also called a server group or target group) of identical servers. For every request the balancer applies an algorithm to choose a member, forwards the request and passes the answer back.
Clients talk to one address; the balancer fans requests out to the pool.
Here are the five steps for a single request:
From a name lookup to the reply, with the balancer adding the real client address.
DNS returns the balancer's address, not a server's. The servers keep private addresses that clients never see.
The balancer terminates the client connection and opens its own towards the chosen server, so your server sees the balancer as the caller. To keep the real client address, the balancer adds an
X-Forwarded-Forheader (or uses the PROXY protocol at layer 4). Use it for logging and rate limits, and trust it only from your own balancer.The algorithm may be as simple as turn-taking or as clever as "fewest open requests". The next lesson, Load Balancing Algorithms, compares them with measurements.
Balancers appear at more than one place in a system. A public one faces the internet, an internal one sits between your services, and a third may spread reads across database replicas.
The same idea repeats at every tier: edge, internal services, databases.
4. Layer 4 vs Layer 7
From OSI Model you know the layers. A balancer works at one of two of them. A layer 4 balancer sees only IP addresses and ports, so it can decide quickly and carry any TCP or UDP protocol. A layer 7 balancer reads the HTTP request, so it can decide by host name, path, header or cookie.
Layer 4 sees addresses and ports; layer 7 also sees the request itself.
The second program sends twelve requests through both kinds. The layer 4 balancer hashes the client address and port (FNV-1a) to choose among three identical servers. The layer 7 balancer has separate pools, matches the path, and answers /health itself.
Layer 7 routing: each URL goes to the pool built for it.
Output
# client:port path L4 picks L7 picks
1 49.37.12.8:51022 /api/ping hyd-api-3 ping-1
2 49.37.12.8:51023 /api/eta hyd-api-1 eta-1
3 106.51.7.90:40112 /api/route hyd-api-2 route-big
4 106.51.7.90:40111 /api/ping hyd-api-3 ping-2
5 152.58.3.14:60211 /api/eta hyd-api-1 eta-1
6 152.58.3.14:60215 /api/route hyd-api-3 route-big
7 223.185.4.2:33018 /api/ping hyd-api-1 ping-1
8 223.185.4.2:33019 /api/eta hyd-api-2 eta-1
9 49.205.9.30:45001 /health hyd-api-1 LB answers 200
10 49.205.9.30:45002 /api/route hyd-api-1 route-big
11 117.97.8.6:52300 /app/home hyd-api-3 web-1
12 117.97.8.6:52301 /api/eta hyd-api-2 eta-2
Route searches: L4 spread them over 3 servers, L7 sent them all to [route-big]
Layer 4 is blind to the URL. The route searches (the heaviest requests) landed on all three servers, so every server must be big enough for them.
Layer 7 sent all three route searches to
route-big, the only large server, and pings to two small ones. You size each pool for its own work.The cost is CPU: a layer 7 balancer parses every request. Choose it when you need path routing, header rules, redirects or cookies. Choose layer 4 for raw speed, millions of long-lived connections or non-HTTP protocols.
A simple rule of thumb for picking the balancer layer.
5. Health Checks
A balancer that keeps sending requests to a dead server makes things worse than having no balancer. It needs to know who is healthy, and there are two ways to find out. Active checks probe each server on a timer, for example GET /health every 2 seconds. Passive checks watch real traffic and count errors and timeouts.
To avoid flapping, use thresholds: eject a server after 3 failures in a row, and bring it back only after 2 successful probes.
A server leaves after 3 failures and returns after 2 passes.
The third program breaks hyd-api-2 from 11 s to 27 s while 10 requests per second arrive, and tries four policies.
Output
Server hyd-api-2 is broken from 11.0 s to 27.0 s. 400 requests, 10 per second.
policy failed ejected at back in rotation
none 53 never never
passive 4 11.8 s 32.2 s
active 16 16.0 s 30.0 s
both 3 11.8 s 30.0 s
With no checks, a third of the pool was dead for 16 seconds and 53 requests failed.
Passive checking reacted fastest, at 11.8 s, because real requests are the probe, but it only fails requests to learn. It also returned the server late, at 32.2 s, since it must wait to try again.
Active checking needed 16.0 s to eject (probes are spaced 2 s apart, so it needs three misses) and failed 16 requests in that time, but brought the server back at 30.0 s without risking real users.
Both together failed only 3 requests: passive ejects quickly, active restores safely. A good health endpoint checks what the server needs to serve (its database, its disk) and stays cheap, because it runs every few seconds.
6. Deploying Without Dropping Requests
Servers must be restarted for every release. If the balancer keeps sending requests while the process stops, users see errors. Connection draining (also called deregistration delay) fixes that: the balancer stops sending new requests to the server, waits for the in-flight ones to finish, and only then do you restart.
A rolling deploy: drain, restart, check health, then move on.
The fourth program does a rolling deploy of three servers under 40 requests per second. Most requests are short, but 5% take 8 to 12 seconds, such as a report export or a large upload.
Output
Rolling deploy of 3 servers, 2400 requests (40 per second)
Request length: 80% 0.2-0.6 s, 15% 1.5-3 s, 5% 8-12 s
policy dropped longest wait before restart
kill at once 49 0.0 s
drain 5 s 8 5.0 s
drain 30 s 0 9.1 s
Killing at once dropped 49 requests, all of those in flight at the moment of the restart.
A 5-second drain dropped 8: the short requests finished but the 8-12 s ones did not.
A 30-second drain dropped none. The price was a longer wait, 9.1 s in the longest case, so the whole deploy is slower. The drain time should be a little longer than your longest normal request.
7. Sessions and Sticky Routing
A user logs in once and expects every later request to know it. If the login is saved in the memory of hyd-api-1 and the balancer sends the next request to hyd-api-2, the user is asked to log in again. There are three answers.
Where you keep the session decides what a crash costs you.
The fifth program simulates 1,200 users making 10 requests each, with server 2 crashing before round 6.
Output
1200 users, 10 requests each. Server 2 crashes before round 6.
policy requests logins extra logins logged out by crash
no stickiness 12000 3431 2231 9
sticky cookie 12000 1593 393 393
shared store 12000 1200 0 0
No stickiness: 3,431 logins for 1,200 users, so 2,231 extra logins. Every user bounces between servers.
Sticky cookie (also called session affinity): the balancer sets a cookie and keeps a user on one server. Extra logins fell to 393, but they are exactly the 393 users whose server crashed.
Shared store such as Redis: 1,200 logins, none repeated, none lost. Any server can serve any user, the balancer's job stays simple and servers become disposable. This is the answer to prefer, and it is the same shape as the cache from Consistent Hashing.
Sticky routing is still useful for things like WebSocket connections or a warm local cache, but never make it the only place a session lives.
8. Termination of HTTPS
Encryption can be handled in three ways. The balancer can terminate TLS: clients speak HTTPS to it, it decrypts, reads the request and talks plain HTTP inside the private network. It can pass through the encrypted bytes at layer 4, in which case servers keep the certificates but the balancer cannot read URLs. Or it can re-encrypt, terminating on the way in and opening a new HTTPS connection to the servers.
Three ways to handle HTTPS; the choice decides what the balancer can see.
Terminating keeps certificates in one place and lets layer 7 rules work. It is the usual choice.
Re-encrypt when the internal network is shared with others or compliance demands encryption everywhere.
Pass through when servers must see the client certificate, or when you want no keys on the balancer at all.
9. The Balancer Must Not Be a Single Point
If every request goes through one balancer, that machine is now the thing that can take the whole product down. We covered the idea in Single Point of Failure. The usual fix is a pair: an active and a standby balancer share a virtual IP, they exchange heartbeats (VRRP or keepalived are the common tools), and the standby takes over the address when the heartbeat stops. Cloud balancers do this for you, across several zones.
An active-standby pair behind one virtual IP.
10. How Many Servers?
The last program answers the question every team asks. BusTrack's peak is 4,200 requests per second and one server handles 900. It prints three tables.
Output
1) How many servers? Peak 4200 req/s, one server handles 900 req/s
servers busy% busy% after one fails verdict
5 93 116 overloaded when one fails
6 77 93 overloaded when one fails
7 66 77 safe
8 58 66 safe
9 51 58 safe
Smallest safe pool: 7 servers (6 carry the peak at 85% busy, plus 1 spare)
2) The load balancer itself (each LB is up 99.9% of the time)
single LB 99.9000000% 43.200 min
pair, perfect failover 99.9999000% 0.043 min
pair, failover works 99% 99.9989010% 0.474 min
3) The pool: each server is up 99.5%, we need at least 6 up
6 servers (no spare) 97.0372508% 1279.907 min
7 servers (1 spare) 99.9483679% 22.305 min
8 servers (2 spare) 99.9993117% 0.297 min
9 servers (3 spare) 99.9999901% 0.004 min
Capacity: 5 servers would be 93% busy and break when one fails (116%). 6 servers cover the peak at 77%, but after one failure the other 5 carry the load at 93%, which is too hot. 7 servers stay at 77% after a failure, so 7 is the smallest safe pool. This is N+1 with a margin, and you should also keep busy time below roughly 80% so spikes do not tip the queues over.
The balancer: a single balancer at 99.9% allows 43.2 minutes of downtime a month. A pair with a perfect failover gives 99.9999%, but real failovers sometimes fail. With a failover that works 99% of the time the pair is still 99.9989%, with 0.474 minutes down.
The pool: if each server is up 99.5% of the time and we need 6 working, six servers give only 97.04%, which is about 21 hours of trouble a month. One spare gives 99.9484%, two spares 99.9993%. Each extra server gives a rapidly smaller gain, so stop when the next one no longer pays for itself.
11. Common Mistakes
Running a single balancer and calling the system highly available.
Having no health check, or a health check that only returns 200 without testing the database.
Restarting servers with no connection draining, so every release drops requests.
Keeping sessions in the memory of one server and relying on sticky cookies.
Sizing the pool for the peak but not for the peak with one server missing.
Trusting
X-Forwarded-Forfrom anyone, which lets clients fake their address.Using layer 7 everywhere when a plain layer 4 balancer would do, or the other way round.
12. Best Practices
Use a managed balancer when you can, and run it across at least two zones.
Combine passive and active health checks, with eject and return thresholds.
Set the drain time slightly above your longest normal request.
Keep servers stateless: sessions and uploads belong in shared stores.
Plan for N+1 or N+2, and test it by turning a server off in a quiet hour.
Watch the balancer's own numbers: request rate, error rate, latency per backend, healthy host count.
Terminate TLS at the balancer and keep certificate renewal automated.
13. Practice Problems
In the first program, raise the arrival rate by 20%. How many servers keep p99 below 15 ms? Hint: work out the busy percentage before running it.
In the second program, add a path
/api/alertswith its own pool of two servers. Which of the twelve requests change?In the third program, change the eject threshold from 3 to 2 failures. What does it do to failed requests and to flapping?
In the sixth program, change the server availability to 99.9% and find the smallest pool that gives 99.99% or better.
14. Interview Questions
What does a load balancer do besides spreading traffic? It hides failed servers through health checks, lets you deploy without downtime through draining, can terminate TLS and can route by URL at layer 7.
Layer 4 vs layer 7? Layer 4 sees addresses and ports and is faster and protocol-agnostic. Layer 7 reads the HTTP request and can route by path, header or cookie at higher CPU cost.
How do you keep users logged in across servers? Keep the session in a shared store such as Redis; sticky cookies are an optimisation, not a substitute.
How would you remove the balancer as a single point of failure? Run a pair on a virtual IP, or use a managed multi-zone balancer, and test the failover.
How do you do a zero-downtime deploy? Rolling restart with connection draining, health checks gating the return to rotation.
How many servers do you need for 4,200 requests per second if one handles 900? Five carry the peak but not a failure; seven is the smallest pool that still stays under 80% busy with one server down.
Summary
A load balancer gives clients one address, spreads requests over a pool and skips unhealthy servers.
Layer 4 is fast and protocol-blind; layer 7 can route by URL, header and cookie.
Use passive and active health checks together, and drain connections before every restart.
Keep sessions in a shared store; use sticky routing only as an optimisation.
The balancer needs redundancy too, and the pool must survive one failure at peak.
Conclusion
A balancer is simple to describe, but every number above came from a decision: where requests are routed, how fast a dead server is noticed, how long a restart waits and where a session lives. Continue with Load Balancing Algorithms to see how the choice of rule changes latency when servers are uneven or slow.
Previous topic: Proxy vs Reverse Proxy. Next: Load Balancing Algorithms.