Node.js traps · Chapter 1 of 16
A sync call that blocks the event loop
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The event loop
- 3 tasks
- Node.js
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
The lesson
By the end of this case
You can tell a blocked event loop from its symptoms, show it on purpose with a health check that has to wait, move the work onto Node's thread pool, and guard it with a test that counts turns of the event loop.
The ticket
PAR-711: The site stops answering at 9:55 every morning. Assigned to you by Nikhil. Priority: high. Since: the security release on the 3rd.
Asha, in the operations channel at 9:58 am: "Same as yesterday. At five to ten the box office and gate staff at all twelve venues sign in for the morning shows, and for a few seconds nobody can book. Two customers in the Rangdeep queue paid and saw a spinning wheel. Then the site comes back on its own."
The load balancer's log and the API's own lines, from this morning:
09:55:01.208 lb GET /healthz api-1: no answer in 2000 ms (1 of 3)
09:55:02.415 api login: Meenal Joshi signed in
09:55:02.731 api login: Ravi Shinde signed in
09:55:03.210 lb GET /healthz api-1: no answer in 2000 ms (2 of 3)
09:55:05.212 lb api-1 marked down after 3 failed checks, restarting
Nikhil: "The security review asked us to raise password hashing to 600,000 iterations, and we shipped it on the 3rd. One login is about 300 ms on our API servers. The login function is async, so I assumed it could not hold anyone up. Look at what the API is doing between those two login lines. Reproduce it, fix it, and make sure it never comes back. You are in staff-login.js."
One thread for every request
Node runs your JavaScript on one thread, the event loop. It takes one callback, runs it to the end, then picks the next: a request, a timer, a payment's answer. That is why Node handles thousands of connections cheaply, and it has one rule: no callback may take long. While one runs, nothing else does, not even the health check.
The surprise is that async does not change this. An async function runs synchronously until its first await. Here is a ticket checker with heavy work and no await in it:
async function checkTicket(code) {
console.log('checking', code);
for (let i = 0; i < 300_000_000; i++); // heavy, synchronous work
console.log('checked', code);
return true;
}
setImmediate(() => console.log('health check answered'));
const answer = checkTicket('T0023-E7');
console.log('checkTicket returned', answer);
await answer;
checking T0023-E7
checked T0023-E7
checkTicket returned Promise { true }
health check answered
The function returned a promise that was already settled: all the work happened inside the call. The health check, due on the very next turn, waited until the end.
Where the slow work can go
Some of Node's built-ins do their heavy work off the event loop, on libuv's thread pool (four threads by default, UV_THREADPOOL_SIZE): hashing, compression, file reads. Each comes in two forms. The one whose name ends in Sync runs on the event loop and returns the answer. The other takes a callback (or, with promisify from node:util, returns a promise), hands the work to the pool and returns at once.
You can see the difference by counting turns of the event loop while the work runs: a setImmediate callback that counts and asks to run again. Here with compression, on a 20 MB poster file:
import { gzip, gzipSync } from 'node:zlib';
import { promisify } from 'node:util';
const gzipAsync = promisify(gzip);
const poster = Buffer.alloc(20_000_000, 'Pune 52 ');
// Counts turns of the event loop until work() settles.
async function turnsDuring(work) {
let turns = 0;
let done = false;
const tick = () => {
turns += 1;
if (!done) setImmediate(tick);
};
setImmediate(tick);
await work();
done = true;
return turns;
}
console.log('gzipSync:', await turnsDuring(async () => gzipSync(poster)));
console.log('gzip:', await turnsDuring(() => gzipAsync(poster)));
gzipSync: 0
gzip: 30965
Zero turns: nothing else could run. Thirty thousand turns: the loop was free the whole time (that number changes from run to run; zero never does). For CPU work of your own there is no ready-made async version; you split it into chunks or move it to a worker thread.
Making it happen on purpose
A stall is easy to replay without any clock: start a health check that asks for the next turn (setImmediate), start the logins at the same moment, and write down who finished first. Order is the same every run, on any machine, fast or slow.
A test that would have caught it
Order catches the original code, but a fix that waits one turn and then blocks anyway would put the health check first and still freeze the site. So the guard counts turns while three logins run, as above, and expects the loop to keep turning; it also expects every login to sign in, so a fix that stops checking passwords fails.
Your turn
Three tasks, one file each. In repro.js, hold up the health check on purpose and run it with node repro.js in the case's folder. In staff-login.js, move the hashing off the event loop, keeping today's hashes valid. In staff-login.test.js, write the guard: the check runs it beside the original code, the fix and a wrong fix that waits a turn first. Then answer Nikhil's interview question at the bottom of the case, in your own words.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
repro.js: hold up the health check on purpose
Write reproduce() in repro.js. Make one staff record with hashPassword from staff-login.js (any email, name and password, with 100,000 iterations so it runs fast), spread it into { email, name, ...record }, and make a login with createLogin([record]). Then, before waiting for anything, start a health check (a Promise around setImmediate whose callback pushes 'health' onto a list) and three logins with the right password, each pushing 'login' onto the same list when it resolves. Wait for all four and resolve to the list.
The check runs your reproduce() twice: beside the original staff-login.js it must resolve to ['login', 'login', 'login', 'health'] (the health check waited for every login), and beside a fixed staff-login.js to ['health', 'login', 'login', 'login']. No real waiting and no setTimeout: reproduce() must finish within 2 seconds.
- Task 2
staff-login.js: logins that let every other request through
Fix hashPassword(password, salt?, iterations?) and createLogin(staff) in staff-login.js, so the password hashing runs off the event loop and the API keeps answering while logins run. login(email, password) must resolve to { ok: true, name } for the right password, and log login: <name> signed in; to { ok: false } for a wrong password or an email nobody has. hashPassword must resolve to { salt, iterations, hash }.
Keep the exports, ITERATIONS (600,000), the log line and the hash itself (PBKDF2 with SHA-256, 32 bytes, as hex, with each record's own salt and iterations), so the hashes stored today still sign in. The check uses its own staff records, made with node:crypto, and counts how many turns of the event loop go by while three logins with 100,000 iterations run at once, and while three hashPassword calls run: at least 5 each time.
- Task 3
staff-login.test.js: a test that would have caught it
Write a vitest test file, staff-login.test.js, that would have caught the stall before the iterations went up. The check runs your file three times: beside the original staff-login.js, where at least one test must fail; beside the fixed staff-login.js, where every test must pass; and beside a wrong fix that waits one turn of the event loop and then hashes with the blocking call anyway, where at least one test must fail.
So make a staff record with 100,000 iterations, start a pinger (a setImmediate callback that counts and schedules itself again until the logins are done), run three logins at once, and check both sides: the pinger ran at least 5 times while they ran, and every login resolved to { ok: true, name }. Each test must finish within 3 seconds.
What you will learn
- repro.js: hold up the health check on purpose
- staff-login.js: logins that let every other request through
- staff-login.test.js: a test that would have caught it
More in The event loop
Build "A sync call that blocks the event loop" yourself
Parda's booking backend has run on Node for a year, and Nikhil keeps handing you incidents where Node did exactly what the team told it. Each is a runtime trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.