The conference site from Networking, HTTP, DNS, and CDNs serves its public schedule at the edge. During registration, however, ticket requests reach the origin. One API instance can handle 500 requests per second at the target latency. Peak demand is 2,400 requests per second. How many instances do you need, and what happens when several of them disappear at once?
You will size a fleet against an explicit failure, compare assignment algorithms using a burst you can work by hand, and design health checks, shutdown, and autoscaling around actual serving capacity. You should be comfortable following an upstream HTTP request and reading the capacity estimates in Back-of-the-Envelope Estimation.
Find the bottleneck before adding replicas#
Vertical scaling means giving one instance more CPU, memory, storage performance, or network capacity. Choose the resource that is limiting goodput, the rate of useful work completed successfully. A faster CPU may help expensive signature checks. More memory may help a process whose working set spills to disk. If the database spends most of its time waiting on a locked row, upgrades to the front-end tier cannot remove that serialization point.
Horizontal scaling means adding instances and spreading work across them. A pool of equivalent processes can handle independent HTTP requests concurrently. Pooling helps only while work can be distributed and the shared dependencies can absorb the resulting demand. An API with 12 replicas and a 20-connection database pool per replica may ask the database for 240 connections. If the database can sustain only 160 across this service and other tenants, increasing API replicas may worsen queueing and error rates. Budget dependency consumption when you set replica bounds.
Use an open-loop load test to establish per-replica safe throughput, with arrivals continuing independently of previous responses. Include the expected request mix, body sizes, quotas, and downstream latency. Record throughput, error rate, and tail latency while you increase load. A single QPS number is portable only to a sufficiently similar workload. A burst of costly exports can use the resources that otherwise serve many ticket lookups.
Define what any healthy replica can do#
A process is stateless for routing when any eligible replica can handle the next request given the request and shared services. That contract lets the balancer remove one replica without losing the only place a particular user's next operation can run. A process can still keep connection pools, log buffers, and replaceable local caches.
Put ticket ownership, capacity limits, and retry identities in durable shared state. If a ticket write times out and the next attempt reaches another replica, that replica needs the same idempotency record. A shared cookie signing key or a shared session store can let any replica validate the session. Plan for the session store's own capacity and failure modes.
Affinity, also called stickiness, pins related work to a destination for a period. It can help when work benefits from locality, such as successive requests that reuse a large local result. It also shifts load according to the popularity of the affinity key. A sticky session stored only in replica memory can disappear on failover. An established WebSocket is inherently tied to a live connection. The application still needs a reconnect path, resubscription rules, and a way to recover state when the connection ends.
Diagram key and text version
- Entry
- Process
- Client → Load balancer: request
- Load balancer → API replica A: if selected
- Load balancer → API replica B: if selected
Start with one origin instance while it meets demand. As independent request throughput or instance redundancy becomes necessary, place a balancer in front of multiple API instances. Add a health mechanism to control membership, then place replicas across failure domains that match the availability target. Shared state belongs in the data tier, whose own redundancy and scaling plan remain separate.
Choose the layer and unit of assignment#
A Layer 4 balancer routes transport-level traffic. A typical Layer 4 TCP listener chooses a backend for a connection or flow using network and transport information. All work multiplexed inside that TCP connection follows the selection while the flow remains active. With long-lived connections, new replicas may take a while to see substantial traffic.
A Layer 7 HTTP balancer can select routing policy using HTTP information such as hostname, path, or method. It can choose a destination per request or stream when the protocol, connection handling, and policy permit it. A layer that inspects encrypted HTTP needs access to decrypted requests, commonly through TLS termination on that hop. Use the boundary from the preceding lesson when you specify whether and how upstream TLS is authenticated.
For the conference site, route /tickets to the purchase pool and /schedule cache misses to the catalog pool. The pools see different costs and different failure semantics. This isolation stops a catalog surge from competing for the same API workers, though both pools can still contend for shared dependencies. A load balancer can itself be a distributed service, with a data plane forwarding traffic and a control plane supplying configuration and health decisions. Include the balancer in cross-zone capacity and recovery tests.
Compare routing policies by the signal they use#
| Policy | What the router measures | What to verify |
|---|---|---|
| Round robin | Position in an ordered list | Comparable capacity and representative cost mix across successive requests |
| Weighted round robin | Target weight | Weight calibration during mixed instance sizes, canaries, or ramp-up |
| Least connections | Active transport connections | Whether a connection tracks work when clients multiplex or leave connections idle |
| Least requests | Outstanding requests visible to the router | Slow jobs, quick failures, and unobserved load from other routers |
| Two-choice least requests | Outstanding count on two randomly sampled eligible targets | Sampling and stale signals under contention |
| Key-based routing | A stable key such as a tenant or partition | Skew, failure remapping, and the lifecycle of the assigned state |
Round robin is easy to reason about when targets are comparable and the request mix is stable. Weights express intended shares. For weights 2 and 1, the target with weight 2 receives roughly two-thirds of assignments over a sufficiently long stable interval. Check realized shares and work per instance. The algorithm does not infer capacity from a configured weight.
Least requests can steer work away from servers already holding several slow requests. An in-flight count is a proxy for resource consumption. A route that fails in 1 ms can look less busy than a route that successfully handles requests in 50 ms. Combine load observations with error rates and passive outlier signals so quick failures do not attract more work.
The power of two choices compares just two randomly selected eligible targets. In the classic equal-sized balls-and-bins model, choosing the less loaded of two drastically reduces maximum occupancy compared with one random choice. Real requests have variable costs and finish over time, so use that result as intuition and measure production behavior. Envoy's implementation illustrates the distinction between an equal-weight sampled policy and its separate weighted policy.
A hash of a tenant or session can preserve locality. If a single tenant dominates demand, all that tenant's requests may land on one target. Naive modulo hashing also remaps many assignments when the pool size changes. Ring-based or rendezvous placement can make membership changes less disruptive. Check whether the destination must own the data or merely benefits from a warm cache, and choose what happens when its target disappears. The partitioning lesson will examine these placement algorithms in more detail.
Work a burst by hand
Three replicas, A, B, and C, can each run one request at a time. At time zero, six requests arrive in a fixed order with service times of 80, 10, 10, 80, 10, and 10 milliseconds. Ignore network and dispatch overhead. Round robin sends the first and fourth to A, the second and fifth to B, and the third and sixth to C. Since each replica executes in order, A finishes at 80 and 160 ms while B and C each finish at 10 and 20 ms. The balancing metric reports two requests at each host even though A did eight times as much service work.
With all six arriving at once and ties broken in A, B, C order, least outstanding gives the same assignments. Before the fourth request, each replica has one job counted, and the router cannot tell which will finish first. A cost-aware policy could send the fourth job to B. One feasible split is A with the first 80 ms job and one 10 ms job, B with a 10 ms job and the second 80 ms job, and C with the other two 10 ms jobs. Completion then occurs by 90 ms. Cost estimates may be wrong, so an alternative is to route high-cost work into a separate pool or use concurrency limits for expensive operations.
Size the survivors, including zone loss#
Let D be peak offered demand in requests per second, C the measured safe requests per second per ready replica, and F the number of replicas lost in the failure you plan to tolerate. Under homogeneous capacity and sufficiently even routing, provision at least:
Here ceil rounds up to the next whole number. With D=2400 and C=500, at least five ready replicas are needed. Six suffice for one lost instance. But place six as two in each of three zones and lose a zone: the surviving four can serve about 2,000 requests per second, creating a deficit of 400 per second before retries. Seven spread 3/2/2 also fail the largest-zone test. Eight spread 3/3/2 leave five survivors if either largest zone fails, so the estimated capacity is 2,500. If operations require even placement, nine spread 3/3/3 leave six, offering 3,000 requests per second.
Test the availability decision with traffic patterns and zone-aware routing enabled. All survivors must be reachable by the traffic that moved, and their shared dependencies must have enough remaining headroom. A fleet that can sustain a lost zone may still lack capacity for simultaneous rollout disruption. Name the simultaneous failures you budget for and account for maintenance separately.
Separate eligibility, repair, and shutdown#
Active checks probe the destination at intervals. Passive checks infer trouble from live requests, such as connection failures or a rising error count. An occasional timeout is ambiguous, so require evidence before changing membership and require recovery evidence before reintroducing a host. For a check every five seconds with a two-failure threshold, if loss starts just after a successful probe, the failing probe starts occur roughly five and ten seconds later. Add probe timeout and propagation time before assuming every router stopped sending traffic.
A startup probe can give initialization time. Readiness decides whether the replica accepts new traffic. Liveness decides whether its process needs a restart. In Kubernetes these are separate probes through the kubelet and can trigger different actions. An unbounded readiness check against a shared dependency can remove all targets during a database incident. A shallow probe can also miss a locally broken connection pool. Use cheap, meaningful local readiness and a separate signal for fleet-wide dependency degradation. Design route-specific degraded responses where useful work can continue.
Graceful shutdown first marks the replica unavailable for new assignments and gives that state time to propagate. Then allow in-flight work to finish within a grace budget before terminating. Define how existing streams and reused connections behave, since a drain mechanism may cover connections or requests depending on the platform. A planned drain differs from a crash, where in-flight work can fail and mutating requests may have completed before their response disappeared.
Diagram key and text version
- Entry
- Process
- Outcome
- Probe fails → Update target pool: threshold met
- Update target pool → Route to survivor: ready target
- Update target pool → Return 503: empty pool
Some infrastructure explicitly fails open when aggregate health falls below a threshold. AWS Application Load Balancer documents routing failover settings with this behavior. Fail-open trades isolation from known bad targets for a chance of reaching an incorrectly marked one. Choose the policy before an incident, test shared-dependency failure and empty-pool behavior, and make the selected behavior visible in dashboards.
Scale on a signal you can interpret#
Autoscaling is a feedback loop with measurement delay, decision delay, and time to start and warm replicas. A CPU target can work for CPU-bound handlers. Concurrency, in-flight age, or queue backlog may be better if the bottleneck is I/O. Match the metric to the resource that limits successful work and test it during normal peaks and downstream outages. Applying the same scaling signal to API workers and a database can create interacting delays.
Suppose four ready replicas average 75% usage and the target is 50%. A proportional recommendation is 4(75/50)=6 replicas, assuming aggregate work remains constant and divides evenly. A controller such as a Kubernetes HorizontalPodAutoscaler applies extra rules for metric availability, replica bounds, and stabilization. Six replicas matter only once they are ready. If startup takes two minutes and registration opens at a known time, set minimum serving capacity before the spike. Keep headroom throughout rollout and avoid shifting every new request to cold replicas immediately.
When the whole fleet is overloaded, balancing redistributes demand. Scale-out may arrive too late or leave the limiting dependency unchanged. Limit per-replica work in flight, enforce upstream deadlines, and reject lower-priority work before queues exhaust memory. Retries need a fixed attempt budget and backoff with jitter. Otherwise the demand that survives one failure can trigger another.
Diagnose an uneven fleet#
| Observation | Where to look first | What to test |
|---|---|---|
| Even request counts, uneven CPU | Cost by route or tenant | Replay the real mix and compare completed work per target |
| New targets appear but traffic stays on old ones | Readiness and transport reuse | Track endpoints, connection age, and effective routing weight |
| All replicas become unready together | Shared dependency or probe path | Compare probe failures to dependency health and external success |
| More replicas cause more database timeouts | Aggregate connection and query budgets | Measure connection usage, queue time, and database saturation |
| p99 rises after a zone loss | Surviving headroom and traffic placement | Compare arrival rate, active work, retries, and per-zone errors |
In a design interview, state a workload and a failure objective, identify the assignment unit, and draw the transition from one process to a pool. Put durable state and retry identity behind the pool. Calculate surviving capacity, then narrate startup, failure detection, draining, and an empty target set. Close with the metrics or tests that prove the design meets its latency and availability objectives.
Run the Python lab#
Download the lab and run python3 06-load-balancing-horizontal-scaling.py. Python 3.10 or newer is enough. The simulation sends a deterministic burst to single-worker replicas and compares round robin with a full scan for the least outstanding target. Because all requests arrive at once, the queue lengths include every assigned job until the burst has been assigned. Its capacity and health checks confirm the independent assumptions behind zone loss and consecutive probe thresholds.
Try it yourself
Budget an uneven pool
Peak demand is 3,000 requests per second. Each ready replica safely serves 600 requests per second. Compare placements 3/2/2 and 3/3/2 under one lost zone. How much headroom does the better placement retain?
Reveal solution
Five ready replicas are required. From 3/2/2, losing the largest zone leaves four and a 600 requests-per-second deficit. From 3/3/2, losing either largest zone leaves five, meeting demand with zero modeled headroom. Provision additional capacity if routing is uneven, simultaneous maintenance is required, or observed demand can exceed the peak assumption.
Try it yourself
Diagnose a fast-failing hot replica
Least requests sends more traffic to one target even as the overall error rate increases. What observations would explain the skew?
Reveal solution
Check per-target success and error counts alongside latency and in-flight counts. Fast errors complete quickly, so the target appears less loaded. Compare a meaningful readiness probe and upstream error classes, then verify that outlier detection can move traffic away without exhausting survivor capacity.
Memory chart#
Capacity measured safe rate × ready, reachable survivors
State preserve durable identity across replicas
Routing choose a unit, eligibility rule, and assignment signal
Health startup → ready → draining or unhealthy → recovery
Autoscaling signal → recommendation → warm-up → ready capacity
Diagnosis compare assigned work, completed goodput, and failure scope
The next lesson examines Caching Strategies and Invalidation, including what happens when newly added replicas are cold and their misses reach the same backend.
References#
- Designing Data-Intensive Applications, first edition, Chapter 1, covers load parameters, response distributions, and vertical and horizontal scaling.
- Google SRE, Load Balancing in the Datacenter and Addressing Cascading Failures cover routing policy, fast failures, and overload transfer.
- AWS Builders’ Library, Implementing Health Checks and Application Load Balancer target group attributes document health-check trade-offs, deregistration, and routing failover.
- AWS Network Load Balancer and Application Load Balancer illustrate flow hashing and request-based routing.
- Kubernetes probes and Horizontal Pod Autoscaling describe probe outcomes and the autoscaling feedback calculation.
- Azar et al., Balanced Allocations analyzes the classic equal-work model. Envoy load balancing policies document a production use of sampling and request counts.