Skip to content

Interview PrepRuntime · Core

The Node.js Event Loop and I/O ​

9. What is non-blocking I/O? ​

The short answer

I/O means input and output: reading files, talking to databases, calling other services over the network. Non-blocking I/O means starting such an operation and getting control back immediately, instead of the thread stopping until the data arrives. The program is told later, through a callback or a resolved promise, when the result is ready. In Node.js, this is what lets one thread serve thousands of connections: while one request waits for the database, the thread handles others.

A restaurant picture. A blocking waiter takes an order, walks it to the kitchen, and stands there until the food is ready, serving nobody else. A non-blocking waiter takes the order, hands it to the kitchen, serves other tables, and comes back when the kitchen rings the bell.

blockingAwaits for DB, idleABwaits for DB, idleBnon-blockingABABboth queries wait at the same time; the thread is freetime →
Wait together, not in turn. A blocking thread sits idle during each database call, so requests queue behind each other. A non-blocking thread starts both calls and handles each reply when it arrives.
ts
import { readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'

app.get('/terms', (req, res) => {
  const text = readFileSync('terms.html', 'utf8')       // (1) blocking
  res.send(text)
})

app.get('/terms-better', async (req, res) => {
  const text = await readFile('terms.html', 'utf8')     // (2) non-blocking
  res.send(text)
})
  1. The whole server stops until the file is read. Under load, every other request waits.
  2. The read happens off the main thread, and other requests run meanwhile.

Synchronous file calls are fine at start-up, such as reading a config file before the server starts listening, because no requests are being served yet. Never use them inside request handlers.

10. What is the difference between blocking and non-blocking operations? ​

The short answer

A blocking operation stops the calling thread until it finishes, so nothing else can run on that thread in the meantime. A non-blocking operation returns at once and reports its result later. In Node.js, blocking the main thread is the worst case, because it pauses every request in the process. Blocking happens with synchronous APIs such as fs.readFileSync, with CPU-heavy JavaScript such as large loops, JSON parsing of huge payloads or slow regular expressions, and with synchronous crypto.

BlockingNon-blocking alternative
fs.readFileSync, fs.writeFileSyncfs/promises, streams (question 53)
crypto.pbkdf2Sync, scryptSynccrypto.pbkdf2, crypto.scrypt with a callback or promisified
zlib.gzipSync on big datazlib.gzip, or a gzip stream
child_process.execSyncexec, spawn
A CPU loop over 1 million itemsChunking, worker threads (question 22)
JSON.parse of a 200 MB stringA streaming JSON parser
A regex with catastrophic backtracking on user inputA safer pattern, input limits (question 34)

How to know if something blocks: it returns its result directly rather than through a callback, promise or event, and it is not trivially fast. "Sync" in a Node.js function name is the clear signal.

Measuring it in production:

ts
import { monitorEventLoopDelay } from 'node:perf_hooks'

const delay = monitorEventLoopDelay({ resolution: 20 })
delay.enable()
setInterval(() => {
  metrics.gauge('event_loop_delay_p99_ms', delay.percentile(99) / 1e6)   // nanoseconds to ms
  delay.reset()
}, 10_000)

Event loop delay is how late timers fire compared with when they should. A p99 above about 100 ms means something is blocking the main thread.

11. What is concurrency, and how does Node.js handle it? ​

The short answer

Concurrency means making progress on many tasks in overlapping time periods; parallelism means running several tasks at the very same instant on different CPU cores. Node.js gives you concurrency on one thread: thousands of requests can be in flight, each waiting on I/O, while the event loop runs whichever callbacks are ready, one at a time. For parallelism, Node.js uses its thread pool internally, and you add more with worker threads, multiple processes or more containers.

The difference in one picture. A single chef cooking ten dishes, starting the pasta, then chopping while it boils, is concurrent. Five chefs each cooking a dish at the same time is parallel.

ConcurrencyParallelism
MeaningMany tasks in progressMany tasks executing at the same instant
NeedsOne thread is enough, with non-blocking I/OSeveral cores and threads or processes
Node.js gets it fromThe event loopThread pool, worker threads, cluster, containers
Helps withWaiting: network, diskComputing: CPU-heavy work

Concurrency in code:

ts
app.get('/dashboard', async (req, res) => {
  const [orders, stock, alerts] = await Promise.all([      // three requests in flight at once
    ordersApi.recent(req.user.id),
    stockApi.lowStock(),
    alertsApi.open(),
  ])
  res.json({ orders, stock, alerts })
})

While this request waits on three services, hundreds of other requests are handled on the same thread.

Limits of concurrency to watch: database connection pools, outgoing HTTP connection limits, the libuv thread pool size, and the memory each in-flight request holds. A server can accept more concurrent requests than its dependencies can serve, so add timeouts and limits (question 99).

12. What is the Event Loop in Node.js? ​

The short answer

The event loop is the loop, run by libuv on Node.js's main thread, that decides which callback runs next. It goes through a fixed set of phases over and over: run expired timers, run pending system callbacks, wait for and run I/O callbacks, run setImmediate callbacks, and run close callbacks. Between every callback, Node.js empties the process.nextTick queue and then the promise microtask queue. The loop keeps the process alive while there is pending work, and exits when there is nothing left to wait for.

The same idea as in the browser, with more detail. The general event loop is explained in the JavaScript module (question 60). Node.js's version, built on libuv, divides the task queue into phases with a specific order (question 13).

Why a Node.js process stays running, or exits:

ts
const server = app.listen(3000)          // an open server handle keeps the loop alive
setTimeout(() => {}, 5000)               // a pending timer keeps it alive for 5 seconds

const t = setInterval(sendHeartbeat, 1000)
t.unref()                                // (1) this timer alone will not keep the process alive
  1. unref() tells the loop not to count this handle. If nothing else is pending, the process exits even though the interval exists. Useful for background metrics timers.

What blocks the loop: any synchronous code that takes long, because the loop cannot move to the next phase until the current callback returns (question 21).

13. What are the phases of the Node.js Event Loop? ​

The short answer

Each turn of the loop goes through six phases in order. Timers runs setTimeout and setInterval callbacks whose time has passed. Pending callbacks runs some deferred system callbacks, such as certain TCP errors. Idle and prepare are internal. Poll waits for new I/O events and runs their callbacks, such as data arriving on a socket or a file read finishing. Check runs setImmediate callbacks. Close callbacks runs 'close' handlers, such as a socket closing. After each individual callback, the nextTick queue and then the promise queue are drained.

① timerssetTimeout, setInterval② pending callbacksdeferred system errors③ idle, prepare: internal④ pollwait for I/O, run its callbacks⑤ checksetImmediate⑥ close callbackssocket.on('close')after every callback1. process.nextTick queue2. promise microtasks
Six phases, in a fixed order. Each phase runs the callbacks queued for it. Between any two callbacks, Node.js first empties the nextTick queue and then the promise queue.
PhaseRunsExample
① TimersExpired timer callbackssetTimeout(fn, 100) after 100 ms or more
② Pending callbacksSome system callbacks deferred from the last turnA TCP ECONNREFUSED on some systems
③ Idle, prepareInternal to Node.js
④ PollNew I/O events; waits here if nothing else is scheduledSocket data, finished file reads, incoming connections
⑤ ChecksetImmediate callbacksWork to run right after I/O
⑥ Close callbacks'close' eventssocket.on('close')

Where your code usually runs: most request handling runs in the poll phase, because it is triggered by data arriving on a socket. Promise continuations from await then run as microtasks right after.

How the poll phase decides how long to wait: if timers are due soon, it waits only until then; if setImmediate callbacks are queued, it does not wait at all; otherwise it blocks, using no CPU, until an I/O event arrives.

14. What is the execution order of process.nextTick(), Promise callbacks, setTimeout(), and setImmediate()? ​

The short answer

Synchronous code runs first. Then, before the loop moves on, Node.js empties the process.nextTick queue, then the promise microtask queue. After that, the loop continues with its phases: setTimeout callbacks run in the timers phase, setImmediate callbacks in the check phase. So in a CommonJS file the usual order is sync code, nextTick, promises, then the timer and the immediate, whose relative order at the top level depends on timing. Inside an I/O callback, setImmediate always runs before setTimeout(…, 0).

ts
// order.cjs
console.log('1 sync start')

setTimeout(() => console.log('5 or 6 timeout'), 0)
setImmediate(() => console.log('5 or 6 immediate'))

Promise.resolve().then(() => console.log('4 promise'))
process.nextTick(() => console.log('3 nextTick'))

console.log('2 sync end')

Running node order.cjs prints 1, 2, 3, 4, then timeout and immediate in either order.

① sync1, 2② nextTick3③ promises4④ timers phase: timeout④ check phase: immediateat the top level, either can come first;inside an I/O callback, immediate always wins
Sync, then ticks, then promises, then the loop. ① Synchronous code. ② Every nextTick callback. ③ Every promise callback. ④ Then the loop's phases, where the timeout and the immediate run.

Why timeout versus immediate is uncertain at the top level: a setTimeout(fn, 0) is really at least 1 ms. When the loop starts, it checks the timers phase first. If that first millisecond has already passed, which depends on how busy the machine is, the timeout runs first; if not, the loop moves on to the check phase and the immediate runs first.

Inside an I/O callback, the order is fixed:

ts
import { readFile } from 'node:fs'
readFile(__filename, () => {
  setTimeout(() => console.log('timeout'), 0)
  setImmediate(() => console.log('immediate'))
})
// always: immediate, timeout

The callback runs in the poll phase. The next phase is check, so the immediate runs; the timeout waits for the next turn's timers phase.

A subtlety with ES modules: in an .mjs file, the top-level code itself runs as part of a promise job, so promise callbacks queued there can run before nextTick callbacks. If an interviewer's puzzle surprises you, ask whether the file is CommonJS or an ES module.

15. What is the difference between process.nextTick() and setImmediate()? ​

The short answer

process.nextTick(fn) runs fn as soon as the current operation finishes, before the event loop continues and even before promise callbacks; it is not part of the event loop's phases at all. setImmediate(fn) runs fn in the check phase of the loop, after I/O callbacks have had their turn. The names are confusing: nextTick is the more immediate one. Because nextTick runs before any I/O, many recursive nextTick calls can starve the loop, while setImmediate cannot.

process.nextTicksetImmediate
RunsRight after the current operationIn the check phase of the loop
Before promises?Yes, in CommonJSNo
Before I/O callbacks?YesAfter the poll phase
Can starve I/O if recursiveYesNo
Typical useMake an API consistently asynchronous; emit an event after the constructor returnsYield to the loop between chunks of work

The classic legitimate use of nextTick: letting the caller attach a listener before an event fires.

ts
import { EventEmitter } from 'node:events'

class Connection extends EventEmitter {
  constructor(public url: string) {
    super()
    process.nextTick(() => this.emit('ready'))       // (1)
  }
}

const conn = new Connection('postgres://…')
conn.on('ready', () => console.log('ready'))          // (2) registered in time
  1. Emitting inside the constructor directly would fire before the caller had a chance to subscribe. nextTick defers it until right after the current synchronous code.
  2. The listener is attached before the deferred emit runs.

Starvation:

ts
function spin() { process.nextTick(spin) }
spin()                                   // the loop never reaches I/O again: the server freezes

Rule of thumb: prefer queueMicrotask or promises for "after this", and setImmediate for "let the loop breathe first". Use nextTick only when you specifically need it.

16. What is the difference between setTimeout(fn, 0) and setImmediate()? ​

The short answer

Both schedule fn to run soon on the event loop, but in different phases. setTimeout(fn, 0) runs in the timers phase once at least 1 millisecond has passed. setImmediate(fn) runs in the check phase, straight after the current poll phase. From the main module their order is not guaranteed; from inside an I/O callback, setImmediate always runs first. Use setImmediate when you want to run something after the current I/O work, without an artificial delay.

setTimeout(fn, 0)setImmediate(fn)
PhaseTimersCheck
Minimum delay1 ms; 0 becomes 1None
Order at top levelNot guaranteed versus setImmediateNot guaranteed
Order inside an I/O callbackNext loop turnThis loop turn: first
Available in browsersYesNo, Node.js only

Using setImmediate to keep a server responsive while processing a big batch:

ts
async function processInChunks<T>(items: T[], handle: (item: T) => void, chunk = 1000) {
  for (let i = 0; i < items.length; i += chunk) {
    items.slice(i, i + chunk).forEach(handle)
    await new Promise((r) => setImmediate(r))        // let I/O callbacks run between chunks
  }
}

Each pause lets the loop run its poll phase, so incoming requests are served between chunks (question 65).

17. How do timers work in Node.js? ​

The short answer

setTimeout(fn, ms) asks for fn to run once after at least ms milliseconds, and setInterval(fn, ms) asks for it to run repeatedly with that gap. They are minimums, not guarantees: a timer only fires in the timers phase, so if the main thread is busy, it fires late. Each call returns a Timeout object you can clear with clearTimeout or clearInterval, and unref() so it does not keep the process alive. node:timers/promises offers promise-based versions for use with await.

ts
import { setTimeout as sleep, setInterval as every } from 'node:timers/promises'

const reminder = setTimeout(() => sendCartReminder(userId), 30 * 60 * 1000)   // (1)
clearTimeout(reminder)                                                      // (2)

const flush = setInterval(() => metrics.flush(), 10_000)
flush.unref()                                                               // (3)

await sleep(500)                                                            // (4)

for await (const _ of every(60_000, null, { signal: controller.signal })) { // (5)
  await syncStock()
}
  1. A one-off timer, here in 30 minutes. Keeping long timers in process memory is risky: they vanish on restart, so real reminders belong in a job queue.
  2. Cancel it if the user checks out first.
  3. A background interval that does not stop the process from exiting.
  4. A promise-based delay.
  5. A promise-based interval you loop over with for await, which stops cleanly when the signal is aborted (question 29).

Things that surprise people:

BehaviourDetail
Timers fire late under loadA busy main thread delays every timer
setInterval does not wait for async workIf syncStock takes 70 s with a 60 s interval, runs overlap; schedule the next run with setTimeout only after the current one finishes
Maximum delayAbout 24.8 days, 2³¹−1 ms; larger values fire after 1 ms with a warning
Thousands of timersFine: Node.js groups timers with the same duration efficiently

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Node.js
Runtime
Memory and debugging
Data and files
Process and packages
Other topics
Nothing picked yet