Courses / Node.js: From First Script to Production / Chapter 24
Module 9 · Tests, types and operations · Chapter 24 of 27
Scaling and Deploying: Statelessness, Graceful Shutdown and Containers
Builds on Building a Basic Web Server with node:http, npm and Package Management: Dependencies, Versions and Lockfiles, Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging, Production APIs: Validation, Error Shapes, Idempotency and Fastify, Caching and Background Jobs in Node Services, TypeScript for Node: Type Stripping, tsconfig and Typed Handlers and Observability: Structured Logs, Metrics and Traces. Next up: Case Study: A Food-Delivery Orders Service, End to End.
Part 1 · One process, one core, and no memory to lose
Why you run more than one instance
A Node process runs your JavaScript on one thread, so one process uses about one core for your code. When a lakh of people open a college fest ticket sale together, one process is too small and one failure away from an outage.
The answer is to run several instances, each a copy of the same program, behind a load balancer, which spreads incoming requests across them.
You can start several processes on one machine with the cluster module from the advanced topics chapter, which lets workers share one port. You can run several containers, or several machines. The os.availableParallelism() function tells you how many cores the machine offers, and a common starting point is one worker per core. Make the count configurable, so that an operator can lower it when other programs share the machine. The configuration code later in this lesson reads a WEB_CONCURRENCY variable and never goes above the core count.