In this lesson, you will learn how infinitely recursive promises can monopolize the event loop and effectively "freeze" your application.
The Power of the Microtask Queue
As we’ve discussed, the Microtask Queue (where Promise callbacks live) has a higher priority than the other phases of the event loop. When the current operation finishes, the event loop empties the entire Microtask Queue before moving on to the next phase, such as the Poll phase (I/O) or the Timers phase.
The Recursion Trap
Because the engine promises to drain all microtasks before returning to the event loop, we encounter a danger: what happens if your microtasks keep adding new microtasks faster than they can be finished?
Consider this example:
function recursiveTask() {
Promise.resolve().then(() => {
// This adds a new microtask every time one finishes
recursiveTask();
});
}
recursiveTask();
In this code, every time a Promise resolves, it schedules another Promise. Because the microtask queue must be completely drained before the event loop can process timers, I/O, or check callbacks, the event loop gets stuck in an infinite loop inside the microtask phase.
The Impact on Latency
When this happens, the "tick duration" of your event loop becomes infinite. Your application stops responding to:
- Timers:
setTimeoutcallbacks will never execute. - I/O: Incoming network requests or file system reads will sit in the queue indefinitely.
- User Interaction: Any operation relying on the loop to progress will appear frozen.
While Node.js doesn't have a hard "depth limit" number that throws an error, the logical limit is the time your users are willing to wait. If you flood the microtask queue, you effectively stop the heart of your Node.js application, leading to a state of complete starvation for all other phases of the loop.
Key Takeaway: Because the event loop must exhaust the entire microtask queue before moving to the next phase, infinitely recursive promises will trap the runtime in the microtask phase and starve your application of all other event loop processing.