How to Implement Cooperative Scheduling in Node.js
Keep the event loop responsive by yielding between units of CPU work, using chunked processing and setImmediate to avoid starving I/O.
On this page
Introduction
Node.js runs your JavaScript on a single thread, and the event loop can only handle I/O between units of work. A function that crunches for two seconds blocks every request, timer and socket callback for two seconds, because no other JavaScript can run until it returns. You cannot preempt it; JavaScript has no threads in the usual sense. What you can do is cooperate: break the work into chunks and yield to the event loop between them, so I/O keeps flowing and latency stays bounded.
Why the Event Loop Starves
The event loop processes one callback at a time. While a callback is running, no timers fire, no I/O callbacks run and no promises settle. A long synchronous loop, a large JSON.parse, a heavy regular expression or a recursive traversal all hold the loop hostage for their full duration, and every pending operation waits.
The symptom is a latency spike with no downstream error: p99 jumps, but CPU may be only partially used and no dependency is slow. The cause is a single task monopolising the loop. Cooperative scheduling addresses it by giving the loop a chance to breathe between bounded slices of work.
Chunking Work and Yielding
The basic pattern is to process a bounded batch, then yield, then continue. Yielding with setImmediate lets the loop run pending I/O and timers before resuming, which is what keeps sockets responsive. process.nextTick is the wrong choice here because it defers to the end of the current operation, not to a new loop turn, so it does not actually give I/O a chance.
Choose a chunk size you can measure. Each yield has overhead, so batches that are too small waste time on scheduling and batches that are too large still stall the loop. Measure the duration of one chunk and target a few milliseconds, then adjust so the loop is never blocked long enough to matter.
import { setImmediate as yieldToLoop } from 'node:timers/promises';
async function processInChunks(items, handle, chunkSize = 500) {
for (let i = 0; i < items.length; i += chunkSize) {
const slice = items.slice(i, i + chunkSize);
for (const item of slice) handle(item); // bounded synchronous work
await yieldToLoop(); // let I/O and timers run
}
}
await processInChunks(rows, (row) => transform(row));
Yielding Inside Long Loops
Not every workload is an array. A long loop in a crypto routine, a graph traversal or a parser can be refactored into a generator that yields control periodically. The generator produces a unit of work, the caller awaits a yield to the loop, and then resumes. This threads cooperation through code that has no natural batch boundary.
A common helper checks the elapsed time since the last yield and yields when a budget is exceeded, so the code keeps its logical structure while respecting a latency budget. Budget-based yielding adapts to the actual cost of each item, which a fixed chunk size cannot.
import { setImmediate as yieldToLoop } from 'node:timers/promises';
async function withBudget(items, handle, budgetMs = 5) {
let last = Date.now();
for (const item of items) {
handle(item);
if (Date.now() - last >= budgetMs) {
await yieldToLoop(); // budget exceeded: cooperate
last = Date.now();
}
}
}
Offloading Truly CPU-Bound Work
Cooperative yielding helps when the work can be sliced, but some work cannot be interrupted without changing its result: a single encryption of a large buffer, a native library call, a heavy compression. For these, cooperation is not enough and the right answer is to move the work off the main thread entirely, to worker_threads or a separate process.
Decide by asking whether the work blocks the loop for longer than your latency budget even when chunked. If yes, offload it. If it blocks for a few milliseconds that can be sliced, chunk it. Mixing both, chunking on the main thread and offloading the genuinely heavy parts, is often the practical answer.
# decision guide
work blocks loop < ~5ms and can be sliced -> chunk + yield (setImmediate)
work blocks loop for tens of ms, sliceable -> chunk + yield per budget
work is atomic and blocks for tens+ ms -> worker_threads or child process
work is I/O bound -> await the I/O, loop is fine
Measuring Loop Health
Instrument the loop directly. Event loop lag, the delay between when a timer was scheduled and when it fired, is the signal that a task is blocking the loop. Export it as a metric and alert on sustained lag, because lag is the leading indicator of latency that comes from your own code rather than a dependency.
Monitor per-phase timing if your runtime exposes it, to see whether time is spent in timers, I/O or the CPU-bound callbacks. A rising lag with flat external latency often means a background job is starving foreground requests, which points you at the specific code path to chunk.
import { monitorEventLoopDelay } from 'node:perf_hooks';
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
setInterval(() => {
console.log('loop lag p99 (ms):', histogram.percentile(99) / 1e6);
}, 5000);
// sustained lag => a synchronous task is starving the loop
Common Pitfalls and Conclusion
Do not yield with process.nextTick, which does not let I/O run. Do not yield so often that scheduling overhead dominates. Do not assume chunking fixes atomic work; offload it. Do not forget that await already yields to the microtask queue but not to I/O, so awaiting a resolved promise in a tight loop rarely helps. And do not ignore event-loop lag, which is the metric that proves your scheduling works.
Cooperative scheduling keeps a single-threaded runtime responsive by bounding the time any one task holds the loop. Chunk array work, yield with setImmediate between slices, use budget-based yielding for irregular loops, offload atomic heavy work, and watch event-loop lag to confirm the loop is breathing. It is not a substitute for threads, but it is what keeps Node.js services from stalling under their own CPU work.
Sources: Node.js: The event loop, Node.js: worker_threads, Node.js: perf_hooks event loop delay.
FAQ
- Why does process.nextTick not help here?
- nextTick defers the callback to the end of the current operation, before I/O, so it does not give pending sockets and timers a chance to run. setImmediate defers to the next loop iteration, which is what relief for I/O requires.
- When should I use a worker thread instead of yielding?
- When the work is atomic and blocks the loop longer than your latency budget even when chunked, such as a single large encryption or a heavy native call. If the work can be sliced into milliseconds-sized pieces, chunking and yielding is simpler.
Report a problem with this articleOpens a pre-filled issue on GitHub.