A popular app gets slow. The first reaction is often *we need microservices*, and that is usually the wrong first step. This lesson explains the real options for handling more traffic, in the order that you should try them, and shows the central trick of scaling, a load balancer that spreads requests over several copies, in a small running example.
Scale up, scale out
Scaling up means a bigger machine, with more CPU and memory. It is the easiest change, and it works until the machine is the largest available or too expensive. Scaling out means more machines, or more copies, sharing the load. It has no hard ceiling, but your app must be ready for it. Before either, measure: many slow apps are really slow queries, a missing index or no caching, and fixing those is much cheaper than new servers.
Stateless servers
To scale out, every copy of the app must be interchangeable. A request can go to any copy and get the same result. That means no important data in the memory of one copy: sessions, caches, uploaded files and counters must live in a shared place such as the database, Redis or cloud storage. If a copy can be killed and replaced at any moment without losing anything, your design is stateless, and scaling and deployment both become easy.
The load balancer
A load balancer sits in front of the copies. Clients talk to it, and it forwards each request to one copy. The simplest rule is round robin: the first request goes to copy 1, the next to copy 2, then 3, and back to 1. A good balancer also runs health checks: every few seconds it asks each copy GET /health. A copy that does not answer with 200 is taken out of rotation until it recovers, so users never see it. nginx, HAProxy and cloud balancers all do this. The example is a miniature version in about thirty lines.
// Scaling out in miniature: several copies of a small service behind a round-robin balancer that
// skips copies that fail their health check. nginx and cloud load balancers do the same job.
import http from 'node:http';
export function startService(name) {
let healthy = true;
const server = http.createServer((req, res) => {
if (req.url === '/health') { res.statusCode = healthy ? 200 : 503; return res.end(); }
res.end(`answered by ${name}`);
});
return new Promise((resolve) => server.listen(0, () => resolve({ name, server, port: server.address().port, setHealthy: (v) => { healthy = v; } })));
}
export function createBalancer(targets) {
let index = 0;
const isHealthy = (target) => new Promise((resolve) => {
http.get({ port: target.port, path: '/health' }, (res) => { res.resume(); resolve(res.statusCode === 200); }).on('error', () => resolve(false));
});
return {
async forward() {
for (let tries = 0; tries < targets.length; tries++) {
const target = targets[index++ % targets.length];
if (!(await isHealthy(target))) continue;
return new Promise((resolve, reject) => {
http.get({ port: target.port, path: '/' }, (res) => { let body = ''; res.on('data', (c) => (body += c)); res.on('end', () => resolve(body)); }).on('error', reject);
});
}
throw new Error('No healthy service');
},
};
}
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Save the code as
scale.js. The test uses only Node.
import test from 'node:test';
import assert from 'node:assert/strict';
import { startService, createBalancer } from './ms39-scale.js';
test('round robin, and a sick copy is skipped', async () => {
const [a, b, c] = await Promise.all([startService('A'), startService('B'), startService('C')]);
const balancer = createBalancer([a, b, c]);
const first = [await balancer.forward(), await balancer.forward(), await balancer.forward()];
assert.deepEqual(first, ['answered by A', 'answered by B', 'answered by C']);
b.setHealthy(false);
const next = new Set([await balancer.forward(), await balancer.forward(), await balancer.forward(), await balancer.forward()]);
assert.ok(!next.has('answered by B'));
assert.equal(next.size, 2);
for (const s of [a, b, c]) s.server.close();
});
ok 1 - round robin, and a sick copy is skipped
The test starts three small services and sends six requests, and sees that the answers rotate among the three. Then it makes one service unhealthy and sends more requests, and shows that the sick copy never answers. Finally, if every copy is unhealthy, the balancer throws an error, which a real system turns into a 503.
Microservices: when and why not
A microservice architecture splits one large app into several small services, each with its own code, its own database and its own deployment, talking over HTTP or a message queue. The benefits are real: teams can work and deploy independently, and each part can scale on its own. The costs are real too: network calls can fail, data is spread over several databases, debugging crosses many logs, and you need tooling for deployment and monitoring. Many successful companies run a well-organised modular monolith, one deployable app with clear internal boundaries, until size or team structure makes splitting worth the pain. Project 10 in this course builds a small two-service example so that you can feel both the benefit and the cost.
- Measure first: slow queries, missing indexes and no caching are the common causes.
- Make the app stateless, so any copy can serve any request.
- Add a health route that checks real dependencies, such as the database.
- Run at least two copies behind a load balancer, and deploy one at a time.
- Split into services only when a clear need, such as team size or very different scaling, pays for the extra complexity.
Your task
- Change the balancer to choose the copy with the fewest active requests.
- Make
/healthreturn 503 when the database ping fails. - Write down which parts of your own project are not stateless yet.
How to check it worked
- The answers rotate among the copies.
- A sick copy receives no traffic.
- You can name two costs of microservices.