Sub topic 5
Horizontal scaling: more machines
Horizontal scaling (also called scaling out) adds more machines to a system and divides the work among them. This chapter covers what changes when you go from one server to many, what the application must provide for that to work, and where it goes wrong. It assumes you know the basics of client-server web architecture, the main server resources (CPU, memory, disk, network), and what a web server and a database do. It also assumes you have read the earlier chapters on capacity, metrics, bottlenecks, and vertical scaling.
What horizontal scaling changes
Vertical scaling makes one machine bigger. Horizontal scaling keeps each machine the same size and increases the number of machines. The unit of capacity changes from "one big server" to "a pool of identical servers", often called a fleet or cluster.
Suppose one server handles 500 requests per second (RPS) before latency climbs. Three identical servers can in principle handle about 1,500 RPS. The words "in principle" matter, and most of this chapter explains why the real number is lower.
| Aspect | Vertical scaling | Horizontal scaling |
|---|---|---|
| What changes | Size of one machine | Number of machines |
| Application changes | Usually none | Often required (statelessness, shared storage) |
| Failure of one machine | Total outage | Partial capacity loss |
| Upper limit | Largest available machine | Much higher, but limited by coordination costs |
| Downtime to grow | Often needed (resize, reboot) | Usually none (add a node) |
The three parts a scaled-out system needs
Adding servers is not enough. A horizontally scaled web tier needs three things:
- A way to send each request to one of the servers (a load balancer).
- Servers that can handle any request, so it does not matter which one gets it (stateless design).
- A shared place for data that all servers read and write (a data tier that can serve many clients).
If any of these is missing, adding servers does not help or makes things worse. The next chapters cover load balancing and statelessness in detail. This chapter shows how they fit together.
Distributing requests
The simplest distribution method is round-robin: the balancer sends each request to the next server in a list and wraps around at the end. This Python snippet shows the idea in miniature.
from itertools import cycle
servers = ["app-1", "app-2", "app-3"]
pool = cycle(servers)
for request_id in range(5):
print(request_id, "->", next(pool))It prints:
0 -> app-1
1 -> app-2
2 -> app-3
3 -> app-1
4 -> app-2Round-robin assumes every request costs about the same. That is often false. If one request runs a 5-second report and the next runs a 5-millisecond lookup, equal counts of requests do not mean equal load. Real balancers offer other policies, such as least connections (send to the server with the fewest open connections) or weighted round-robin (send more traffic to larger servers). Pick the policy by looking at how uneven your request costs are.
Statelessness is the main requirement
State is any information the server remembers between requests. A login session held in a server's memory is the classic example. If a user logs in on app-1 and the next request goes to app-2, app-2 has no record of the login, and the user appears logged out.
There are two common fixes.
- Sticky sessions. The balancer remembers which server a client used and keeps sending that client there. This is quick to set up, but it breaks even distribution, because a few heavy users can pile onto one server. It also loses the session if that server dies.
- Externalized state. Move the state out of the application server into a shared store such as Redis, a database, or a signed token the client carries (for example a JWT). Any server can then handle any request.
Externalized state is the standard answer, because it allows servers to be added, removed, and replaced freely. Other kinds of local state need the same treatment:
- Uploaded files written to local disk should go to object storage.
- In-memory caches are duplicated per server. They still work, but each server has its own cache contents, so hit rates drop and stale data can differ between servers.
- Scheduled jobs that run from a cron entry will run once per server unless you add a lock or run them from a single dedicated node.
- Local logs should be shipped to a central system, or you must visit each machine to debug.
The shared data tier becomes the next limit
When you add application servers, every one of them opens connections to the same database. The web tier may scale smoothly while the database stays a single machine. Two effects follow:
- Load concentration. Ten servers send ten times the queries to one database.
- Connection limits. If each server keeps a pool of 50 connections and the database allows 200, then 5 servers already reach the limit. Connection poolers and smaller per-server pools help.
This is why horizontal scaling of the application tier is usually the easy part. Scaling the database (read replicas, sharding) is harder and has its own chapter. For now, remember the order of the work: find the bottleneck first, and check whether the tier you are about to scale out is actually the one that is saturated.
Failure behavior
A major benefit of scaling out is that one server failing does not take down the service. To get this benefit, the balancer must know which servers are healthy. It does this with health checks: it requests a URL such as /healthz from each server at an interval and removes servers that fail several checks in a row.
Plan capacity with failure in mind. If three servers each run at 80% utilization and one fails, the other two must absorb its load and would need to run at 120%, which they cannot. This is called N+1 sizing: provision enough servers that the fleet still copes after losing one (or more). With 4 servers at 60% utilization, losing one raises the other three to 80%, which is survivable.
Health checks have their own failure modes:
- A check that only tests "is the process up" can pass while the database connection is broken.
- A check that tests the database can fail on every server at once when the database is slow, and the balancer then removes the whole fleet. Keep health checks shallow, or make the balancer keep serving when all servers fail.
- Removing a server instantly drops its in-flight requests. Use connection draining so existing requests finish before the server stops.
Why the speedup is not linear
Doubling the servers rarely doubles throughput. Some work cannot be spread out: a single database, a global lock, a serial step in a pipeline. Amdahl's law gives the maximum speedup when a fraction p of the work can be parallelized across n workers:
speedup = 1 / ((1 − p) + p / n)
def amdahl_speedup(parallel_fraction, workers):
return 1 / ((1 - parallel_fraction) + parallel_fraction / workers)
print(round(amdahl_speedup(0.95, 16), 2)) # 9.14
print(round(amdahl_speedup(0.95, 1000), 2)) # 19.63If 5% of the work is serial, 16 servers give about a 9.14x speedup, not 16x. A thousand servers give about 19.63x, and the limit is 20x no matter how many you add. The practical lesson is to find and shrink the serial part, which is often the shared database or a lock, before adding more servers.
Coordination also has costs that Amdahl's law does not model: network hops, cache invalidation traffic, and the extra work of keeping data consistent. These can make a very large fleet slower per server than a small one.
Operating a fleet
More machines means more things to manage. Be ready for these:
- Configuration drift. Servers set up by hand diverge over time. Build them from the same image or configuration so every node is identical.
- Deployments. You must update many servers without downtime. A rolling deployment replaces servers a few at a time, so old and new versions run together briefly. Your code and database schema must tolerate both versions at once.
- Observability. Metrics, logs, and traces must be aggregated across servers. A single slow server hidden inside an average is easy to miss, so look at per-server and percentile latency, not only the mean.
- Cost. Each server has a base overhead (operating system, agents, idle memory), so many small servers can cost more in total than fewer larger ones.
Autoscaling
Because servers are identical and stateless, you can add and remove them automatically. In Kubernetes, a HorizontalPodAutoscaler changes the replica count of a Deployment to keep a metric near a target. This one keeps average CPU near 70%, between 2 and 10 replicas:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70The minimum of 2 keeps the service available if one replica fails. The maximum of 10 caps cost and protects the database from a connection storm. Autoscaling reacts with a delay, because new servers need time to start and pass health checks. For sudden traffic spikes, keep spare headroom or scale ahead of known events.
Common errors
- Scaling out a tier that is not the bottleneck, so latency does not improve.
- Leaving sessions or uploads on local disk, which causes random logouts and missing files.
- Using sticky sessions as a permanent fix, then losing even distribution.
- Ignoring database connection limits when the fleet grows.
- Sizing the fleet for average load with no spare capacity for failure.
- Running scheduled jobs on every server, so work is done many times.
- Judging health only by averages, which hides one bad node.
When horizontal scaling fits
It fits workloads that are request-based, can be split into independent units, and need high availability or growth beyond the largest single machine. It fits poorly when the work is one tightly coupled, serial task, when the application cannot be made stateless without a large rewrite, or when traffic is small enough that one well-sized server with a standby is simpler and cheaper.
Exercise
An application has 4 servers, each running at 70% CPU. The balancer uses round-robin. One server fails its health check and is removed. What utilization do the remaining servers reach, assuming load is spread evenly, and what does this tell you about capacity planning?
Show answer
Total load is 4 × 70% = 280% of one server. Spread across 3 servers, each runs at about 93%. This is close to saturation, so latency will probably climb and a second failure would cause an outage. The fleet was not sized with N+1 headroom. To survive one failure with servers at or below roughly 80%, the fleet needs more servers or a lower normal utilization (for example 5 servers at 56% become 4 servers at 70%).
Exercise
With 90% of the work parallelizable, use Amdahl's law to find the speedup from 10 servers. Then state the maximum possible speedup with unlimited servers.
Show answer
Speedup = 1 / ((1 − 0.9) + 0.9 / 10) = 1 / (0.1 + 0.09) = 1 / 0.19, which is about 5.26x. With unlimited servers, the parallel part shrinks toward zero, leaving 1 / 0.1 = 10x as the maximum.
Exercise
Users report being logged out at random after you add a second application server. Sessions are stored in each server's memory. Name two fixes and one drawback of each.
Show answer
Fix 1: sticky sessions, so the balancer sends each user to the same server. Drawback: uneven load, and sessions are lost if that server fails. Fix 2: move sessions to a shared store such as Redis. Drawback: an extra component to run, secure, and keep available, and a network call on each request.