16 min read
Node.js event loop explained: what blocks it
In one sentence: Node.js runs your code on a single thread: it handles one thing, finishes it and takes the next one from a queue. Waiting for the network or the disk doesn't tie up that thread, but a long calculation does, and while it lasts, every other request waits.
What you will learn
- Explain what the event loop does and why a single thread can serve thousands of clients.
- Tell what blocks the server (calculating) from what doesn't (waiting for the network or the disk).
- Predict in what order code, promises and timers run.
- Measure with two curl commands at once how a blocking route makes the others wait, and fix it.
Before you start, read: 08-errors-and-logs.md
The problem
Section titled “The problem”Imagine Luis asks for a new route in the shop’s API: a report with the year’s sales. Calculating it takes a second and a half, and Luis is fine with that, because only he uses it.
But while Luis asks for it, Ana reloads the shop on her phone, and the product list, which used to take 3 milliseconds, takes more than a second. The same happens to everyone who is shopping. The server hasn’t crashed: it’s busy with the report and can’t do anything else.
In this lesson you’ll cause that jam in your API, measure it with curl and clear it. To understand it, you need to know how Node.js splits up its time.
The analogy
Section titled “The analogy”The analogy
Think of a restaurant with a single waiter. He takes the order at table 1, carries the slip to the kitchen and, while they cook, goes to table 2. He doesn’t stand there waiting for the dish: when the kitchen rings the bell, he picks it up and serves it. That way he alone serves twenty tables, because almost all the time is spent waiting for the kitchen, not working himself.
Now table 3 asks him to peel six pounds of potatoes himself. While he peels, he takes no orders, serves no dishes and collects no bills: every table waits because of one.
The waiter is Node.js’s thread, the kitchen is the operating system, and peeling potatoes is a long calculation.
Where the analogy breaks down
- A waiter can leave the potatoes half peeled. Node never interrupts a piece of code: it runs it to the end.
- The waiter serves whoever he likes. The event loop follows a fixed order: promises before timers, as you’ll see.
- A restaurant hires another waiter and that’s it. Node can also use more threads, but you have to ask for them: your JavaScript, by default, runs on one.
How it really works
Section titled “How it really works”A single thread for your code
Section titled “A single thread for your code”In Phase 1 you saw that a running program is a ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition. Inside a process, one or more ThreadA line of work inside a process, which the processor runs instruction by instruction. A process can have several threads working at once, but the JavaScript code of a Node.js server runs on just one.Go to definition work: lines of work that the processor runs instruction by instruction. With four threads, a process can do four things at once, each on one core of the processor (today’s have several).
Your server is a process, and all your JavaScript runs on a single thread: the routes, the MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition, the validation and the logs. Many servers in other languages, like the classic Java or PHP ones, handle each request on its own thread or process. Node doesn’t: one thread serves everyone, one thing at a time.
How can one thread cope with thousands of clients? With the Event loopThe loop Node.js uses to handle many things at once with a single thread. It runs a piece of code to the end, checks what’s ready in its queue (a request that has arrived, a timer that has run out) and moves on to the next one. If a piece takes a long time, everything else waits.Go to definition, which always repeats the same thing:
- The queuerequests that have arrived, timers that are due, data read from the disk
the event loop takes the first thing
- Your coderuns to the end, without interruptions
when it finishes
- Back to the queueand so on forever, while the server is running
Each request isn’t a single piece of code. If your route does await (lesson 2), it splits in two: what comes before the await is one piece, and what comes after is another that will enter the queue when its PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition is fulfilled. Between the two, the thread is free for other things.
Waiting doesn’t block
Section titled “Waiting doesn’t block”When your code asks the network, the disk or, from Phase 5, a database for something, Node doesn’t sit there watching. It hands the job to a library written in C that it carries inside, libuv, and carries on with the queue. libuv works in two ways:
- The network: it asks the operating system to let it know when data arrives. Waiting on a thousand connections ties up no thread.
- Everything else (reading files, compressing, some cryptography operations): it does it in a small team of four helper threads, the thread pool. When they finish, they leave the result in the queue.
A web server spends almost all its time waiting: for the client, for the database, for another API. That’s why one thread is enough: while it waits, it serves others, like the waiter who doesn’t stay in the kitchen.
Calculating does block
Section titled “Calculating does block”Calculating is something else: it’s work for the thread itself, and nobody else can do it for it. While it calculates, it takes nothing from the queue. That’s called Blocking codeCode that holds the thread until it finishes, without letting anything else run in the meantime. In a Node.js server, a blocking route makes every other request wait, even the ones that have nothing to do with it.Go to definition.
Examples from a real server: checking a password, which is slow to calculate on purpose (Phase 6), resizing an image, going through a list of millions of items, or converting JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition text of many megabytes with JSON.parse.
To see it, this lesson’s API has two routes with the same expensive calculation. They need two imports at the top of src/app.ts:
import { pbkdf2, pbkdf2Sync } from 'node:crypto';import { promisify } from 'node:util';- From
node:crypto, Node’s cryptography ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition, comepbkdf2Syncandpbkdf2: two versions of the same function. - From
node:utilcomespromisify, which turns an old-style function, one that lets you know it has finished by calling another function, into one that returns a promise, the kindawaitunderstands.
And the two routes, which go after app.get('/orders/:id', …):
// A calculation that's expensive on purpose: what a server does to check a password (Phase 6).const ROUNDS = 3_000_000;const pbkdf2Async = promisify(pbkdf2);
// Blocks: while it calculates, the event loop can't handle any other request.app.get('/slow', (c) => { const start = performance.now(); pbkdf2Sync('password', 'salt', ROUNDS, 64, 'sha512'); return c.json({ ms: Math.round(performance.now() - start) });});
// Doesn't block: the calculation runs on another thread, and the event loop carries on meanwhile.app.get('/slow-async', async (c) => { const start = performance.now(); await pbkdf2Async('password', 'salt', ROUNDS, 64, 'sha512'); return c.json({ ms: Math.round(performance.now() - start) });});Piece by piece:
pbkdf2turns a password into a HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, repeating the operation many times so that guessing passwords is slow. It takes the password, a “salt” (Phase 6), the rounds, the bytes of the result and the algorithm.ROUNDS = 3_000_000: three million rounds. The_only separate the thousands to make it easier to read; JavaScript ignores them.promisify(pbkdf2)createspbkdf2Async, the version ofpbkdf2that returns a promise.performance.now()gives the milliseconds the program has been running: the one at the end minus the one at the start is how long it took, andMath.roundrounds it./slowcallspbkdf2Sync. Sync is short for “synchronous”: it returns nothing until it’s done, and it does the work on your thread./slow-asyncdoesawait pbkdf2Async(…). The calculation is the same, but one of libuv’s helper threads does it, and yours stays free meanwhile.
Both answer with how long the calculation took, {"ms": …}. What changes is what happens to everyone else meanwhile:
- Node (one thread)pbkdf2Sync: calculates
without letting go of the thread - curl /products · Node (one thread)the request waits in the queue
- Node (one thread) → curl /slow200 {"ms":663}
- Node (one thread) → curl /products200, half a second late
- Node (one thread) → curl /products200, in milliseconds
- Helper thread (libuv) → Node (one thread)done: the result, to the queue
- Node (one thread) → curl /slow-async200 {"ms":658}
The order: your code, promises and timers
Section titled “The order: your code, promises and timers”There isn’t just one queue: there are several, with priorities. examples/order.ts shows it in four lines. Before running it, guess in what order they come out:
// In what order are these lines written? Run it with: node examples/order.tsconsole.log('1. The program starts');
setTimeout(() => console.log('4. The timer, even though it is 0 ms'), 0);
Promise.resolve().then(() => console.log('3. The promise that is already resolved'));
console.log('2. The code ends, from top to bottom');console.logwrites a line in the terminal.setTimeout(function, 0)schedules a timer: “run this function in 0 milliseconds.”Promise.resolve().then(function)creates a promise that is already fulfilled and tells it what to do with it.
The order of things
node examples/order.tsWhat you will see:
1. The program starts2. The code ends, from top to bottom3. The promise that is already resolved4. The timer, even though it is 0 msRun it from the project folder. If you get Cannot find module, check that you’re in shop-api (with pwd) and that the file is in examples/.
Neither the timer nor the promise runs where it’s written. The rules:
- First, the current piece of code, all of it, from top to bottom: messages 1 and 2.
- Then, every promise that is already fulfilled. This queue is emptied every time a piece of code finishes, before looking at anything else: number 3.
- After that, everything else, in turns of the loop: timers that are due, requests that have arrived, files that have been read. Number 4.
So setTimeout(…, 0) doesn’t mean “now,” but “as soon as the loop gets to the timers.” And if a piece of code takes a second, the 0 ms timer takes a second.
How not to block the server
Section titled “How not to block the server”If a route has to do an expensive calculation, there are four ways out, from the simplest to the most complete:
| What to do | When | How |
|---|---|---|
| Use the asynchronous version | If Node has one: cryptography, files, compression | pbkdf2 instead of pbkdf2Sync, readFile instead of readFileSync |
| Split the work into pieces | A very long loop in your own code | Process a thousand items, give the turn back to the loop (setImmediate) and carry on |
| Move it to another thread | A heavy calculation of yours: an image, a report | worker_threads, a Node module that runs your JavaScript on another thread |
| Move it to another service | Long jobs that don’t have to answer right away | A job queue and another process that does them (Phase 9) |
Sync functions aren’t bad in themselves. At startup, before accepting requests, reading the configuration with readFileSync makes nobody wait. The problem is using them inside a route.
Why it matters with many users
Section titled “Why it matters with many users”Do the math with a route that blocks for a second and a half, like Luis’s report. If ten people ask for it at once, the tenth waits fifteen seconds. And not only them: any other request that arrives in the meantime waits too.
A bigger computer doesn’t fix it: your JavaScript runs on one thread, and a thread uses a single core of the processor. The asynchronous version does make use of more cores, because the helper threads calculate at the same time on other cores. Spreading the work across several Node processes is Phase 9.
Try it
Section titled “Try it”The goal: measure how long the product list waits while another request calculates, find out why your log doesn’t see it, and make it stop waiting.
Add the two imports and the two slow routes to your src/app.ts, create the examples folder with order.ts and start the server as in lesson 8, with npm start. If you get stuck, download this lesson’s folder from ~/backend-course/phase-3 and compare it with yours:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/09-event-loop.tar.gztar -xzf 09-event-loop.tar.gzAnd inside it, npm install. The outputs are from Node 26.11.1 on Linux. Your times will be different: they depend on your processor and on how busy it is. Look at the proportions, not at the exact numbers.
The two routes, separately
Section titled “The two routes, separately”With the server running in one terminal, open another.
1. A slow request, on its own
curl -w '\n' localhost:3000/slowWhat you will see:
{"ms":666}-w '\n' adds a line break at the end, as in lesson 7. Less than a second. On your computer it may be half a second or two; if it goes over five, lower ROUNDS to a million so you don’t wait so long.
2. The product list, on its own
curl -s -o /dev/null -w "products: %{time_total} s\n" localhost:3000/productsWhat you will see:
products: 0.000780 s-o /dev/null throws away the list, which you don’t care about right now, and -w writes, when it finishes, how long the whole request took, in seconds (%{time_total}), and the line break. Less than a millisecond: that’s the baseline.
The two at once
Section titled “The two at once”Now, the slow one and the list at almost the same time. Paste the whole block:
3. The list, while /slow calculates
( curl -s -o /dev/null -w "slow: %{time_total} s\n" localhost:3000/slow &sleep 0.2curl -s -o /dev/null -w "products: %{time_total} s\n" localhost:3000/productswait )What you will see:
slow: 0.663501 sproducts: 0.463793 s&starts the firstcurlin the background, as in Phase 1: you don’t wait for it to finish.sleep 0.2waits two tenths of a second, so that/slowarrives first.waitwaits for what’s in the background to finish.- The parentheses group the commands, so the shell doesn’t write its job notices (
[1] 4321,done).
The list, which took less than a millisecond, has taken almost half a second: what /slow still had left when it arrived. The two lines may come out in the other order: they finish almost at the same time.
What the log doesn’t see
Section titled “What the log doesn’t see”Look at the server’s terminal. Among its JSON lines, the ones from lesson 8, are the ones for these two requests:
4. The log of the two requests
npm startWhat you will see:
…{"level":30,"time":1791890318972,"pid":101,"hostname":"laptop","requestId":"7e553f91-cd6e-47ee-82f5-6e348e7884dc","method":"GET","path":"/slow","status":200,"ms":663,"msg":"request"}{"level":30,"time":1791890318973,"pid":101,"hostname":"laptop","requestId":"2337d7c1-1ed8-4701-aaad-47dac126939d","method":"GET","path":"/products","status":200,"ms":0,"msg":"request"}Don’t run it again: it’s the terminal where it’s already running. Your time, pid, hostname and requestId will be different.
Look at the "ms":0 for /products. For the server, the list took less than a millisecond; for the client, almost half a second. Both are telling the truth: the requestLog middleware starts counting when the request leaves the queue, and the wait came before. A blocked server doesn’t see it in its own times: you have to measure from the outside, as you’ve just done with curl. You’ll see it in Phase 10, with metrics.
Now, without blocking
Section titled “Now, without blocking”5. The list, while /slow-async calculates
( curl -s -o /dev/null -w "slow-async: %{time_total} s\n" localhost:3000/slow-async &sleep 0.2curl -s -o /dev/null -w "products: %{time_total} s\n" localhost:3000/productswait )What you will see:
products: 0.001002 sslow-async: 0.658673 sThe list comes out first, in a millisecond, even though it arrived later: the calculation is on a helper thread, and yours has served it without waiting. If products still takes as long as the slow one, check that you’re calling /slow-async and that its route uses await pbkdf2Async, not pbkdf2Sync.
Challenge: send two /slow at once, and then two /slow-async at once. How long does each one take? Why?Show answer
The two /slow, in the background and without the sleep:
( curl -s -o /dev/null -w "slow A: %{time_total} s\n" localhost:3000/slow & curl -s -o /dev/null -w "slow B: %{time_total} s\n" localhost:3000/slow & wait )slow B: 0.690596 sslow A: 1.360801 sAnd the same with /slow-async, calling them async A and async B:
async A: 0.674652 sasync B: 0.675149 sThe two /slow go in single file: the one that arrives second waits for the other to finish and takes twice as long. The two /slow-async calculate at the same time, each on a helper thread, and take as long as a single one. With five at once, the fifth would wait: there are four helper threads.
You have already seen it
Section titled “You have already seen it”- A frozen tab. When the browser warns that “the page isn’t responding,” it’s the same thing: the page’s JavaScript runs on one thread with its event loop, and something has blocked it.
- In DevTools (how to open them). The Performance tab records what a page does and marks with a red triangle the tasks longer than 50 milliseconds: pieces of code that have blocked the thread.
- In your terminal.
sleep 60leaves you without a prompt until it finishes, andsleep 60 &gives it back right away: blocking or not blocking, in Phase 1. - In HTTP/1.1. A slow response held up the ones behind it: head-of-line blocking, the same idea.
Common mistakes
Section titled “Common mistakes”Syncfunctions inside a route.readFileSyncorpbkdf2Syncblock the thread while they last: in a route, use the asynchronous version.- Believing that
asyncsends the work to another thread. Anasyncfunction runs on the same thread. If there’s a one-second calculation inside, it blocks for a second, with or withoutawaiton other lines. - Trusting the server’s own times. Your log doesn’t see what a request waits in the queue. Measure from the client.
- Forgetting that reading JSON is calculating too. A
JSON.parseof 50 MB blocks the whole server: limit the size of what you accept.
Summary
Section titled “Summary”- All your JavaScript runs on a single thread: the event loop runs a piece of code to the end and takes the next thing from the queue.
- Waiting for the network or the disk doesn’t block: libuv does it, and the thread stays free. Calculating does, and while it lasts, every request waits.
- First comes the current code, then the fulfilled promises and then the timers:
setTimeout(…, 0)isn’t “now.” - To avoid blocking: the asynchronous version, splitting the work,
worker_threadsor another service. - Your log doesn’t see the blocking: measure it from the outside, with several requests at once.
What you’ve built in this phase
Section titled “What you’ve built in this phase”Maybe you started the phase without ever having programmed, and you finish it with a real API for Ana and Luis’s shop, the one that replaces the fake /api/orders of Phase 2’s nginx:
- routes to see the products and the orders, all of them or one by one, and to create them: first with
node:httpand then with Hono; - middleware that logs each request, opens CORS to the shop and answers
401to anyone who adds products without Ana’s token; - validation with Zod: a
422that says which field fails and why, and a400if the request can’t even be read; - errors that don’t slip out: a
404or a500in JSON, without the stack trace and with an id to find it in the log; - logs in JSON, configuration in environment variables and, now, what makes an API slow and how to measure it.
Up to here, you decided what each route was called and what it answered. In Phase 4, “API design,” you design it for others: routes that are understood without asking you, pagination, versions and a written contract with OpenAPI.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- The Node.js Event Loop (Node.js): the phases of the loop, one by one, with
setImmediateandprocess.nextTick. - Don’t Block the Event Loop (or the Worker Pool) (Node.js): what blocks, including regular expressions and large JSON, and how to avoid it.
- JavaScript execution model (MDN): the same model in the browser, with its task queues.
- What the heck is the event loop anyway? (Philip Roberts, JSConf EU 2014): a talk that draws the event loop step by step.