How systems work

Load balancers.

A load balancer sits in front of a group of servers and gives them one address. Clients connect to it, and it passes each request on to one of the servers behind it. Add servers and the site gets faster without anyone changing a URL. Lose one and, if all goes well, nobody notices.

That small job hides real choices: which server gets the next request, how to tell a server is dead, what to do with users who were logged in to it, and how to restart servers without dropping anyone. This page shows each one happening.

In the labs after the walkthrough, every coloured chip is one request in a simulation running in your browser. The letter is the client that sent it and the number counts that client’s requests, so A12 is client A’s twelfth request. Follow one from its client, through the load balancer, into a server’s queue and out again, or click it to see its story. A red chip with a cross has failed.

00 The life of one request

Before the live labs, follow a single request from the client to a server and back, then watch what happens when a server dies. Step through at your own pace, or press Play all.

Client ABrowserClient BPhone appLoad balancer203.0.113.10 · the one public addressRule: least connectionsServerHealthOpenServer 1✓ healthy3Server 2✓ healthy1Server 3✓ healthy2Health check: GET /healthz every 1sServer 1App serverServer 2App serverServer 3App serversend requestsone address · picks a serverservers do the work

Step 1 of 10

Meet the pieces

Clients send requests. The load balancer has the one public address they all use, and it decides which server gets each request. The servers behind it do the actual work. Clients never see the servers directly.

01 One front door, many servers

One server can only do so much. Each server here works on two requests at a time, at about 0.6 seconds each, so it handles a little over three a second. Beyond that, requests wait in its queue.

Put three servers behind a load balancer and the clients still see one address. They do not know or care how many servers there are, which means you can add, remove and replace servers freely.

ClientsQueue at serverServersClient Asends 1.3/sClient Bsends 1.3/sClient Csends 1.3/sClient Dsends 1.3/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
Served
0
Longest queue
0
Oldest waiting
0.0s

Click any chip to follow that one request.

