Course contents

03. Scaling and Load Balancing Lesson 2 of 8

Horizontal Scaling

Scale out with identical instances behind a load balancer: size the fleet, survive failures with N+1, keep instances stateless, and spot shared bottlenecks.

14 minBeginner10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Horizontal scaling (scaling out) adds identical instances behind one address instead of a bigger machine.
  • Instances needed ≈ peak ÷ (per-instance capacity × target utilisation), plus spare for failures.
  • With N+1 instances, one failure costs capacity for a moment, not availability.
  • Instances must be interchangeable: sessions and other state live in shared stores.
  • Every instance adds load to shared dependencies; scaling out stops helping when one of them saturates.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Horizontal scaling, or scaling out, means adding more machines that run the same software, instead of making one machine bigger. A load balancer (or DNS, or the clients themselves) spreads requests across the instances, so to clients the fleet looks like one service at one address. To handle more traffic you add instances; to save money you remove them.

Why it exists

A single machine has a largest size, a steep price curve near the top and no protection against its own failure. Many ordinary machines together have none of those limits for work that can be split up: capacity grows roughly with the number of instances, one failure takes away only a fraction of it, and instances can be replaced or upgraded one at a time without downtime.

How it works

A single entry point. Clients talk to a load balancer, which keeps a list of healthy instances and forwards each request to one of them. Instances are registered when they start and removed when they fail health checks or are shut down.

Interchangeable instances. Any instance must be able to serve any request. That means no user state kept only in an instance's memory or local disk: sessions go to a shared cache or database (or into signed tokens carried by the client), uploads go to object storage, and scheduled jobs are coordinated so they do not run on every instance at once.

Sizing. If one instance handles C requests per second, and you want to run at a target utilisation u (often 0.6–0.7, to keep queueing delays low), a peak of P needs about P ÷ (C × u) instances, rounded up. Add at least one more so the fleet still fits the peak with one instance down (N+1), and more if you must survive losing a whole availability zone.

Changing the count. Because instances are identical, adding one is a repeatable operation: start it from the same image, let it pass health checks, and the balancer starts sending it traffic. Autoscaling automates this based on CPU, request rate or queue depth.

When to use it

  • Stateless tiers: web servers, API servers, workers pulling from a queue.
  • When you need availability: a service that must survive the loss of an instance or a zone.
  • When load varies a lot over the day or year, so the fleet can grow and shrink with it.
  • When growth will outrun the largest single machine.

When not to

  • Small, steady workloads that one machine handles comfortably: the balancer, deployment tooling and monitoring for a fleet may cost more than they save.
  • Stateful components that cannot simply be copied, such as a relational primary. Those need replication or sharding, which are different and harder techniques.
  • When the bottleneck is a shared dependency: adding app instances then only adds load to it.

Trade-offs

Choice You gain You pay
Scale out instead of up Headroom past one machine, survives instance failures Load balancer, stateless design, more moving parts
Many small instances Small blast radius per failure, fine-grained scaling More per-instance overhead, more connections to shared stores
Few large instances Less overhead, fewer connections Each failure removes a larger share of capacity
Low target utilisation Low latency, room to absorb a failure or spike Paying for idle capacity
Sticky sessions Keep in-memory sessions Uneven load, lost sessions when an instance dies

Alternatives

  • Vertical scaling: one bigger machine. Simpler and often right for databases, but capped and a single point of failure.
  • Caching: serve repeated work from memory so fewer instances are needed.
  • Asynchronous processing: move slow work to a queue and workers, so the request path needs less capacity.
  • Serverless functions: the platform scales instances per request for you, with cold starts and per-invocation limits as the trade-off.

Failure modes

  • No headroom for failure: the fleet is sized exactly for peak, so losing one instance overloads the rest and the failure spreads.
  • Hidden local state: sessions, caches or files on one instance break users when requests land elsewhere or the instance dies.
  • Shared dependency saturates: more instances mean more connections and queries; a database, cache or downstream API hits its limit and every instance waits on it.
  • Connection explosion: each instance opens its own connection pool, so 50 instances × 20 connections can exceed what a database accepts.
  • Thundering herd on scale-out: new instances start with cold caches and JIT, and can be slower than the existing ones for their first minutes.

In production

Build instances from one immutable image and treat them as replaceable. Run them across at least two availability zones with enough spare capacity to lose one. Put a connection pooler in front of the database when the instance count grows. Use autoscaling with sensible minimums, maximums and cool-down periods, and watch per-instance metrics as well as totals so that one bad instance stands out. Deploy with rolling or blue-green releases, draining connections from each instance before it stops.

Common misconceptions

  • "Twice the instances means twice the throughput." Only until a shared dependency, a lock or the network saturates.
  • "It fits, so it is fine." Running at 90% utilisation fits on paper but queues requests and has no room for a failure.
  • "Sticky sessions make an app scalable." They make a stateful app run on several machines, with uneven load and lost sessions on failure.
  • "Scaling out is always cheaper." Many small instances carry more overhead (memory per process, connections, licences) than fewer large ones.

Interview angle

Expect to put a load balancer and several stateless instances in front of every request-serving tier, then justify the number: "each instance does about 75 req/s, peak is 210, at 70% target that is four, five with a spare." Interviewers then push on state (where do sessions live?), failure (what happens when one dies, or a zone?), and the next bottleneck (the database). Naming that bottleneck before they ask, and how you would scale it, is what distinguishes a strong answer.

Model assumptions

