AlgoViz

Advanced load balancing patterns

medium 30 min

A load balancer decides which server gets a request, so it can also decide which version gets it and what happens when a server misbehaves.

Video lesson · Chapter 1 of 5

A release meets its first fifty real requests per second

0:00 / 3:52

Theory

Read or listen first. About 2 min.

What it is

Spreading requests evenly is only the first use of a load balancer. Because every request passes through it, it can also send a chosen part of the traffic somewhere else. That one ability is behind most of the patterns on this page.

Two groups of patterns follow. Release patterns (canary, blue-green, mirroring) decide which version of the software gets the traffic. Protection patterns (ejecting bad servers, circuit breaking, timeouts, retries) decide what to do when something fails.

Why it exists

Most outages start with a change. If a new version goes to everybody at once, everybody finds the fault. If it goes to one user in twenty, the fault costs a twentieth.

The second cause is failure that spreads. One slow service makes its callers wait, they fill up and become slow too. A balancer that stops sending to the slow part, and refuses to repeat requests without limit, breaks that chain.

A short history

  1. March 2010

    Martin Fowler describes blue-green deployment: two environments and a switch between them.

  2. March 2014

    Fowler describes the circuit breaker, popularised by Michael Nygard's book Release It.

  3. May 2014

    Danilo Sato describes parallel change (expand and contract), which lets two versions share one database.

  4. June 2014

    Danilo Sato describes canary release on the same site.

  5. October 2023

    Gateway API 1.0 for Kubernetes: traffic weights are part of a standard interface.

Words to know

Canary
A small part of the traffic that gets the new version first.
Control
The part that keeps the old version, to compare with.
Blue and green
Two complete environments. One serves, the other waits or is updated.
Mirroring
Sending a copy of requests to a second version and ignoring its answers. Also called shadowing.
Rollback
Going back to the old version. With weights it means setting a number to 0.
Outlier ejection
Removing one server that behaves worse than the others, for a while.
Retry budget
A limit on retries as a share of normal requests.
Expand and contract
Change the database in steps so that the old and the new version both work.

Understand it

Start here

A new slide at the water park

Let a few people try it first
BlueGreen

The blue slide was never taken down while the green one was on trial.

At the water parkIn the system
Blue slide, green slideOld and new version
Guard who sends visitorsLoad balancer with weights
Guard who watchesAutomatic comparison of errors and delay
ChainWeight 0
Slide kept standingOld version kept for rollback

The idea

Deploying is not releasing

Deploying puts a version on servers. Releasing sends users to it. When they are two steps, you can stop between them. The balancer is what separates them.

Four patterns, one question each

  • Canary

    Is it safe for a few? Then for more.

  • Blue-green

    Can we switch everybody, and back, in seconds?

  • Circuit breaker

    Should we call it at all right now?

  • Retry with timeout

    How long do we wait, and may we ask again?

A canary with a judge

Users send requests to a load balancer with weights. 95 percent go to the stable version and 5 percent to the canary. Both report metrics to an analysis service, which compares them and sets the next weight.
Solid: requests. Dashed: numbers. The analysis decides on the next weight.

Canary

Shift weight in steps and compare

A common plan

StageOld versionNew versionWait for
195%5%First errors, crashes, memory
275%25%Delay under load
350%50%Database and cache effects
Done0%100%Keep the old one for a while
First steps between 1% and 10% are usual. AWS CodeDeploy offers ready plans that start with 10%.

One step of a rollout

Who is hurt by a bad version

failed=r⋅w⋅t⋅e\text{failed} = r \cdot w \cdot t \cdot e
1,000 requests a second, weight 5%, found after 300 s, 20% of them fail: 3,000. At 100% it would be 60,000.

How many requests you must see

n≈3pn \approx \frac{3}{p}
To see at least one failure of rate p with 95% confidence. For p = 0.1% that is 3,000 requests, or 60 seconds at 50 a second.

Choose users, not requests. With a random choice per request, a user who loads 20 pages meets a 5% canary with a chance of 1 - 0.95^20, about 64%, and flips between versions. A hash of the user's id keeps each user on one side, and a user who was in at 5% is still in at 25%.

Python
from zlib import crc32def bucket(user, salt):    return crc32(f"{salt}:{user}".encode()) % 10_000def version(user, salt, percent):    return "new" if bucket(user, salt) < percent * 100 else "old"users = [f"user-{i}" for i in range(10_000)]at5 = {u for u in users if version(u, "r42", 5) == "new"}at25 = {u for u in users if version(u, "r42", 25) == "new"}print(len(at5), len(at25), at5 <= at25)   # about 500, about 2500, True
A bucket per user. Change the salt for each release, or the same users will be the testers every time.
Edit and run it in your browser

