Courses / Node.js: From First Script to Production / Chapter 12
Module 6 · Inside the runtime · Chapter 12 of 27
process.nextTick, Promise Jobs and the Microtask Queue
Builds on Globals and Modules: process, CommonJS and ES Modules, Asynchronous Programming: Callbacks, Promises and async/await, Event-Driven Programming with EventEmitter and Inside the Event Loop: Phases, Timers and setImmediate. Next up: The libuv Thread Pool and Blocking Work.
Part 1 · Two queues between callbacks
Work that runs before the loop moves on
Some callbacks must run right after the current code, before any timer or file result gets a turn. Node has two queues for exactly that, and mixing them up is the usual reason a log appears in a surprising place.
The previous chapter showed the loop's phases. Two kinds of callback sit outside those phases. The first is the next tick queue, filled by process.nextTick(fn). The second is the microtask queue, which belongs to V8, the JavaScript engine. It holds promise jobs, which are the callbacks you pass to then, catch and finally once a promise has settled, and the functions you pass to queueMicrotask. The continuation of an await also goes there, as a later lesson shows.
Node empties both queues whenever the JavaScript stack becomes empty: after the main script, and after every single callback the loop runs. The process.nextTick documentation states the rule. The next tick queue is fully drained after the current operation completes and before the event loop continues. Whenever that queue has been drained, the microtask queue is drained immediately after.
That gives the order of draining. First every tick callback. Then every promise job. If a promise job queues a new tick, or a tick queues a new promise job, Node goes round again until both queues are empty. Only then does the loop get the thread back.
The five-line order
The script below queues a timer, an immediate, a tick and a promise job, in that order, after one line that logs at once. It is a CommonJS file, so it is saved with the .cjs extension.
console.log('sync'); setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate')); process.nextTick(() => console.log('tick')); Promise.resolve().then(() => console.log('promise'));
sync tick promise timeout immediate
Node 24.18.0, one run on Windows.
The order of the first three lines is fixed. The synchronous line comes first, then the tick, then the promise job, then the loop starts. The last two lines are the timer and the immediate, the pair from the previous chapter whose order is not guaranteed in the main module. The next output counts 20 runs of the same file.
l1-order.cjs {
'sync tick promise immediate timeout': 11,
'sync tick promise timeout immediate': 9
}20 runs on Windows. The counts differ on every run.
Only the last two entries move. The tick and the promise job never move. Look at the order in the scene.
Watch for the tick and the promise running before any phase
Read it as steps
A CommonJS script queues a timer, an immediate, a tick and a promise job, and they run in a fixed order.
Ticks and promises feed each other
The ordering rule is easier to trust once you test it with nesting. In the next script, a promise job queues a tick, and a tick queues a promise job.
Promise.resolve().then(() => {
console.log('promise 1');
process.nextTick(() => console.log('tick from promise'));
});
Promise.resolve().then(() => console.log('promise 2'));
process.nextTick(() => {
console.log('tick 1');
Promise.resolve().then(() => console.log('promise from tick'));
});
process.nextTick(() => console.log('tick 2'));tick 1 tick 2 promise 1 promise 2 promise from tick tick from promise
Node 24.18.0.
Both ticks ran first, then both promise jobs. The promise job queued by tick 1 ran in the same microtask drain, right after the two jobs that were already waiting. The tick queued by promise 1 had to wait until the whole microtask queue was empty, and then it ran. That is the "go round again" rule at work. The tick queue is not drained between two promise jobs.
Between each callback
The drain happens after every callback, not once per phase. Before Node 11, the timers phase ran all its due timers and only then drained the tick queue. The Node 11 release notes record the change: the next tick queue runs after each immediate and each timer. Two timers due at the same moment show it.
setTimeout(() => {
console.log('timer 1');
process.nextTick(() => console.log(' tick from timer 1'));
Promise.resolve().then(() => console.log(' promise from timer 1'));
}, 5);
setTimeout(() => {
console.log('timer 2');
process.nextTick(() => console.log(' tick from timer 2'));
Promise.resolve().then(() => console.log(' promise from timer 2'));
}, 5);timer 1 tick from timer 1 promise from timer 1 timer 2 tick from timer 2 promise from timer 2
Node 24.18.0.
The tick and the promise job from the first timer ran before the second timer started. Each callback is complete, with its follow-up work, before the next one begins. This makes microtask-based code predictable: a function that queues a job does not wait behind other timers.
A script logs a, then calls process.nextTick to log b, then calls Promise.resolve().then to log c. What does a CommonJS file print?
a,b,c. The tick queue is drained before the microtask queue.
Inside a promise job you call process.nextTick(f). When does f run?
- After the microtask queue is empty. Node drains ticks, then promise jobs, and repeats until both are empty, so
fwaits for the other jobs already queued.
Two timers are due together and the first queues a promise job. Does the job run before the second timer's callback?
- Yes. Since Node 11 the tick and microtask queues are drained after each timer callback, not after the whole timers phase.
Part 2 · ES modules change the first turn
The same file, a different order
The five lines from the previous lesson print a different order when the file is an ES module. This is the one fact about ordering that surprises people who know the CommonJS result.
Save the same five lines as l2-order.mjs, or put "type": "module" in the nearest package.json. Run it, and the tick and the promise swap places.
sync promise tick immediate timeout
Node 24.18.0. The same lines as the previous lesson, in an `.mjs` file.
l2-order.mjs {
'sync promise tick timeout immediate': 6,
'sync promise tick immediate timeout': 14
}20 runs on Windows. Only the last two entries move.
In the CommonJS run the tick printed before the promise. Here the promise printed first. The synchronous line is still first, and the timer and immediate still race at the end.
Why the order flips
The Node documentation explains it. A CommonJS file is run by Node's loader as an ordinary function call, so when the file finishes, Node is on its normal path and drains the tick queue first. An ES module is different. Its code is evaluated as part of the microtask queue, the same queue promises use. When the module's top-level code ends, V8 is already in the middle of draining that queue. It carries on and runs the remaining promise jobs before it returns control to Node, and only then does Node look at the tick queue.
The same documentation page gives the rule for queueMicrotask. In a CommonJS file a tick always runs before a microtask. In an ES module a microtask always runs before a tick, since Node is already draining the microtask queue.
The nested script from the previous lesson is a test of this. Here it is as an ES module.
promise 1 promise 2 tick 1 tick 2 tick from promise promise from tick
Node 24.18.0. The nested script of the previous lesson in an `.mjs` file.
Compare the two orders. The promise jobs run first now. The ticks follow, and tick from promise is queued by a promise job that already ran, so it comes after the two ticks that were waiting.
Only the top level is special
The flip applies to code at the top of the module, which is part of the module's evaluation. Code inside later callbacks behaves normally. A file callback, a timer or a request handler is run by the loop, and after each of them Node drains the tick queue first. The script in the last lesson of this chapter shows an .mjs file where the tick runs before the promise inside a file callback.
The practical rule is short. Never write code whose correctness depends on a tick running before a promise job, or the other way round. If two pieces of work must run in a given order, make the second depend on the first: chain the promises, or emit an event after the first one is done. The ordering table is for reading other people's logs, not for relying on.
The same code with process.nextTick and Promise.resolve().then is moved from a .cjs file to a .mjs file. What changes?
- At the top level of the file, the promise job now runs before the tick. In the CommonJS file the tick ran first.
Why does the module type change the order?
- An ES module is evaluated inside the microtask queue, so V8 keeps draining promise jobs before Node gets to the tick queue. A CommonJS file runs as a normal call, and Node drains ticks first.
Does a process.nextTick call inside a timer callback in an .mjs file run before or after a promise job queued in the same callback?
- Before. The special order is only for the module's top-level code. A timer callback is run by the loop, which drains ticks first.
Part 3 · Where await resumes
What await does to a function
An async function looks like ordinary code that waits, so it is easy to forget that the waiting is the microtask queue at work. The thread is handed back at every await, and the exact place matters.
An async function runs synchronously until its first await. At that point the function pauses and returns a promise to its caller. The value after await is turned into a promise if it is not one already. When that promise settles, a promise job is queued to resume the function from the line after the await. The rest of the function is therefore a callback, and it runs as a microtask.
That has a consequence for the order. Even await null, which has nothing to wait for, gives up the thread. The remainder of the function does not run until the current stack is empty and the queue reaches that job.
Two functions taking turns
Both functions below await twice. The script calls them one after another, and then logs a line.
async function first() { console.log('first: start'); await null; console.log('first: after 1st await'); await null; console.log('first: after 2nd await'); } async function second() { console.log('second: start'); await null; console.log('second: after 1st await'); await null; console.log('second: after 2nd await'); } first(); second(); console.log('sync code done');
first: start second: start sync code done first: after 1st await second: after 1st await first: after 2nd await second: after 2nd await
Node 24.18.0.
Each function ran until its first await, then handed back. The sync code done line came before either of them resumed, because the resumptions are jobs. When the stack was empty, the first function resumed, then the second, then the first again. They took turns, one microtask at a time. No setTimeout was involved at all, and the loop never left the microtask queue.
Await against then
An await costs one promise job, the same as a then. The next script runs an async function against a then chain started a moment later.
async function waiter() { await null; console.log('A: after await'); } waiter(); Promise.resolve() .then(() => console.log('B: then 1')) .then(() => console.log('B: then 2')) .then(() => console.log('B: then 3')); console.log('sync code done');
sync code done A: after await B: then 1 B: then 2 B: then 3
Node 24.18.0.
A: after await came before the first then callback, since the async function started first, and each of the then steps took one job. The two styles share one queue and run in the order the jobs were queued.
Returning a promise costs extra jobs
There is one case where the count is not one. If an async function returns a promise, the outer promise does not settle with it directly. It has to wait for that inner promise through extra steps. The script compares an async function that returns a plain value with one that returns an already resolved promise, with a four-step then chain as a ruler.
async function plain() { return 'x'; } async function wrapped() { return Promise.resolve('x'); } plain().then(() => console.log('plain settled')); wrapped().then(() => console.log('wrapped settled')); Promise.resolve() .then(() => console.log('tick 1')) .then(() => console.log('tick 2')) .then(() => console.log('tick 3')) .then(() => console.log('tick 4'));
plain settled tick 1 tick 2 wrapped settled tick 3 tick 4
Node 24.18.0 and V8 13.6. The exact count is V8's behaviour and may change.
The plain function settled before the first ruler step. The one that returned a promise settled after the second ruler step. It took two extra jobs. You would not normally count jobs like this. It matters when two async paths race and a log shows an order you did not expect. Inside an async function, return value is the cheaper form. Use return await promise only inside a try block, when you want the catch block to see the rejection.
An async function calls await null on its first line. When does the line after it run?
- Later, as a promise job, once the current call stack is empty. The
awaithands the thread back even though nothing was pending.
Two async functions each await twice and are called one after the other. How do their steps interleave?
- The first runs to its first
await, then the second does. They resume in the same order, one microtask at a time, and each pauses again at its nextawait.
Why can returning a promise from an async function make its result arrive later than returning a plain value?
- The returned promise has to be adopted by the function's own promise, which takes extra promise jobs. In this run it took two more.
Part 4 · Starving the loop
A queue that never empties
Microtasks are the fastest way to run code, which is why they are dangerous. If the two queues never become empty, the loop never gets to run again.
Remember the rule from the first lesson: Node drains the tick queue and the microtask queue completely before the loop moves on. If a callback keeps queuing another one, that queue is never empty. Timers stay due and never run. Incoming connections wait in the operating system. The process still uses the processor, but nothing else moves. This is called starvation.
The Node documentation warns about it. It is possible to create an infinite loop by recursively calling process.nextTick. The script below shows the effect without an infinite loop. It recurses for 300 ms of wall time and then stops, while a timer waits for 10 ms.
const start = performance.now(); const stopAt = start + 300; setTimeout(() => { const ms = Math.round(performance.now() - start); console.log(`timer asked for 10 ms, ran after ${ms} ms`); }, 10); function spin() { if (performance.now() < stopAt) process.nextTick(spin); } spin();
timer asked for 10 ms, ran after 300 ms
Node 24.18.0.
The timer was set for 10 ms and ran after 300 ms. It was due almost at once, but the loop never reached the timers phase until spin stopped queuing itself. In a real server the same bug means no request is answered for as long as the recursion lasts.
Promises do the same
Promise jobs are no safer. A chain that keeps adding the next job starves the loop in the same way.
const start = performance.now(); const stopAt = start + 300; setTimeout(() => { const ms = Math.round(performance.now() - start); console.log(`timer asked for 10 ms, ran after ${ms} ms`); }, 10); function spin() { if (performance.now() < stopAt) Promise.resolve().then(spin); } spin();
timer asked for 10 ms, ran after 300 ms
Node 24.18.0.
Same result, 300 ms. The cause is the queue, not the API. The two forms differ in one way: with nextTick the other microtasks wait too, but with promises the tick queue waits. In both the loop waits.
This happens in real code more often than in demos. A loop such as for (const id of ids) await cache.get(id) where the cache always answers from memory does not wait on I/O. Each await resolves in a job, the next iteration starts at once, and a very large list holds the loop for as long as the work takes. A single long loop is not a bug in itself, but you must know that await on a value that is already there does not let timers or sockets in. The next script runs 50 lakh awaits on a map lookup while a 10 ms timer waits.
const start = performance.now(); const since = () => Math.round(performance.now() - start); setTimeout(() => { console.log(`timer asked for 10 ms, ran after ${since()} ms`); }, 10); const cache = new Map([['a', 1]]); async function get(key) { return cache.get(key); } let sum = 0; for (let i = 0; i < 5_000_000; i++) sum += await get('a'); console.log(`${sum} awaits finished after ${since()} ms`);
5000000 awaits finished after 302 ms timer asked for 10 ms, ran after 306 ms
Node 24.18.0 on Windows. The time depends on the machine.
The timer printed after the loop, not during it. Nothing in the loop waited for I/O, so the loop never reached the timers phase.
The fix: give the loop a turn
To let the loop run between pieces of work, the work has to go through a phase. setImmediate does that. Each immediate queued from inside an immediate runs in the check phase of the next turn, so the timers phase and the poll phase get their turn in between.
const start = performance.now(); const stopAt = start + 300; setTimeout(() => { const ms = Math.round(performance.now() - start); console.log(`timer asked for 10 ms, ran after ${ms} ms`); }, 10); function spin() { if (performance.now() < stopAt) setImmediate(spin); } spin();
timer asked for 10 ms, ran after 10 ms
Node 24.18.0. The same script, with `setImmediate` in `spin`.
The timer ran after 10 ms, on time, while spin kept going. Watch the recursion and the fix side by side.
Watch for the timer waiting while spin re-queues itself
Read it as steps
A function that keeps re-queuing itself with nextTick holds the timer back. With setImmediate the timer runs on time.
The scene shows the whole point: a callback that queues itself with setImmediate yields after each piece. One that queues itself with nextTick or a promise does not. When you must process a large array without blocking, handle a few thousand items, then call setImmediate for the next batch. The thread pool chapter applies the same idea to CPU work.
Part 5 · Choosing a scheduler
Four ways to say "later"
Node gives you four ways to run a function after the current code. They look alike, but each sits at a different place in the order, and choosing among them is a design decision.
| Call | Runs | Good for |
|---|---|---|
process.nextTick(fn) | after the current operation, before promise jobs | rare: errors and events that must come before anything else |
queueMicrotask(fn) or a promise | after the tick queue, before the loop moves on | small follow-up work that must finish before I/O |
setImmediate(fn) | the check phase of the current turn | splitting long work, letting I/O run first |
setTimeout(fn, ms) | the timers phase, at least ms later | real delays, retries, timeouts |
The documentation marks process.nextTick as legacy (stability 3, changed in Node 22.7 and 20.18) and tells you to prefer queueMicrotask unless you need what only the tick queue can do. A tick's one special power is that it runs before promise jobs in a CommonJS file. Almost no application code needs that.
The script below calls all four inside a file callback, where the order is settled.
import fs from 'node:fs'; fs.readFile(import.meta.filename, () => { setTimeout(() => console.log('setTimeout 0'), 0); setImmediate(() => console.log('setImmediate')); queueMicrotask(() => console.log('queueMicrotask')); Promise.resolve().then(() => console.log('promise then')); process.nextTick(() => console.log('process.nextTick')); console.log('callback body ends'); });
One error behaves differently
A function passed to queueMicrotask is not wrapped in a promise. An exception thrown in it is not a rejection. It goes to the process as an uncaught exception.
process.on('uncaughtException', (err) => { console.log(`uncaught: ${err.message}`); }); queueMicrotask(() => { throw new Error('thrown in a microtask'); }); setTimeout(() => console.log('timer still runs'), 0);
uncaught: thrown in a microtask timer still runs
Node 24.18.0.
The handler for uncaughtException saw the error. If no handler were installed, the process would end with the usual stack trace. Always put a try and catch inside a microtask callback, as you would in a timer.
Deferred events: the standard case
The event emitter chapter showed why a constructor must not emit synchronously: the caller attaches its listener only after the constructor returns, so the event is lost. Here are the two ways to defer it, next to the eager version, in one script.
import { EventEmitter } from 'node:events'; class EagerJob extends EventEmitter { constructor() { super(); this.emit('ready'); } } class TickJob extends EventEmitter { constructor() { super(); process.nextTick(() => this.emit('ready')); } } class MicrotaskJob extends EventEmitter { constructor() { super(); queueMicrotask(() => this.emit('ready')); } } const hear = (name) => () => console.log(`${name}: heard ready`); new EagerJob().on('ready', hear('eager')); new TickJob().on('ready', hear('tick')); new MicrotaskJob().on('ready', hear('microtask')); console.log('all jobs created');
all jobs created microtask: heard ready tick: heard ready
Node 24.18.0, in an `.mjs` file.
The eager version emitted at once, and nobody was listening. The other two deferred the emit, so the caller's on call, which runs right after the constructor, was already in place. Both deferred forms work. In this ES module the microtask version printed first. The same classes in a CommonJS file printed in the other order, as the next output shows. The listeners do not depend on that.
all jobs created tick: heard ready microtask: heard ready
Node 24.18.0, the same code as a `.cjs` file with `require`.
Choose by the rule of thumb in the table: use queueMicrotask here, and use process.nextTick only when you need to go before promise jobs.
This is the pattern behind many Node APIs. A function that takes a callback must call it always synchronously or always asynchronously, never sometimes one and sometimes the other, so that callers can reason about the order. When you can finish at once but your caller expects to be called later, defer with queueMicrotask.
| Term | Meaning |
|---|---|
| Tick queue | callbacks from process.nextTick, run before promise jobs |
All chapters · Previous: Inside the Event Loop: Phases, Timers and setImmediate