DevPath · Learn to code ESPTEN

Observability and performance

Scaling: horizontal, load balancers and stateless

When one machine is not enough

There comes a point where your service receives more traffic than a single instance can handle. There are two ways to grow.

Vertical vs. horizontal

In modern practice the horizontal approach is preferred, and it is the foundation of the cloud.

The load balancer

A load balancer is the piece that sits in front of your instances and distributes requests among them (round-robin, least connections, etc.). The client talks to a single address; the balancer decides which instance responds. It also queries the health checks and stops sending traffic to instances that do not respond.

The key to horizontal: being stateless

To be able to freely distribute requests across interchangeable instances, each instance must be stateless: it does not keep in its local memory anything the next request needs. Why? Because the balancer can send a user's request 1 to instance A and request 2 to B. If the session lives in A's memory, B does not know it and the user "loses" their session.

The solution: move the shared state outside, to a store that all of them share — the database, Redis for sessions/cache, a file service. The instances become disposable: you can create, destroy or replace any of them without losing anything. That is exactly what enables what comes next.

Autoscaling and load testing

Mental summary: stateless lets you scale horizontally, the balancer spreads the load and autoscaling adjusts the number of instances to demand. And you measure it all with the metrics from the first pillar.

Examples

Round-robin balancing: distribute by turns across instances

function createBalancer(instances) {
  let i = 0;
  return function next() {
    const chosen = instances[i % instances.length];
    i++;
    return chosen;
  };
}

const lb = createBalancer(["A", "B", "C"]);
console.log([lb(), lb(), lb(), lb()].join(" ")); // A B C A
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Performance: caching, lazy loading and the DBView the module →