Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

worker-threads

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.

Demonstration

Setup: start the server in one terminal.

npm run dev

A — 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
  • **/ping stays slow or stalls** until /block completes, 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
  • **/ping returns quickly** even while /non-block is still computing in the separate thread and not blocking the main thread / event loop.

Requirements

  • Node.js 18+ (worker_threads is built in)

Setup

npm install

Run

npm run dev

Runs tsc, then node dist/index.js. After you change TypeScript, run again, or use npm run build and npm start.

HTTP routes

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-block

Default port: 3000.

About

Small Fastify demo: a worker thread pool that offloads CPU-style work via Node’s worker_threads API.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages