Projects / Load balancer
Go · about 10 hours · 4 phases
Build a load balancer in Go
When a website gets busy, one server is not enough. So there are several, and something has to decide which one gets each request. That something is a load balancer, and it also has to cope when a server dies, slows down, or needs to be swapped out while people are using it. In about 10 hours you will build one yourself in Go.
You work in four phases of about 2.5 hours each. Every phase ends with something you can run and see, so you always know whether you are done. By the end you will have:
- a proxy that spreads 3,000 requests evenly across three servers,
- health checks that take a dead server out of rotation and bring it back, with only a few requests lost,
- timeouts, safe retries, and a policy that copes with a slow server about four times better than taking turns,
- a proxy you can reconfigure and stop while it is busy, without dropping a single request.
You only need basic Go: variables, functions, structs and go run. Goroutines, atomics and signals are explained when they first show up.
The four phases
Spread the requests
You end with a proxy that sends 3,000 requests evenly across three servers, and a clear picture of what goes wrong when one of them dies.
- 1.1 Three tiny backends30 min
- 1.2 Forward one request35 min
- 1.3 Take turns35 min
- 1.4 Count with a load generator30 min
- 1.5 Break it20 min
Stop sending traffic to dead servers
You end with a backend killed in the middle of a busy run costs about four requests, not a thousand, and it rejoins by itself when it comes back.
- 2.1 Remember who is alive30 min
- 2.2 Ask them every second45 min
- 2.3 Notice at once25 min
- 2.4 Kill one under load30 min
- 2.5 Why two in a row?20 min
Choose well, wait less
You end with a table that shows least connections handling the same slow backend about four times faster than round robin.
- 3.1 Never wait forever40 min
- 3.2 Retry the safe ones45 min
- 3.3 Fewer requests for the busy one35 min
- 3.4 Measure both30 min
Change it while it runs
You end with a script that swaps a backend under load and shuts the proxy down mid-flight, and both runs report failed 0.
- 4.1 A status page25 min
- 4.2 Backends from a file35 min
- 4.3 Reload under load, and a leak45 min
- 4.4 Stop politely30 min
- 4.5 The final test15 min