Chasing 1 million requests per second: the Node.js groundwork
I have been geeking out on Cododev's video Let's Handle 1 Million Requests per Second, It's Scarier Than You Think!. The goal is in the title: serve more than a million HTTP requests every second, using Node.js, C++, PostgreSQL and Redis on AWS.
I paused at the point where it moves to AWS, about 34 minutes in. Everything before that happens on one machine with plain Node.js, and it was enough to change how I think about a Node server. These are my notes on that part. The code is in the video's node-1m-rps repository.
One thread means one core
The video starts with CPU utilization before any server code, and the demo is one line:
while (true) {}
Run it and one CPU core goes to 100% while the others stay idle. On an 8-core machine the system as a whole shows about 12.5% usage, which looks like plenty of headroom. There is none. That single thread is completely busy, and it cannot borrow the other seven cores.
This is the situation of every Node.js server. Your JavaScript runs on one thread, so one Node process can use at most one core for it, however large the machine is.
The second script shows the way out. It starts twelve worker threads that each run the same loop, and now the load spreads across the cores:
import { Worker, isMainThread } from "worker_threads";
import { fileURLToPath } from "url";
if (isMainThread) {
for (let i = 0; i < 12; i++) {
new Worker(fileURLToPath(import.meta.url));
}
} else {
while (true) {}
}
To use the whole machine, you need more than one thread of JavaScript.
Three frameworks, one set of routes
The repository has the same server written three times, in Cpeak, Fastify and Express, each on its own port. I focused on Cpeak and Fastify.
Cpeak is Cododev's own framework. It is small, has zero dependencies, and its API is close to Express. Its README says it aims for roughly Fastify's performance.
import cpeak, { parseJSON } from "cpeak";
const app = cpeak();
app.beforeEach(parseJSON({ limit: 1024 * 1024 }));
app.route("get", "/simple", (req, res) => {
res.json({ message: "hi" });
});
app.listen(3000, () => {
console.log("Cpeak server running at http://localhost:3000");
});
Fastify is the established fast option. It parses JSON bodies without extra middleware, and you hand send an object and it serializes it.
import Fastify from "fastify";
const app = Fastify({ bodyLimit: 1024 * 1024 });
app.get("/simple", (req, res) => {
res.send({ message: "hi" });
});
app.listen({ port: 3002, host: "0.0.0.0" }, () => {
console.log("Fastify server running at http://localhost:3002");
});
Side by side, the differences are small:
| Cpeak | Fastify | |
|---|---|---|
| Define a route | app.route("get", path, handler) | app.get(path, handler) |
| JSON bodies | parseJSON middleware via beforeEach | Built in, with bodyLimit |
| Send JSON | res.json(data) | res.send(data) |
| Catch errors | app.handleErr(fn) | app.setErrorHandler(fn) |
Two routes matter in this part of the video:
GET /simplereturns{ message: "hi" }. It does almost no work, so it measures the overhead of the framework itself.PATCH /update-something/:id/:nameis closer to a real endpoint. It validates the URL parameters, reads ten fields from a JSON body and responds with a list of 100 objects, which is a few kilobytes of JSON to build and serialize.
Testing both is the useful habit here. A framework can look great on the first route and ordinary on the second, because on the second your own code is doing most of the work.
Measuring with autocannon
autocannon is a load-testing tool written in Node. This is the command from the repository:
autocannon -m GET \
--connections 20 --duration 20 --pipelining 2 --workers 6 \
"http://localhost:3000/simple"
| Flag | Meaning |
|---|---|
--connections 20 | Keep 20 connections open at the same time |
--duration 20 | Run for 20 seconds |
--pipelining 2 | Send 2 requests on each connection before waiting for a response |
--workers 6 | Use 6 threads to generate the load |
The --workers flag is the first lesson applied to the tester. autocannon is a Node program too, so with one thread it can run out of CPU before the server does, and then you are measuring the tool instead of the server.
In the results I look at three things: average requests per second, latency at the 99th percentile, and the count of errors and non-2xx responses. A high request rate means little if the slowest 1% of requests take seconds or some of them fail.
One caveat when the tester and the server share a machine: they compete for the same cores, so the numbers describe that one computer under that one setup. They are good for comparing two versions of a server and bad for quoting as absolutes.
Using every core
A single Node process stops at one core. The fix is to run one process per core and share the port between them, which is what Node's cluster module does. The repository does it through PM2. This is the relevant part of its config:
module.exports = {
apps: [
{
name: process.env.F || "cpeak",
script: `./${process.env.F || "cpeak"}.js`,
instances: "max",
exec_mode: "cluster",
},
],
};
instances: "max" starts one copy of the server for each CPU core, and exec_mode: "cluster" makes them all accept connections on the same port. The F environment variable picks the framework:
F=fastify pm2 start ecosystem.config.cjs
That syntax is for bash. In PowerShell, set the variable first with $env:F = "fastify" and then run pm2 start ecosystem.config.cjs.
PM2 is a convenience on top of something Node already has. The same idea without it is about a dozen lines:
import cluster from "node:cluster";
import { availableParallelism } from "node:os";
if (cluster.isPrimary) {
for (let i = 0; i < availableParallelism(); i++) cluster.fork();
// Replace a worker if it dies, so the server keeps its capacity.
cluster.on("exit", () => cluster.fork());
} else {
await import("./fastify.js");
}
The primary process starts the workers and runs none of the route handlers itself. Each worker is a full Node process with its own event loop and its own memory.
Two things are worth remembering about clustering:
- Workers share nothing. A counter, cache or session kept in a variable exists once per worker, and a user's next request may land on a different one. Shared state has to live outside the process, which I expect is where Redis comes in later in the video.
- Throughput does not multiply neatly by the core count. The load tester needs CPU too, and the operating system decides how connections are spread across workers. My own numbers below show how far from neat it can be.
What I measured
I ran the /simple route on my laptop: 4 cores and 8 threads (Intel i7-1185G7), 16 GB of RAM, Windows 11 and Node 24, running on battery with my usual apps open. autocannon ran on the same machine with the settings above. Each figure is the range across two 20-second runs.
| Single process | Clustered, 8 workers | |
|---|---|---|
| Cpeak | 13,600 to 16,100 req/s | 24,700 to 27,700 req/s |
| Fastify | 12,400 to 15,500 req/s | 25,800 to 27,800 req/s |
The 99th percentile latency stayed between 8 and 16 ms in every run, with no errors.
Two things stand out. Cpeak and Fastify are too close to call here: each won one of the two single-process runs, so the gap between runs is bigger than the gap between frameworks. And eight workers gave a little under twice the throughput of one, nowhere near eight times. The tester's six threads were fighting the server for the same four cores, so past a point there was no spare CPU to give. Putting the tester on its own machine is the obvious next step.
My antivirus was the first bottleneck
My first runs were far worse: both frameworks sat between 700 and 900 requests per second, whatever settings I gave autocannon. The server process was using about a quarter of one core, so Node was mostly waiting.
The cause was my antivirus. Its web protection was inspecting every HTTP request, including the ones going to localhost. Turning it off for the test raised the same single-process run from under 1,000 requests per second to more than 12,000, and the server process finally used its whole core.
If your local numbers look absurdly low and the server's CPU is not busy, look at what sits between the tester and the server before blaming the framework.
What I am taking away
- A Node.js process uses one core for JavaScript. Low overall CPU usage can hide a thread that is already at its limit.
- Fastify and Cpeak are close enough in API and in speed that the choice should come from measurements on realistic routes.
- A load test is only as good as the tester and the machine. Give the tester enough threads, read latency and errors alongside requests per second, and check that nothing else is in the path.
- Clustering is how one machine uses all of its cores, and it forces shared state out of process memory.
Next in the video are AWS, a database on disk, Redis, and C++. The following note covers the move to AWS and why its cost stopped me from following along.