Blue-green

Two environments and a switch

Two complete production environments run at the same time. Blue serves, green is updated and tested. Then all new traffic goes to green and blue waits as the way back.

After the switch

Users reach a load balancer. A solid arrow goes to the green environment with version 2, which is active. A dashed arrow goes to the blue environment with version 1, which is ready for rollback. Both use one database.
One database below both. That is where the difficulty is.

Switch and back

Good at

  • Going back in seconds.
  • Testing the real environment before users come.
  • No mix of two versions for web requests for long.

Hard at

  • Everybody gets the fault at once.
  • Two environments cost up to double.
  • Open connections and cached DNS stay on the old side.
  • Data written by version 2 that version 1 cannot read.

Mirroring

A copy for the new version

The balancer sends each request to the old version and a copy to the new one. The copy's answer is thrown away. Istio and nginx have this built in. You see errors, delay and load with real traffic and hurt nobody.

Mirrored traffic

The new version must not write to the real database or send real e-mails.

Choose

Which release pattern?

Rolling updateCanaryBlue-greenMirroring
Who meets a faultMore and more usersA fewEverybody, brieflyNobody
Way backMinutesSecondsSecondsNot needed
Extra machinesFewFewUp to doubleUp to double
Versions side by sideYesYes, for longerOnly while drainingYes
NeedsNothingWeights and good metricsA second environmentSafe side effects

Decide

Two relatives: header routing sends your own staff to the new version by a header or cookie, and A/B tests use the same split to ask which version users prefer. An A/B test answers a product question and runs for weeks. A canary answers a safety question and runs for minutes or hours.

Protection

Eject the bad server

Health checks ask now and then. Outlier ejection watches the real answers: after several server errors in a row, or a success rate far below the others, the server is out for a while and then tried again. This is a circuit breaker for one server, run by the balancer.

Circuit breaker states

Closed: normal. Open: fail fast, use a fallback. Half-open: a few tests to see if it recovered.

The pattern has a page of its own: circuit breaker. Two facts belong here. A balancer must limit how many servers it ejects, or a shared fault removes all. And when too few are healthy, it is better to use all of them: Envoy calls this panic mode, at 50% by default.

Protection

Timeouts and retries with a budget

Exponential backoff, base 100 ms

After failed attemptWaitTotal waited
1100 ms100 ms
2200 ms300 ms
3400 ms700 ms
4800 ms1,500 ms
Each wait is made random (jitter), so that clients that failed together do not come back together.

Details are on the pages about timeouts and retries. At the balancer three rules matter:

  • Retry on another server, not on the one that failed.
  • Retry only what may happen twice: reads, or writes with an idempotency key.
  • Retry in one layer, with a budget.

Retries multiply through layers

calls at the bottom=(1+r)k\text{calls at the bottom} = (1 + r)^{k}
3 retries in each of 3 layers: 4 to the power of 3 is 64 calls for one click, when the bottom is already failing.

A budget allows retries only up to a share of normal requests, for example 20%. With 1,000 requests a second and everything failing, the load becomes 1,200. With 3 retries each it would be 4,000. Envoy recommends retry budgets over a fixed maximum.

Together

In which order the pieces act

  1. 1

    Choose the version

    Weights or a hash of the user: old or new.

  2. 2

    Choose a server

    Among healthy ones that are not ejected. See load balancing.

  3. 3

    Send with a timeout

    Never wait without a limit.

  4. 4

    Maybe retry

    On another server, if the budget allows and the request may happen twice.

  5. 5

    Count

    Errors and delay per version and per server. These numbers feed the canary and the ejection.

Summary

The whole topic in one minute.

Release patterns move traffic, not software: install first, then shift weight, compare with the old version, and go back by changing a number. Canary limits who is hurt, blue-green makes going back fast, mirroring hurts nobody but cannot show everything.

Protection patterns stop failure from spreading: take the bad server out, refuse early, wait for a limited time, retry little. Without limits retries become the outage.

  • Deploying and releasing are two steps. Weights separate them.
  • Canary: 1% to 10% first, compare with the old version, hash users, go back by setting 0.
  • Blue-green: two environments, switch in seconds, database changes must fit both.
  • Mirroring: real traffic, no answers used, beware of writes.
  • Eject bad servers, but limit how many.
  • Retries need backoff, jitter, another server and a budget.

Sources