Four clients send five requests a second to one address. The load balancer spreads them over three servers.
    Try this. Drop to one server. Its queue grows and the oldest waiting request gets older every second. Add servers back and watch the queue drain. Then push requests per second up to 12 and see how many servers you need.

    A load balancer turns “make the server faster” into “add another server”. That only works if any server can handle any request, which sections 06 and 08 come back to.

    02 Round robin and the slow server

    Round robin is the simplest rule: server 1, then 2, then 3, then 1 again. It is fair in turns, and it is the default in many load balancers.

    Fair turns are not fair work. When one server is slower, because of a noisy neighbour, a bad disk or a long garbage collection pause, round robin keeps giving it a third of the traffic. Its queue grows and every third request waits behind it.

    Least connections sends each request to the server with the fewest requests open. The load balancer already knows that number, because the requests pass through it. A slow server holds its requests longer, so its count stays high and it gets fewer new ones.

    ClientsQueue at serverServersClient Asends 1.5/sClient Bsends 1.5/sClient Csends 1.5/sClient Dsends 1.5/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 34× slowerIn rotation · 0 served
    Longest queue
    0
    Oldest waiting
    0.0s
    Served
    0

    Click any chip to follow that one request.

    Server 3 takes four times as long per request. Round robin gives it a third of the traffic anyway.
    Algorithm
      Try this. Watch server 3’s queue grow under round robin while the others sit half idle. Switch to least connections: the queue drains, and server 3 gets only what it can handle. Compare the served counts on each server.

      Round robin is fine when servers and requests are alike. When they are not, pick an algorithm that looks at load.

      03 Weighted: bigger servers get more

      Sometimes servers differ on purpose: a new machine with three times the cores next to two old ones. Weighted round robin gives each server a weight and hands out turns in that ratio. With weights 3, 1 and 1, server 1 gets three requests in every five, spread out rather than in a clump.

      Weights are also how you send a little traffic to a new version (a canary): give it weight 1 next to servers with weight 19, and it sees about 5% of requests.

      ClientsQueue at serverServersClient Asends 2.0/sClient Bsends 2.0/sClient Csends 2.0/sClient Dsends 2.0/sLoad balancerPicks a serverWeightedQueue · emptyQueue · emptyQueue · emptyServer 1weight 3In rotation · 0 servedServer 2weight 1In rotation · 0 servedServer 3weight 1In rotation · 0 served
      Average time
      0.0s
      Longest queue
      0
      Served
      0

      Click any chip to follow that one request.

      Server 1 is three times faster and has weight 3. Watch the served counts settle at about 3 : 1 : 1.
      Algorithm
        Try this. Switch to round robin (the tags now show each server’s speed). The fast server now idles while the two slow ones queue up, and the average time per request rises. Switch back to weighted.

        Weights are something you set and must keep true. Least connections finds the same balance on its own, which is why many teams use it instead.

        04 Random, and the power of two choices

        Picking a server at random sounds lazy, and on average it is fair. But averages hide streaks. Every so often, chance sends several requests in a row to the same server, and with the servers this busy, its queue takes a while to recover.

        The power of two choices fixes that cheaply: pick two servers at random and send the request to the one with fewer open requests. That small comparison removes nearly all the streaks. It matters most when there are many load balancers, each with its own slightly stale view of the servers: they would all rush to the same “least loaded” server, while random pairs spread them out. Envoy and NGINX both offer it.

        ClientsQueue at serverServersClient Asends 3.3/sClient Bsends 3.3/sClient Csends 3.3/sClient Dsends 3.3/sLoad balancerPicks a serverRandomQueue · emptyQueue · emptyQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 servedServer 4In rotation · 0 servedServer 5In rotation · 0 served
        Longest queue
        0
        Oldest waiting
        0.0s
        Average time
        0.0s

        Click any chip to follow that one request.

        Five servers at about 80% busy. Random choice lets queues build up on unlucky servers.
        Algorithm
          Try this. Watch the longest queue under random: it often sits at three or more and now and then reaches six. Switch to two choices and it stays at two or below. Least connections does about as well here, because there is only one balancer.

          Two random choices and a comparison give nearly the result of checking every server, at a fraction of the cost.

          05 Health checks: noticing a dead server

          The load balancer cannot see inside a server. To know it is alive, it asks: every few seconds it sends a health check, such as GET /healthz, and expects a quick 200. One failed check could be a blip, so a server is only removed after several failures in a row, and only added back after several passes.

          That means a dead server keeps getting traffic for a while. The gap is roughly the check interval times the failure threshold, and every request sent in that gap fails.

          ClientsQueue at serverServersClient Asends 1.5/sClient Bsends 1.5/sClient Csends 1.5/sClient Dsends 1.5/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
          Failed
          0
          Time to detect
          –
          Served
          0

          Click any chip to follow that one request.

          Checks every second; three failures in a row take a server out. The lines flash green or red on each check.
            Try this. Kill a server and watch requests turn red on it while its checks fail one by one. After the third, its line goes dashed and traffic moves to the others. It restarts after eight seconds and comes back after two passing checks. Now set checks to every 250 ms with 2 failures and kill again: far fewer red chips.

            Fast checks catch failures sooner but cost traffic and can flap on one slow reply. Many load balancers also watch real traffic (passive checks or outlier detection) and eject a server that starts returning errors.

            06 Sticky sessions or stateless servers

            Suppose each server keeps logged-in users in its own memory. Then a user who logs in on server 1 and whose next request lands on server 2 is a stranger there: logged out. One fix is sticky sessions: the load balancer remembers which server each client used (usually with a cookie) and keeps sending it there.

            Stickiness hides the problem rather than solving it. When that server dies, every session on it dies too. It also makes load uneven, because a busy client cannot be spread out. The lasting fix is stateless servers: keep sessions in a shared store such as Redis or a database, or in a signed cookie, so any server can serve any request.

            ClientsQueue at serverServersClient Asends 1.3/sClient Bsends 1.3/sClient Csends 1.3/sClient Dsends 1.3/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
            Logged out
            0
            Failed
            0
            Served
            0

            Click any chip to follow that one request.

            Each server keeps sessions in its own memory. Without stickiness, clients bounce between servers.
              Try this. Watch the logged-out count climb with no stickiness. Turn on sticky sessions: each client’s chips now go to one server and the count stops. Kill a server: its clients are logged out once they move. Now turn on the shared store and kill another: nobody is logged out.

              Use stickiness as an optimisation (warm caches), not for correctness. If losing one server logs people out, the state is in the wrong place.

              07 Draining during a deploy

              A rolling deploy restarts servers one at a time, so the others carry the traffic. Restart a server straight away and you cut off the requests it was working on, and the load balancer keeps sending it new ones until health checks notice it is gone.

              Connection draining does it in order: tell the load balancer to stop sending new requests to the server, wait for its open requests to finish (with a time limit), then restart it, then add it back once it passes its checks. AWS calls the wait the deregistration delay; it defaults to 300 seconds.

              ClientsQueue at serverServersClient Asends 0.8/sClient Bsends 0.8/sClient Csends 0.8/sClient Dsends 0.8/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
              Cut off mid-way
              0
              Failed
              0
              Served
              0

              Click any chip to follow that one request.

              Requests take about 1.5 seconds. Deploy v2 restarts each server in turn.
                Try this. Press Deploy v2 with draining off: requests are cut off mid-way and more fail on the restarting server. Reset, turn draining on and deploy again. Each server empties its queue, restarts and returns. Failed stays at zero.

                Set the drain time a little above your slowest normal request. Long-lived connections such as WebSockets need the client to reconnect, so make reconnects routine.

                08 Layer 4 or layer 7

                The names come from the network layers. A layer 4 load balancer works with TCP (or UDP) connections. It sees addresses and ports, picks a server when a connection opens, and then copies bytes both ways. It is fast and works for any protocol, but it cannot see a URL, a header or a cookie, especially once the traffic is encrypted.

                A layer 7 load balancer speaks HTTP. It ends the TLS connection, reads each request and then chooses: by path (/api to one pool, /img to another), by header, by cookie for stickiness. It can retry a failed request, add headers and pick a server per request rather than per connection.

                That last point matters more than it sounds. With keep-alive, HTTP/2, gRPC and WebSockets, one connection can carry thousands of requests. A layer 4 balancer can only balance connections, so a busy client lands all its work on one server.

                ClientsQueue at serverServersClient Asends 3.8/sClient Bsends 0.8/sClient Csends 0.8/sClient Dsends 0.8/sLoad balancerPicks a serverRound robinLayer 4Queue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
                Longest queue
                0
                Oldest waiting
                0.0s
                Served
                0

                Click any chip to follow that one request.

                Layer 4 seesWaiting for a request…Bytes after the handshake are opaque. It picks a server once per connection.
                Client A sends five times as much as the others, all over one long-lived connection.
                Balances at
                  Try this. At layer 4, every A chip goes to the same server and its queue grows. Look at what the balancer sees: two addresses and nothing else. Switch to layer 7: it reads each request, spreads A’s requests over all three servers and the queue drains.

                  A common setup uses both: a layer 4 balancer at the edge for raw speed, in front of layer 7 proxies that do the routing.

                  09 Hot spots

                  Some routing pins work to a server on purpose. Hashing by client, user or key sends the same client to the same server every time, which keeps caches warm and needs no table of who went where. Consistent hashing, a careful version of this, is how caches and databases split data across nodes.

                  The catch is that load is rarely even across clients. One big customer, one celebrity account or one viral item can send more traffic than a single server can take. Hashing cannot split it, and adding servers does not help: the hot key still lands on one of them.

                  ClientsQueue at serverServersClient Asends 5.3/sClient Bsends 0.9/sClient Csends 0.9/sClient Dsends 0.9/sLoad balancerPicks a serverClient hashQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
                  Longest queue
                  0
                  Oldest waiting
                  0.0s
                  Served
                  0

                  Click any chip to follow that one request.

                  Routing by a hash of the client. Client A sends two thirds of all traffic.
                  Algorithm
                    Try this. Add servers, up to five. Client A’s server still drowns while the new ones sit idle. Switch to least connections and the queue drains with three.

                    When one key is hot, spread that key: route it per request, give it its own pool, or split it (add a suffix to the key so it lands on several servers). Watch the busiest server, not the average.

                    10 The load balancer can fail too

                    Everything so far assumed the load balancer itself never fails. It is one box in front of everything, so if it goes down, every request fails no matter how many servers are healthy. Three common ways around that:

                    • An active and standby pair that share one address. They send each other heartbeats, and when the active one goes quiet the standby claims the address (keepalived and VRRP work like this). Failover takes about a second.
                    • DNS with several addresses, one per load balancer. Clients spread across them, and a dead one is removed from DNS. That is slow to take effect, because clients and resolvers cache answers for the record’s TTL, often longer.
                    • Anycast: the same IP address is announced from many places at once, and the internet’s routing sends each client to a nearby one. If a site goes away, routes move to the next. Cloudflare and Google’s front ends work like this.

                    Managed load balancers such as AWS ALB do this for you: the name points to a fleet of nodes across zones that scales and replaces itself.

                    ClientsQueue at serverServersClient Asends 1.3/sClient Bsends 1.3/sClient Csends 1.3/sClient Dsends 1.3/sLoad balancerPicks a serverRound robinQueue · emptyQueue · emptyQueue · emptyServer 1In rotation · 0 servedServer 2In rotation · 0 servedServer 3In rotation · 0 served
                    Failed
                    0
                    Served
                    0

                    Click any chip to follow that one request.

                    One load balancer in front of three healthy servers. It restarts six seconds after it dies.
                      Try this. Kill the load balancer: every request fails for six seconds, though all three servers are fine. Turn on the standby and kill it again. The standby takes over after about a second, and only the requests in that second fail.

                      Any part that every request passes through needs a spare. Check your design for the one box with no second.

                      11 Choosing a load balancer

                      The ideas above show up in every product under different names. A rough map:

                      ProductLayerAlgorithmsHealth checksGood for
                      NGINX7, and 4 with the stream moduleRound robin, weighted, least connections, hash, random with two choicesPassive in the open source version; active in NGINX PlusA web server and reverse proxy you run yourself
                      HAProxy4 and 7Round robin, least connections, source and URI hashing, and moreActive and passive; slow start; drain by maintenance modeA fast, very configurable proxy you run yourself
                      AWS ALB7Round robin, least outstanding requests, weighted randomPer target group; deregistration delay for drainingHTTP services on AWS, path and host routing
                      AWS NLB4Flow hash: one target per connectionPer target groupTCP and UDP at very high volume, static IPs
                      Envoy4 and 7Round robin, least request (two choices by default), ring hash, Maglev, randomActive checks plus outlier detectionService meshes and gRPC, configured by an API
                      Cloudflare Load Balancing7 (proxied) or DNSWeighted pools; steering by location or latencyMonitors from many locationsSpreading traffic across regions or clouds, on an anycast network

                      Check the current docs before you choose: these products add features every year, and names and defaults change.

                      12 Check yourself

                      1. Three servers sit behind round robin. One of them is running a slow disk and takes four times as long per request. What happens?

                      2. Health checks run every 5 seconds and a server is removed after 3 failures in a row. It dies. Roughly how long are requests sent to it?

                      3. Your app keeps login sessions in each server’s memory and uses sticky sessions. One server crashes. What do its users see?

                      4. During a deploy you restart each server straight away. Users see a few errors on every deploy. What is the usual fix?

                      5. Clients keep one long-lived connection open and send many requests over it. A layer 4 balancer is in front. Why is load uneven?

                      Next partCaches