TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท scaling ยท networking

Load balancing

Spreading requests across several identical servers, skipping unhealthy ones, and finding new ones automatically through service discovery, all behind one address.

9 min4 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

The host at the gate

A theme park has several identical rides. Families all arrive at one gate, and a host sends each to a ride. The simplest way is in turn: A, B, C, A, B, C. A smarter host looks at the queues and picks the shortest.

Spreading requests

Running several copies of a service gives more capacity and survives a crash. A load balancer sits in front, on one address, and forwards each request to one of the servers using an algorithm:

AlgorithmPicks
Round robinThe next server in turn (optionally weighted)
Least connectionsThe server with the fewest requests in flight
Hash (IP, user id)The same server for the same key, for sticky sessions or caches

Layer 4 balancers forward TCP connections; layer 7 balancers understand HTTP and can route by path, header or cookie. Examples: NGINX, HAProxy, Envoy, AWS ALB.

Spreading the crowd3 steps
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งFamily 1๐Ÿ‘ฉโ€๐Ÿ‘ฆFamily 2๐Ÿ‘จโ€๐Ÿ‘งFamily 3๐Ÿง‘โ€๐Ÿ’ผPark host๐ŸŽ Ride A๐ŸŽกRide B๐ŸŽขRide C
Press play and watch it happen!

Skipping a broken ride

Every few seconds the host radios each ride, "all OK?". A ride that stops answering is skipped until it's fixed, so no family ends up queuing at a broken ride.

Health checks

The load balancer actively probes each server (GET /health) and passively watches for errors and timeouts. After a few failures the server leaves the pool; after a few successes it returns. Good health endpoints check what this instance needs to work (its threads, its own connection pool) but stay cheap, and avoid failing on a shared dependency (see What can go wrong below).

Pair this with graceful shutdown: on deploy, a server stops taking new requests, finishes what it has, then exits.

Skipping a broken ride4 steps
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งFamily๐Ÿง‘โ€๐Ÿ’ผPark host๐ŸŽ Ride A๐ŸŽกRide B๐ŸŽขRide C
Press play and watch it happen!

A board of open rides

On a busy day new rides open, and quiet ones close. Instead of the host memorising them, every ride writes itself on a board when it opens, and the host reads the board.

Service discovery

With autoscaling and containers, server addresses change constantly. In service discovery, instances register with a registry (Consul, Eureka, etcd, or Kubernetes, where a Service tracks matching pods), and load balancers or clients read the current list from it.

Discovery can be server-side (a load balancer or proxy looks it up) or client-side (the caller gets the list and balances itself, as with Spring Cloud LoadBalancer).

New rides open3 steps
๐Ÿง‘โ€๐Ÿ’ผPark host๐Ÿ“‹ Ride board๐ŸŽ Ride A๐ŸŽกRide B
Press play and watch it happen!

When the host gets it wrong

Ride B still answers the host's radio with a cheerful "yes". But the ride itself jerks and stops halfway, and families climb off upset. Worse, the host sees that ride B's queue is always short, because nobody stays on it, so the host sends even more families there. The host only fixes this after watching several families come back unhappy and deciding to pull the rope across ride B.

Or the host notices that every ride is struggling because the same power cable is overloaded. If the host radios "is the cable OK?" and hears "no", the host closes every ride at once, and the whole park is empty. So a wise host who hears every ride say "no" keeps the rides open anyway: a shaky ride beats an empty park.

Some families are told to always return to the same ride, because their saved seat is there. When that ride closes, the seat is gone and they start over, so the park keeps saved seats at the gate, where any ride can find them. When a ride turns families away, they all rush back to the gate at the same moment, which makes the crowd worse, so the host asks families to wait a little, each a different time. And there is only one host: if the host faints, nobody gets in, so big parks keep a second host standing by.

