Sub topic 1
Why one server is not enough: scaling and availability
Prerequisites
This chapter assumes you already know the following:
- How a client and a server exchange requests and responses over HTTP.
- What TCP, IP addresses and ports are, and that a server listens on an address and port pair.
- How to edit a text configuration file and run commands in a terminal.
You do not need any load balancer experience. This chapter sets up the problem that load balancers solve. Later chapters cover the tools.
The single-server starting point
Most services begin on one machine. A web server, the application code and often the database run together. This is simple to build, simple to debug and cheap to run. It works well until one of two things happens.
- Demand grows past what the machine can handle.
- The machine fails, and the service goes down with it.
The first problem is about capacity. The second is about availability. They are related but different, and a good design addresses both. This chapter defines each one, shows how to measure it, and explains why spreading work across several servers needs a new component in front of them.
Capacity and scaling
Capacity is the amount of work a system can do before response times degrade or requests fail. You usually measure it as requests per second, concurrent connections, or bytes per second.
Every server has limits on CPU, memory, network bandwidth, disk I/O and operating system resources such as open file descriptors. The first limit you hit is the bottleneck. When load rises past it, you see the typical symptoms:
- Latency climbs, because requests wait in queues.
- Connections are refused or time out once the listen queue is full.
- Errors such as HTTP 502, 503 and 504 appear.
- The process may run out of memory and be killed by the operating system.
Vertical scaling
Vertical scaling (scaling up) means moving to a bigger machine: more cores, more RAM, faster disks.
Advantages:
- No change to the application.
- No coordination between machines.
Limits:
- There is a ceiling. The largest machine you can buy or rent is finite.
- Cost often rises faster than capacity near the top of the range.
- Resizing usually needs a restart, which means downtime.
- It does nothing for availability. One big machine is still one machine.
Horizontal scaling
Horizontal scaling (scaling out) means running several copies of the server and sharing the work among them. Each copy is called a backend, and the group is a pool.
Advantages:
- Capacity grows by adding machines, in small steps.
- You can use cheap, uniform hardware or virtual machines.
- Losing one machine loses only a fraction of capacity.
Costs:
- Something must decide which backend gets each request.
- The application must tolerate running as several copies.
- Operating many machines is more work than operating one.
| Property | Vertical scaling | Horizontal scaling |
|---|---|---|
| How capacity grows | Bigger machine | More machines |
| Upper limit | Largest available machine | Much higher, bounded by design and budget |
| Downtime to grow | Often needed | Usually none |
| Failure impact | Total outage | Partial capacity loss |
| Application changes | None | Often needed (state, sessions) |
| Extra components | None | A way to distribute traffic |
The last row is the reason this tutorial exists. Once you have several backends, clients still need a single name and address to connect to. Something has to receive each request and hand it to one of the backends.
Availability
Availability is the fraction of time a service is working when users need it. It is usually quoted as a percentage of time, often called "nines".
| Availability | Allowed downtime per year | Allowed downtime per month (30 days) |
|---|---|---|
| 99% | about 3.65 days | about 7.2 hours |
| 99.9% | about 8.76 hours | about 43 minutes |
| 99.99% | about 52.6 minutes | about 4.3 minutes |
| 99.999% | about 5.3 minutes | about 26 seconds |
You can compute these numbers yourself. The following script converts an availability target into allowed downtime.
SECONDS_PER_YEAR = 365 * 24 * 3600
def downtime_per_year(availability_percent):
"""Return allowed downtime in seconds per year."""
return SECONDS_PER_YEAR * (1 - availability_percent / 100)
for target in (99.0, 99.9, 99.99, 99.999):
seconds = downtime_per_year(target)
print(f"{target}% -> {seconds / 60:.1f} minutes per year")Running it prints about 5256 minutes for 99%, 525.6 for 99.9%, 52.6 for 99.99% and 5.3 for 99.999%.
Single points of failure
A single point of failure (SPOF) is a component whose failure takes down the whole service. A lone server is a SPOF. So are a single power supply, a single network switch, a single database and, as later chapters show, a single load balancer.
Redundancy removes a SPOF by keeping more than one component able to do the same job. Redundancy only helps if failover works. That means:
- Failure is detected quickly and correctly.
- Traffic stops going to the failed component.
- The remaining components can carry the extra load.
Step 3 is easy to forget. If two servers each run at 70% of capacity and one fails, the survivor receives 140% of what it can handle. It then fails too. This is a cascading failure. A common rule is to size the pool so that the loss of one member (often written N+1) leaves the rest under their limits.
Why redundancy improves the numbers
Suppose one server is available 99% of the time, and failures are independent. Two servers are both down at the same time only 1% of 1%, or 0.01% of the time. With perfect failover, that gives 99.99% availability.
def parallel_availability(single, copies):
"""Availability of N independent copies where any one is enough."""
return 1 - (1 - single) ** copies
for n in (1, 2, 3):
print(n, f"{parallel_availability(0.99, n):.6f}")The output is 0.990000, 0.999900 and 0.999999 for one, two and three copies.
Treat these figures as an upper bound. They assume that:
- Failures are independent. Two servers in the same rack share power and a switch, so they often fail together.
- Failover is instant and always works. In practice detection takes seconds, and some requests fail in that window.
- Whatever distributes traffic is itself reliable. If it is not, it becomes the new weakest link, and the chain is only as strong as that link.
What goes wrong with naive approaches
Before introducing a load balancer, it helps to see why simpler ideas fall short.
One hostname, several IP addresses
You can publish several A records for one DNS name. Clients receive the list and pick an address, often the first. This spreads load roughly, and it needs no extra hardware. It has real problems:
- DNS does not know which servers are healthy. A dead server's address keeps being handed out until you edit the records.
- Resolvers and clients cache answers for the record's time to live (TTL). Changes take time to reach everyone.
- Clients choose in their own ways, so the spread can be uneven.
- You cannot take a server out of rotation cleanly.
DNS-based distribution has a legitimate role at a larger scale, covered in a later chapter on global load balancing. It is a poor way to handle failover inside a single site.
Client-side lists
You can give clients a list of servers and let them retry on failure. This works for some internal services with well-controlled clients. For public web traffic it does not. You cannot update every browser, and each client would need its own health logic.
Manual failover
An operator notices an outage and repoints traffic by hand. This is slow, error prone and depends on someone being awake. It works for rare, planned changes, not for unplanned failures.
The load balancer as the missing piece
A load balancer sits between clients and the pool. Clients connect to one stable address, and the load balancer forwards each request or connection to a backend. That one position gives it several abilities:
- Distribution. It spreads work across backends using a chosen algorithm.
- Failure detection. It checks which backends are working and stops sending traffic to the ones that are not.
- Transparent changes. You can add, remove or replace backends without clients noticing.
- A single entry point. It can also handle shared jobs such as TLS, logging and rate limiting, depending on the type.
The next diagram shows the arrangement.
The diagram also shows the new risk. The load balancer is now the single entry point, so it must not become a SPOF. A later chapter covers how to make the load balancer tier redundant.
Designing the application for a pool
Adding a load balancer does not make an application scale by itself. The application must behave correctly when any request can land on any backend.
Stateless services
A stateless backend keeps no information about a client between requests. Everything needed to handle a request arrives with it, or is read from a shared store. Stateless services are easy to scale, because every backend is interchangeable.
Where state goes
Real applications have state. The usual approach is to move it out of the web servers and into shared systems:
- User sessions go in a shared store such as Redis or a database, or into a signed token carried by the client.
- Uploaded files go to object storage or a shared file system, not the local disk of one backend.
- Caches can be local if a miss is harmless, or shared if consistency matters.
- Scheduled jobs need coordination so that three copies do not run the same job three times.
If state stays on individual servers, you must send each client back to the same server every time. That technique is called session persistence, and it has costs that a later chapter examines.
Shared dependencies
Scaling the web tier moves the bottleneck. If ten backends all query one database, the database becomes the limit and the SPOF. Horizontal scaling of the front tier does not remove the need to plan the data tier. Common responses include read replicas, caching and connection pooling. These topics are outside this tutorial, but you should recognize the pattern: each tier has its own capacity and availability questions.
Measuring before and after
Decide how you will measure the result before you change the architecture. Useful measures include:
- Requests per second at the entry point.
- Latency percentiles such as p50, p95 and p99. Averages hide the slow tail that users notice.
- Error rate, split by status code class (4xx versus 5xx).
- Utilization of CPU, memory and connections on each backend.
- Whether load is even across backends.
A simple capacity estimate helps with planning. Suppose a single backend handles 400 requests per second before latency becomes unacceptable, and you expect peaks of 1,500. You need at least four backends for capacity, and a fifth so that losing one still leaves enough. That is N+1 sizing.
import math
def backends_needed(peak_rps, per_backend_rps, spare=1):
"""Backends required for peak load, plus spare capacity for failures."""
return math.ceil(peak_rps / per_backend_rps) + spare
print(backends_needed(1500, 400))This prints 5. Measure the per-backend figure with a load test. A guess is not enough, because it drives the whole calculation.
Common mistakes
- Scaling out without removing local state. Users get logged out or lose uploads when a request reaches a different backend.
- Sizing for the average. Traffic comes in peaks, and failures happen during them.
- Ignoring the N+1 rule. The pool works until the first failure, then collapses.
- Treating redundancy as availability. Two servers in one rack, one zone or on one power feed share fate.
- Forgetting the new SPOF. A pool behind a single load balancer is only as available as that load balancer.
- Assuming DNS handles failover. DNS records do not track health, and caches delay changes.
Where this leads
The rest of the tutorial builds on this problem. The next chapter defines what a load balancer does in more detail. After that, you will learn how Layer 4 and Layer 7 balancing differ, how algorithms choose a backend, and how health checks keep traffic away from failures. Later chapters cover session persistence, TLS, deployment options, graceful removal of servers, redundancy for the load balancer itself, global distribution and troubleshooting.
Exercise
A service runs on two servers, each at 65% of its capacity. One server fails. What happens to the surviving server, and what sizing change would prevent the problem? Assume traffic stays the same and is shared evenly.
Show answer
The surviving server receives all the traffic, which is 130% of its capacity (65% + 65%). It becomes overloaded, latency and errors rise, and it may fail too, causing a cascading failure. To prevent this, size the pool with N+1 spare capacity so the remaining servers stay under their limits after one failure. For example, run three servers at about 43% each, so that after one fails the other two carry about 65% each. Alternatively, keep two servers but run each below 50% of capacity.
Exercise
A single server is available 99.5% of the time. Assuming independent failures and perfect failover, what is the availability of two such servers where either one is enough? Give one reason the real figure would be lower.
Show answer
Both are down at once with probability 0.005 × 0.005 = 0.000025, so availability is 1 − 0.000025 = 0.999975, or 99.9975%. The real figure would be lower because failures are rarely independent (servers can share power, a network switch or a software bug), failover is not instant, and the component that distributes traffic can itself fail.