Call Stack, Callback Queue, Microtask Queue & Libuv Workers
Call Stack, Callback Queue, Microtask Queue & Libuv Workers
To master backend performance and debug tricky race conditions in Node.js, every developer must understand the exact priority mechanism governing asynchronous execution: the Call Stack, the Microtask Queue, the Callback Queue (Macrotask Queue), and the Libuv Worker Thread Pool.
1. Execution Priority Hierarchy
When multiple asynchronous operations complete simultaneously, Node.js uses a strict order of precedence:
- 1Synchronous Code on Call Stack: Runs immediately until the call stack is completely empty.
- 2Microtask Queue 1 (
process.nextTick): Runs before ANY other asynchronous queue, immediately after the current operation finishes. - 3Microtask Queue 2 (Promises /
queueMicrotask): Promise.then(),.catch(), andasync/awaitcontinuations. - 4Macrotask / Timer Queue (
setTimeout,setInterval): Evaluated during the Timers phase of the Event Loop. - 5Check Queue (
setImmediate): Executed during the Check phase of the Event Loop.
2. Priority Demonstration in Code
Actual Execution Order:
3. The Libuv Worker Thread Pool
While network I/O (HTTP sockets, TCP) uses non-blocking OS kernel polling (epoll/kqueue), certain operations cannot be performed asynchronously by operating system kernels. Node.js sends these to the Libuv Thread Pool:
- File System Operations:
fs.readFile,fs.writeFile - Cryptography:
crypto.pbkdf2,crypto.scrypt,crypto.randomBytes - Compression:
zlib.deflate,zlib.gzip - DNS Lookups:
dns.lookup
The default size of this thread pool is 4 threads, but it can be scaled for heavy workloads using the environment variable:
Multiple Choice Questions
process.nextTick() inside its own callback?setTimeout(fn, 0) and setImmediate(fn), which is explicitly designed to execute immediately after the I/O polling phase completes?Non-Blocking Asynchronous Code with Promises and Async/Await
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.