The simulation is a simplified model, not a benchmark. Each instance has 6 workers, an 80 ms mean service time (lognormal, cv 0.35) and room for 12 waiting requests (about 75 req/s). The load balancer uses round robin and health checks every 500 ms (2 failures eject, 3 successes restore). The shared database has 3 connections at 12 ms per query (about 250 queries/s) and a 200 ms pool timeout; app workers stay occupied while they wait for it. The session store is drawn for illustration only and is not simulated. Arrivals are random (Poisson); network hops take a fixed 2–25 ms. Utilisation is the fraction of busy workers, not CPU. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One instance behind a load balancer

    Users reach the application through a load balancer, which for now has a single instance behind it. The instance works on six requests at once at about 80 ms each, so it tops out near 75 requests per second.

    At 50 requests per second it is about two-thirds busy and every request succeeds.

    Scene: Users send 50 requests per second through a load balancer to one app instance, which is about two-thirds busy. Nothing fails.

    Key idea: Scaling out starts with a stable entry point that can send traffic to more than one instance.

  2. 2. A peak the instance cannot carry

    One second in, a campaign starts and traffic jumps to 130 requests per second, almost twice what one instance can do.

    The instance saturates, its queue fills and requests are rejected. Scaling up would mean a restart in the middle of the peak. Instead we start more copies of the same application.

    Scene: Traffic rises to 130 requests per second. The single instance is overloaded and some requests are rejected.

    Key idea: A single instance has a hard capacity; past it, requests fail.

  3. 3. Three identical instances

    We start App 2 and App 3, identical copies of App 1, and register them with the load balancer. Clients notice nothing: the address they use did not change.

    The balancer now splits 130 requests per second three ways, about 43 each. Every instance is a bit over half busy and the rejections stop.

    Scene: Three instances share 130 requests per second, about 43 each. Each is a little over half busy and nothing fails.

    Key idea: Horizontal scaling adds identical instances behind one address; capacity grows with the count.

  4. 4. Running hot

    Traffic keeps growing to 210 requests per second. Three instances can do about 225 in total, so on paper they still fit.

    In practice each instance is now around 90% busy, requests queue whenever one is momentarily full, and P95 latency climbs. "It fits" is not the same as "it is healthy".

    Scene: At 210 requests per second all three instances are around 90% busy and latency is noticeably higher.

    Key idea: Size for a target utilisation (often 60–70%), not for 100%.

  5. 5. Do the arithmetic, add a fourth

    Instances needed ≈ peak ÷ (capacity per instance × target utilisation) = 210 ÷ (75 × 0.7) = 4.

    With App 4 in rotation each instance gets about 52 requests per second, roughly 70% busy. P95 drops back down. Because instances are identical, this is a repeatable recipe; autoscaling automates it.

    Scene: Four instances share 210 requests per second, about 70% busy each, and latency is back down.

    Key idea: Instances ≈ peak ÷ (per-instance capacity × target utilisation), rounded up.

  6. 6. An instance dies, the service does not

    One second in, App 2 crashes. Requests the balancer still sends there fail until its health checks notice, about a second later, and take App 2 out of rotation.

    After that the three survivors carry 210 requests per second, around 90% busy each, and errors stop. A single large server would have been a full outage. This is the availability benefit of scaling out, as long as you keep that spare instance (N+1).

    Scene: App 2 crashes. A few requests fail until health checks remove it, then the three remaining instances serve all traffic without errors.

    Key idea: With N+1 instances, losing one costs capacity, not availability.

  7. 7. Any instance must handle any request

    Round robin just sent consecutive requests from the same user to different instances. That only works if instances keep no local state: if App 2 had kept sessions or shopping carts in its memory, those users just lost them.

    So state moves out of the instances into a shared store (a cache or database) that all of them use. Sticky sessions are the workaround when you cannot, at the price of uneven load and lost sessions on failure.

    Scene: App 2 is back. All four instances keep user sessions in a shared session store instead of their own memory, so any instance can serve any request.

    Key idea: Stateless instances are interchangeable, which is what makes scaling out and failover work.

  8. 8. Every instance shares one database

    The instances also read their data from one shared database. It has three connections and needs about 12 ms per query, so it answers roughly 250 queries per second.

    At 210 requests per second that is enough. Each request now holds its app worker a little longer (it waits for the query), but four instances still have room.

    Scene: All four instances read from one database with three connections. At 210 requests per second everything succeeds.

    Key idea: Scaling out the app tier multiplies the load on everything the instances share.

  9. 9. More instances, same ceiling

    Traffic grows to 300 requests per second and we do what worked before: start App 5 and App 6.

    This time it does not help. The database can answer about 250 queries per second however many instances ask, so throughput stalls below 300 and requests fail. The app workers look fully busy too, but they are only waiting for database connections. The app tier scales out; the shared database is now the limit. Caching, read replicas and sharding (later modules) are how you scale that part.

    Scene: Six instances receive 300 requests per second, but the shared database is saturated. Throughput stays below 300 and some requests fail.

    Key idea: Scaling out a stateless tier stops helping once a shared dependency saturates.

  10. 10. What scaling out asks of you

    Scaling out gives you almost unlimited headroom for stateless work and survives instance failures. In return: a load balancer, stateless instances, a fleet sized with headroom, and deployments and monitoring for many machines instead of one.

    Watch the shared parts. Every instance you add multiplies connections and queries to databases, caches and downstream services; one of them is always the next bottleneck.

    Scene: Six instances behind the load balancer share one saturated database.

    Key idea: Scale out stateless tiers freely; plan separately for every shared dependency.