Sub topic 10
Trade-offs: availability, cost, and complexity
This chapter assumes you know what vertical and horizontal scaling are, and that you can read basic latency and utilization numbers. You have also seen load balancers and stateless application servers. Here the focus is on what each approach costs you in availability, money, and engineering effort. The same traffic can be served by one large machine or by many small ones, and the two designs fail, bill, and break in different ways.
Availability: what happens when a machine dies
Availability is the fraction of time a system answers requests correctly. Scaling choices change it in two ways: how many machines can fail before users notice, and how much capacity you lose when one does.
The single big machine
A vertically scaled system often ends up with one large server. That server is a single point of failure (SPOF): if it dies, everything on it is down. Planned work also causes downtime. Resizing a cloud instance usually means stopping it, changing its type, and starting it again. Kernel patches and database upgrades may need a restart too.
You can reduce the risk with a standby copy, but that adds cost and a failover process. A hot standby sits idle until the primary fails, so you pay for two large machines and get the capacity of one.
Many small machines
With horizontal scaling, losing one of N machines removes only 1/N of capacity. If the other machines have enough headroom, users see little or nothing. Rolling deploys also work well here. You update one machine at a time while the rest serve traffic.
Redundancy only helps if the failure is independent. Ten servers in one rack share a power feed and a switch. Ten servers in one availability zone share that zone's fate. Spreading across zones improves availability, but it adds cross-zone network latency and, on most clouds, data transfer charges.
Capacity after a failure
Headroom is the part that people forget. Suppose three servers each run at 80% utilization. If one fails, the other two must absorb its load, and each would need to run at 120%. They overload, and the failure cascades.
Size the pool so that it can lose a machine and still stay under your target utilization. This is often called N+1 sizing. The table shows the maximum safe average utilization per server before a single failure pushes the survivors over 100%.
| Servers (N) | Safe utilization with one failure | Idle capacity you pay for |
|---|---|---|
| 2 | 50% | 50% |
| 3 | 66.7% | 33.3% |
| 5 | 80% | 20% |
| 10 | 90% | 10% |
Larger pools waste less on redundancy. This is one real economic advantage of horizontal scaling: the cost of "one spare" shrinks as the pool grows.
A calculation you can run
If one server is available 99.5% of the time and failures are independent, the chance that all of N servers are down at once is 0.005 raised to the Nth power. This code compares one server to a pool where at least one server must be up. It is an optimistic model, because it ignores shared failures and the capacity problem described above.
def pool_availability(single, n):
"""Probability that at least one of n independent servers is up."""
return 1 - (1 - single) ** n
single = 0.995
for n in (1, 2, 3):
print(n, f"{pool_availability(single, n):.6%}")The output is 99.5%, 99.9975%, and 99.999988%. Real systems land well below these numbers, because the load balancer, the database, and shared deploy mistakes also fail. The point is the shape: each added independent server multiplies the failure probability by a small factor, but only if the system really tolerates the loss.
Cost: price per unit of capacity
Cost has more than one dimension. The main ones are the price of the hardware, the price of idle capacity, the price of operations, and the price of engineering time.
Hardware pricing curves
Small and mid-sized machines are sold in volume, so cloud providers price them close to linearly. An instance with twice the vCPUs and memory often costs about twice as much. At the high end the curve bends upward. Machines with very large memory, many sockets, or special storage cost more per unit of capacity, and you may have only a few types to choose from. In an on-premises setting the effect is stronger: a server with four sockets costs much more than twice a two-socket server.
So vertical scaling is usually cheap at first and expensive near the ceiling. Horizontal scaling keeps the price per unit roughly flat, but adds the overheads below.
Overheads of many machines
- Per-machine overhead. Each machine runs an operating system, agents for logging and monitoring, and sometimes a runtime. These use CPU and memory that do no application work. Ten small machines carry ten copies of that overhead, one big machine carries one.
- Load balancer and network. Load balancers bill per hour and per unit of traffic. Cross-zone traffic can add per-gigabyte charges.
- Licensing. Software priced per core, per socket, or per node changes the math. A database licensed per core makes a large machine expensive. A product licensed per node can make many small machines expensive.
- Idle capacity. You provision for peaks. A fixed pool sized for the daily peak is mostly idle at night. Autoscaling, covered in a later chapter, recovers some of this. A single big machine cannot shrink without a restart.
Engineering cost
People are usually the largest cost. A design that needs a distributed cache, session handling, a deploy pipeline for many nodes, and cross-node debugging takes engineer-weeks to build and an ongoing share of attention to run. If a larger instance solves your problem for an extra few hundred dollars a month, that is often cheaper than the engineering time to avoid it. The reverse also holds: at large scale, the savings from commodity machines pay for a platform team.
Complexity: what you take on
Complexity is the third axis. It is harder to measure than price, but it decides whether a design stays reliable.
Vertical scaling is simple until it isn't
Moving to a bigger instance needs no application changes. Code, configuration, and data stay in one place. Transactions are local, there is no network between components, and debugging means looking at one machine. That is a real benefit, and it is why many systems should scale vertically first.
The complexity appears later. Very large machines have non-uniform memory access, long garbage collection pauses, and long restart and recovery times. A restart that must reload hundreds of gigabytes of cache can take many minutes. Backups and restores of one huge volume are slow, which lengthens your worst-case recovery time.
Horizontal scaling adds distributed-systems problems
Once work spreads across machines, you inherit problems that a single machine did not have:
- State. Sessions, uploads, and local caches must move out of the server process, or requests must be pinned to one server. See the earlier chapter on stateless design.
- Partial failure. A call to another machine can time out with no way to know if it ran. You need timeouts, retries, and idempotent operations.
- Consistency. Replicas and caches can disagree for a short time. Your application must tolerate stale reads, or pay latency to avoid them.
- Coordination. Scheduled jobs, leader election, and locks need care so that two nodes do not run the same job.
- Observability. A single request touches several machines. You need centralized logs, metrics, and request tracing to follow it.
- Deployment. Versions overlap during a rolling deploy, so every change must work with both old and new code running together.
Retries show the hidden cost
Here is a small example of the partial-failure problem. A client retries a call that timed out. If the server already processed the first call, the retry duplicates the effect. An idempotency key makes the retry safe.
processed = {}
def charge(idempotency_key, amount):
if idempotency_key in processed:
return processed[idempotency_key] # repeat call, same result
result = f"charged {amount}"
processed[idempotency_key] = result
return result
print(charge("order-42", 30))
print(charge("order-42", 30)) # retry does not charge twiceIn a real service, the processed table lives in shared storage, not in process memory. If it lived in memory on one of several servers, a retry routed to another server would charge twice. This is the sort of bug that only exists once you scale out.
Comparing the two side by side
| Dimension | Vertical scaling | Horizontal scaling |
|---|---|---|
| Failure impact | All capacity lost if the machine fails | Only 1/N of capacity lost |
| Planned downtime | Often required for resizing | Rolling updates avoid it |
| Cost at small scale | Low, no extra components | Higher, needs load balancer and shared state |
| Cost at large scale | Rises steeply near the ceiling | Roughly linear per unit |
| Application changes | None or few | Stateless design, shared stores |
| Operational effort | One machine to manage | Fleet, deploys, observability |
| Upper limit | Largest available machine | Coordination overhead and shared components |
| Recovery from failure | Slow restart, or promote standby | Replace one node quickly |
Edge cases and common mistakes
- Counting servers instead of capacity. Three servers do not give three servers of safe capacity if you must survive a loss. Count capacity after failure.
- Redundancy with a shared dependency. Two app servers that depend on one cache, one queue, or one config service are not independent.
- Scaling out before measuring. If the bottleneck is a database lock, more web servers add contention and make it worse.
- Ignoring warm-up. New instances start with cold caches and cold connection pools. A pool that autoscaled in response to a spike may serve slowly for several minutes.
- Forgetting failover time. A standby that takes ten minutes to take over still means ten minutes of outage. Availability numbers should include detection and failover time.
- Underestimating the human cost. The cheaper design on the invoice may be the more expensive design in on-call hours.
Summary of the trade-off
Vertical scaling buys simplicity and loses on failure tolerance and ceiling. Horizontal scaling buys failure tolerance and a higher ceiling, and charges in complexity, overhead, and the need to design for state. The right balance depends on how much downtime you can accept, how fast you will grow, and how large your team is.
Exercise
A service runs on 4 identical servers behind a load balancer. Each handles at most 1000 requests per second. Traffic is 3000 requests per second, spread evenly. One server fails. Explain what happens to utilization on the remaining servers, and what the maximum safe average load per server would have been to survive one failure with no overload.
Show answer
Before the failure, each server handles 750 requests per second, which is 75% utilization. After one fails, 3000 requests per second spread over 3 servers gives 1000 each, which is exactly 100%. That leaves no headroom, so any variation causes queueing and rising latency, and a cascade is likely. To survive one failure safely, the total traffic must fit on 3 servers, so each of the 4 servers should run at no more than 75% of capacity in normal operation, and in practice lower, such as 60 to 70%, to leave margin for bursts. Here the load is exactly at the limit, so the pool should have a fifth server or the load should be reduced.
Exercise
Your team runs a single large database server and a stateless web tier of 6 servers. The database host fails once a year and takes about 20 minutes to recover. A colleague proposes adding 6 more web servers to "improve availability." Is this the best use of effort? Name a better first step.
Show answer
Probably not. The web tier already tolerates the loss of a server, and the system's availability is limited by the least redundant component, the database. Adding web servers does not remove that single point of failure. A better first step is to add a replica of the database with automated failover, and to test the failover, so that recovery takes seconds or a couple of minutes rather than 20 minutes. Also check that the 6 web servers can absorb the loss of one under peak load.