Node.js Course
Node.js
/
Advanced

Thread Pool

Definition

A collection of background threads maintained by `libuv` to execute heavy tasks that cannot be handled asynchronously by the OS kernel, preventing them from blocking the main Event Loop.

Explain Like I'm New

Wait, I thought Node was single-threaded? The JavaScript code YOU write is single-threaded. But deep in the basement, `libuv` maintains a secret team of 4 C++ workers (The Thread Pool). When you ask Node to hash a password or read a file, it secretly passes that work to the basement workers. They do the heavy lifting simultaneously while your main thread keeps serving web pages.

Real World Example

Cryptographic functions (`pbkdf2`), File System operations (`fs.readFile`), and DNS lookups all use the Thread Pool automatically.

Common Use Cases

  • •Optimizing CPU-bound internal operations

Interactive Example

// HOW TO CHANGE THE THREAD POOL SIZE
// You must set this environment variable BEFORE the app starts!
// process.env.UV_THREADPOOL_SIZE = 8;

const crypto = require('crypto');
const start = Date.now();

function doHeavyMath(id) {
  crypto.pbkdf2('pwd', 'salt', 100000, 512, 'sha512', () => {
    console.log(`Task ${id} finished in ${Date.now() - start}ms`);
  });
}

// If you run this with the default pool of 4:
// Tasks 1-4 will finish at roughly the same time (e.g., ~1000ms)
// Task 5 will take TWICE as long (~2000ms) because it had to wait for a free thread!

// doHeavyMath(1);
// doHeavyMath(2);
// doHeavyMath(3);
// doHeavyMath(4);
// doHeavyMath(5);

console.log("The Thread Pool is the hidden secret to Node's non-blocking magic.");

Interview Questions

basic

  • How many threads does the libuv Thread Pool have by default?

intermediate

  • What happens if you run 5 heavy cryptography functions at the exact same time?

Flash Cards

Question

How many threads by default?

Click to reveal answer
Answer

Four (4).

Question

What happens with 5 tasks?

Click to reveal answer
Answer

The first 4 tasks will immediately occupy the 4 threads in the pool. The 5th task must wait in line. It will not start executing until one of the first 4 tasks finishes and frees up a thread.