Small Fastify demo: a worker thread pool that offloads CPU-style work via Node’s worker_threads API.
Even a small synchronous loop can freeze the whole process if it blocks the event loop. See the Node.js guide: Don’t block the Event Loop.
Setup: start the server in one terminal.
npm run devA — Blocking route (/block)
- The handler runs a huge loop on the main thread, so the event loop cannot serve other requests until it finishes.
- Terminal 1: start a long request (it will run for a long time):
curl http://127.0.0.1:3000/block
- Terminal 2 (while Terminal 1 is still waiting):
curl http://127.0.0.1:3000/ping
**/pingstays slow or stalls** until/blockcompletes, because the server thread is busy in the loop.
B — Non-blocking route (/non-block)
- The same kind of work runs inside a worker; the main thread can still handle other requests.
- Terminal 1:
curl http://127.0.0.1:3000/non-block
- Terminal 2 (while Terminal 1 is still running):
curl http://127.0.0.1:3000/ping
**/pingreturns quickly** even while/non-blockis still computing in the separate thread and not blocking the main thread / event loop.
- Node.js 18+ (
worker_threadsis built in)
npm installnpm run devRuns tsc, then node dist/index.js. After you change TypeScript, run again, or use npm run build and npm start.
| Route | Behavior |
|---|---|
GET /ping |
{ "message": "pong" } — cheap; use to test responsiveness |
GET /block |
Long loop on the event loop (starves other routes) |
GET /non-block |
Long loop in a worker; { "result": … } — main thread stays free |
curl http://127.0.0.1:3000/ping
curl http://127.0.0.1:3000/non-blockDefault port: 3000.