What can go wrong

  • A sick server passes the health check. A shallow check (GET /health returns 200 if the process is up) says nothing about a server whose database connection pool is exhausted or whose threads are stuck. It keeps receiving its share and fails real requests: you see a rising 5xx rate or latency on one instance, while the balancer shows it healthy. Worse, under least-connections a server that answers instantly with errors has few requests in flight, so it attracts more traffic (a "black hole"). Under round robin a slow server still gets an equal share, and its queue grows. Fix: passive health checks / outlier detection that eject a server after consecutive errors or timeouts (Envoy outlier detection ejects on consecutive 5xx, 5 by default; NGINX max_fails and fail_timeout), plus a deeper check where it is safe.
  • Health checks take every server out at once. If /health checks a shared dependency (the database), a database blip fails the check on every server together, the pool empties, and a partial degradation becomes a total outage that lingers until checks pass again. Symptom: the healthy-host count drops to zero while the app processes are fine. Fix: keep the balancer's check about this instance, put dependency checks in separate readiness logic with care, use thresholds, and rely on a panic or fail-open mode that sends traffic anyway when too few hosts are healthy (Envoy's panic threshold defaults to 50% of hosts; AWS ALB routes to all targets if none are healthy).
  • Sticky sessions are lost when a node dies. With cookie or hash affinity, session data lives in one server's memory. When it crashes or is drained, its users are sent elsewhere and get logged out or lose their cart, and a hot key can overload one node. Fix: keep sessions in a shared store (Redis, a database, a signed token such as a JWT), so any server can serve any request, and treat stickiness as an optimisation only.
  • Retries make an outage bigger. A failed request is retried by the client, again by the balancer, and again by the service behind it, so one failure can multiply the load several times over on servers that are already struggling (a retry storm). Symptom: request rate jumps while the success rate falls. Fix: retry only idempotent requests, cap attempts, use exponential backoff with jitter, set a retry budget, and add a circuit breaker that stops calling a failing dependency.
  • The balancer itself is a single point of failure. One instance dies and every client loses the address. Fix: run several balancers behind DNS or a virtual IP with failover (keepalived/VRRP), or use a managed one such as Elastic Load Balancing, which runs across availability zones for you.
ChoiceYou gainYou pay
Shallow health checkCheap, stable, never fails because of a shared dependencyMisses servers that are up but broken
Deep health checkCatches broken dependencies and stuck workersSlower, loads the dependency, and can empty the whole pool at once
Sticky sessionsLocal caches and in-memory sessions workLost state when a node dies, uneven load
Stateless serversAny server can take any request, easy scaling and drainingA shared session store or token to run

In Spring Boot, Actuator exposes separate liveness and readiness probes (/actuator/health/liveness and /actuator/health/readiness) (on by default since Spring Boot 4; in 3.x, on Kubernetes or with management.endpoint.health.probes.enabled=true): point the balancer at readiness, and keep it limited to what this instance needs.

A broken ride that still says yes5 steps
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งFamily๐Ÿง‘โ€๐Ÿ’ผPark host๐ŸŽ Ride A๐ŸŽกRide B๐ŸŽขRide C
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸŽฏMission: one server, one failure awayPut a load balancer and a second instance in front of a single server, until it reaches 99.9% availability.10-minute mission
  • ๐Ÿ’ฅFlash sale (naive)A shop that works on a normal day and falls over when the sale opens.guided design
  • ๐Ÿ›ก๏ธFlash sale (resilient)The same shop with a queue, caching and pre-warming, so the spike is survived.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Load balancing, told the same way as the story.
  1. What does the simplest host do at the gate?
  2. A ride stops answering the host's "all OK?" radio. What happens?
  3. On busy days rides open and close. How does the host keep track?
  4. Ride B answers the host's radio with "yes" but jerks and stops, and families come back upset. What should the host do?
Answer every question to check.Passing marks Load balancing as done.
Got the hang of Load balancing? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŽฏ Backend interview prepStep 5 of 9

โ† Previous on the path๐Ÿฌ Rate limitingNext on the path โ†’โšก Circuit breakers and retries

๐Ÿš€ Shipping to productionStep 7 of 10

โ† Previous on the path๐Ÿข Service meshNext on the path โ†’โšก Circuit breakers and retries

๐Ÿ‘‰ Read next

  • โšกCircuit breakers and retriesA fuse box: when an appliance keeps failing, the fuse trips so the fault can't spread through the house.
  • ๐ŸššAmazon EC2 and Auto ScalingHiring food trucks for a festival, with a manager who keeps the right number serving and replaces any that break.
  • ๐Ÿ›ฌElastic Load Balancing: ALB and NLBAn airport arrivals hall: a guide reads tickets and walks people to gates, or a turnstile waves them through.