Sub topic 12
Choosing a strategy for your workload
This chapter pulls the earlier ideas together into a decision process. It assumes you know the difference between vertical scaling (a bigger machine) and horizontal scaling (more machines). It also assumes you can read latency, throughput, and utilization numbers, and that you know why horizontal scaling needs a load balancer and stateless application servers.
By the end you should be able to take a workload, find what limits it, pick a scaling approach, and defend the choice.
Start with the bottleneck, not the technique
Scaling choices fail most often because the team picks a technique before it knows what is slow. Adding servers does not help a system that waits on one database lock. A bigger machine does not help a system that is limited by a single-threaded process.
Work through these questions in order:
- What is the goal? A latency target (for example, p95 under 300 ms), a throughput target (for example, 2,000 requests per second), or an availability target (for example, survive the loss of one machine)?
- Which resource saturates first under load: CPU, memory, disk I/O, network, or a lock or connection pool?
- Which tier holds that resource: web or application servers, cache, database, or an external dependency?
- Is the work in that tier parallelizable, and is its state shared?
The answer to question 3 matters most. Application tiers are usually the easiest to scale out. Data tiers are usually the hardest.
The decision by tier
Different tiers of the same system often need different strategies. A common result is horizontal scaling for the application tier and vertical scaling, plus read replicas, for the database.
| Tier | Usual first move | Why | Watch for |
|---|---|---|---|
| Stateless application servers | Scale out behind a load balancer | Any server can handle any request, so capacity grows nearly linearly | Shared dependencies (database, cache) becoming the new bottleneck |
| Stateful application servers (sessions in memory) | Externalize state, then scale out | Without this, the load balancer needs sticky sessions, and a lost server loses sessions | Session store becoming a single point of failure |
| Cache | Scale up first, then shard the keys | A bigger cache raises hit rate with no client changes | Hot keys, and cold-cache load spikes after a restart |
| Relational database, read-heavy | Scale up, then add read replicas | Replicas absorb reads without changing the write path | Replication lag causing stale reads |
| Relational database, write-heavy | Scale up as far as is practical, then shard | Writes go to one primary, so replicas do not help | Sharding forces key design, loses cross-shard transactions, and is hard to undo |
| Batch or queue workers | Scale out workers | Jobs are independent and can run in parallel | Ordering requirements and a shared queue limit |
Why the answer differs: the workload shape
Workload shape tells you which constraints you must plan for.
- Steady load with slow growth. Vertical scaling is often cheapest in engineering time. You resize once or twice a year. A single large machine is easy to operate and debug.
- Spiky or daily-cyclic load. Horizontal scaling with autoscaling fits. You pay for capacity only when the load needs it.
- Read-heavy load. Caching and read replicas give large gains before any sharding is needed.
- Write-heavy load. The write path is the hard part. Scale the primary up first, and plan the partitioning key before you need it.
- Strict availability target. Horizontal scaling is required, because one machine, however large, is a single point of failure.
- Low-latency per request, with each request needing a lot of memory or CPU. Vertical scaling helps each request. More machines only help with the number of concurrent requests.
Check the ceiling with Amdahl's law
Before committing to many workers, estimate the best possible speedup. Amdahl's law says that if a fraction p of the work can be parallelized, the speedup with n workers is 1 / ((1 - p) + p / n). The serial fraction 1 - p sets a hard cap of 1 / (1 - p).
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.63With 5% serial work, 16 workers give about 9.14x, and 1000 workers give about 19.63x. The cap is 20x. In practice the serial part is often a shared database, a lock, or a coordinator. If your measurements show a serial fraction that large, adding servers is the wrong investment. Fix the serial part first, or scale that part vertically.
Amdahl's law is optimistic. It ignores coordination costs such as network hops, cache invalidation, and lock contention. Real scaling usually falls short of the formula.
Cost and complexity as inputs
Capacity is not the only output. Compare options on these dimensions:
- Cost curve. Large machines often cost more than proportionally per unit of capacity at the top of a size range. Several small machines are often cheaper per unit, but you also pay for load balancers, network traffic between machines, and idle headroom on each.
- Operational complexity. One machine has one set of logs, one deploy target, and no distributed failure modes. A fleet needs deployment automation, health checks, centralized logging, and a plan for partial failure.
- Engineering cost. Making an application stateless, or sharding a database, can take weeks. Resizing a machine can take minutes. Compare the one-time engineering cost with the ongoing infrastructure saving.
- Reversibility. Resizing is easy to undo. Sharding is not. Prefer the more reversible option when you are unsure.
- Failure impact. With one large machine, a failure takes out everything. With ten machines, a failure removes about 10% of capacity, provided the rest can absorb the load.
The last point has a sizing consequence. If you need capacity for 8 units of load and want to survive one machine failing, 3 machines of 4 units each (12 total) can hold the load after a failure. Two machines of 8 units each (16 total) can too, but cost more. One machine of 8 units cannot survive a failure at all. This is the usual N+1 reasoning.
A decision flow
Worked example
A web store has three tiers: web servers, a PostgreSQL primary database, and a Redis cache. During a sale, p95 latency rises from 200 ms to 2.4 s. Measurements show:
- Web servers: CPU at 92%, memory at 40%.
- Database primary: CPU at 35%, 90% of queries are reads.
- Cache hit rate: 80%.
The saturated resource is web server CPU, and the servers keep sessions in a shared Redis store, so they are effectively stateless. The decision is to scale out the web tier behind the existing load balancer. The database has room.
After adding servers, the team re-measures. Database CPU rises to 70%, because the web tier now sends more queries. The new bottleneck is the database. Since reads dominate, the next step is a read replica and a higher cache hit rate, not sharding. This is the normal pattern: scaling one tier moves the bottleneck to the next.
An autoscaling policy suits the sale traffic, which rises and falls. The following HorizontalPodAutoscaler keeps average CPU near 70% with 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 meets the availability goal. The maximum of 10 caps cost and protects the database from an unbounded flood of new connections. The 70% target leaves headroom while new replicas start.
Common mistakes
- Scaling before measuring. You add servers to a tier that was never the bottleneck.
- Ignoring the next bottleneck. Scaling out the application tier floods the database. Check connection pool limits and query load after each change.
- Scaling out stateful servers. Without externalized state or sticky sessions, users lose sessions or see inconsistent data.
- Sharding too early. It is the most expensive change to reverse. Exhaust caching, indexing, query tuning, vertical scaling, and read replicas first.
- Sizing with no failure margin. A cluster that runs at 90% utilization cannot absorb one machine's failure.
- Setting autoscaling limits without a maximum. A bug or an attack can create runaway cost.
- Trusting the Amdahl formula as a promise. Measure real speedup with a load test.
Summary of the decision rules
- Measure first. Choose the strategy for the saturated tier, not for the whole system.
- Prefer the simplest option that meets the target: vertical scaling when load is steady and a single machine suffices, horizontal scaling when load is spiky or availability matters.
- Make the application tier stateless so that it can scale out. Keep state in the data tier or a shared store.
- For the data tier, move in order of reversibility: tuning, caching, scale up, read replicas, then sharding.
- Check the Amdahl ceiling for the serial part before adding many workers.
- Size for the failure of one machine, and re-measure after every change.
Exercise
A service has two application servers at 85% CPU each. Both keep user sessions in local memory. The database is at 20% CPU. Traffic doubles every Friday evening and falls back by Saturday. Which strategy do you choose, what must you change first, and why does losing one server today create a problem?
Show answer
Scale out the application tier with autoscaling, since the load is cyclic and the application tier is the saturated one. First externalize the sessions (for example to Redis or a database) so that any server can handle any request. Today, if one server fails, its sessions are lost, and the remaining server would face the full load at about 170% of its capacity, so it would be overloaded. After the change, keep a minimum of at least 2 replicas with headroom, set a maximum to protect the database, and re-measure the database afterward because it will receive more queries.
Exercise
A write-heavy orders database is at 95% CPU on its primary. It already has two read replicas, and reads are only 10% of the traffic. A colleague proposes adding five more read replicas. Is that a good choice? What do you do instead?
Show answer
No. Read replicas only take reads, which are 10% of the load, so they do not relieve the primary's write path. First tune queries and indexes, then scale the primary up to a larger machine. If writes still exceed what one machine can handle, plan to shard by a key such as customer ID, accepting the loss of cross-shard transactions and the difficulty of reversing the change.
Exercise
A job is 90% parallelizable. What is the maximum speedup from any number of workers, and what is the speedup with 10 workers?
Show answer
The cap is 1 / (1 - 0.9) = 10x. With 10 workers the speedup is 1 / (0.1 + 0.9 / 10) = 1 / 0.19, which is about 5.26x. Adding more workers brings diminishing returns, so reducing the serial 10% is more valuable than adding workers.