DEV Community

Kushagra Sharma
Kushagra Sharma

Posted on

The Rare process.nextTick Infinite Loop Bug in Node.js — How It Nearly Crashed Our Production

A rare infinite loop can occur in Node.js when process.nextTick() is abused—especially when recursive calls are unintentionally made. It can silently block the entire event loop, causing everything else (I/O, timeouts, intervals) to stop responding. Here’s how it happened, how we debugged it, and how we fixed it.

📌 Background
While process.nextTick() is meant to schedule callbacks before the event loop proceeds, it's not throttled like setImmediate() or setTimeout(). It’s intended for quick tasks like deferring a callback once, not for recursion or loops.

function scheduleJob(job) {
process.nextTick(() => {
processJob(job);
});
}

function processJob(job) {
if (shouldReschedule(job)) {
scheduleJob(job); // Recursive!
}
}

We replaced process.nextTick() with setImmediate() to avoid starving the event loop:

function scheduleJob(job) {
setImmediate(() => {
processJob(job);
});
}
const { setTimeout } = require('timers/promises');

async function processJob(job) {
if (shouldReschedule(job)) {
await setTimeout(0); // let event loop proceed
processJob(job);
}
}
Avoid recursion with process.nextTick().

Use setImmediate() if you want to schedule something after I/O callbacks.

process.nextTick() is for short deferrals — treat it like a microtask, not a job scheduler.

Always validate external job data (cron, flags) before scheduling.

Add monitoring to detect long event loop blockage (event-loop-lag, blocked-at, etc).

Top comments (0)