Full answer
Scaling patterns, in the order they usually pay off:
- Profile first. Remove blocking code and slow queries before adding machines.
- Vertical use of one machine: cluster mode, PM2 or several containers, one process per CPU core.
- Horizontal scaling: stateless processes behind a load balancer. Sessions, caches and uploads live in Redis, a database or object storage. Sticky sessions are a fallback for WebSockets, not a goal.
- Caching: HTTP caching and a CDN for public content, in-memory or Redis caches for hot data, with expiry and stampede protection.
- Queues and background workers: accept the request quickly, put slow work (email, reports, image processing) on a queue, and process it with separate worker processes that scale on their own. Make jobs idempotent.
- Database scaling: indexes, connection pooling with a limit, read replicas, partitioning. The database often fails before Node does.
- Autoscaling on a good signal: CPU, event loop utilization, queue length or latency, with warm-up time in mind.
Protecting a service at the limit (admission control):
- Without it, a spike makes the queue of requests grow. Every request waits, timeouts fire, clients retry, and the load grows further (a retry storm). The service collapses for everyone.
- Load shedding rejects the excess quickly. Options: a limit on concurrent in-flight requests per process, rejecting when event loop delay or utilization is above a threshold, or when a queue is longer than N.
- Reply 503 Service Unavailable with Retry-After. Clients with backoff then spread their retries.
- Protect important paths: health checks and critical routes bypass shedding, and low priority work is shed first.
- Add timeouts everywhere, and propagate deadlines, so work that nobody waits for is dropped.
- Test with load tests above the expected peak, and watch the behaviour at 2x capacity.
The aim is graceful degradation: serve most users well, and refuse the rest clearly.
javascript
const http = require('node:http');
// Admission control: allow at most MAX_IN_FLIGHT requests at once, reject the rest quickly.
function withLoadShedding(handler, { maxInFlight, bypass = [] }) {
let inFlight = 0;
return (req, res) => {
if (bypass.includes(req.url)) return handler(req, res); // health checks always pass
if (inFlight >= maxInFlight) {
res.writeHead(503, { 'Retry-After': '1', 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'server busy, retry later' }));
}
inFlight++;
res.on('close', () => { inFlight--; });
handler(req, res);
};
}
const slowHandler = (req, res) => {
if (req.url === '/health') return res.end('ok');
setTimeout(() => res.end('report ready'), 100); // a slow downstream call
};
const server = http.createServer(withLoadShedding(slowHandler, { maxInFlight: 2, bypass: ['/health'] }));
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// Five clients arrive at the same moment.
const burst = await Promise.all(Array.from({ length: 5 }, async () => {
const response = await fetch(base + '/report', { headers: { Connection: 'close' } });
await response.text();
return { status: response.status, retryAfter: response.headers.get('retry-after') };
}));
console.log('served:', burst.filter((r) => r.status === 200).length);
console.log('shed with 503:', burst.filter((r) => r.status === 503).length, '| Retry-After header:', burst.find((r) => r.status === 503).retryAfter);
// The health check still works while the server is busy.
const busy = Array.from({ length: 2 }, () => fetch(base + '/report', { headers: { Connection: 'close' } }).then((r) => r.text()));
await new Promise((resolve) => setTimeout(resolve, 20));
const health = await fetch(base + '/health', { headers: { Connection: 'close' } });
console.log('health check while busy:', health.status);
await Promise.all(busy);
// After the burst, capacity is free again.
const again = await fetch(base + '/report', { headers: { Connection: 'close' } });
console.log('after the burst:', again.status);
server.close();
});Two requests fit into the limit, three are refused at once, and the health check and the later request still work. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): served: 2 shed with 503: 3 | Retry-After header: 1 health check while busy: 200 after the burst: 200
Key points
- Remove bottlenecks before adding machines.
- Stateless copies, external state, queues and caches enable horizontal scaling.
- The database is often the real limit.
- Shed load early with 503 and Retry-After.
- Protect health checks and critical routes.
Common mistakes
- Adding servers before finding the real bottleneck.
- Letting queues grow without a limit.
- Retrying immediately without backoff and jitter.
- Scaling Node instances while the database connection pool runs out.
Follow-ups
- How would you choose the in-flight limit?
- How do you shed load based on event loop delay?
- How does a queue change the scaling picture?
Tips
- Put the patterns in order of cost and benefit.
- Explain the retry storm.
- Say that 503 with Retry-After is a kind answer to a client.