Courses / Node.js: From First Script to Production / Chapter 27
Module 11 · Mock interview · Chapter 27 of 27
Mock Interview: Five Timed Node.js Prompts with Model Answers
Builds on The Node.js Interview: Rounds, Scoring and a Study Plan, Asynchronous Programming: Callbacks, Promises and async/await, Building a Basic Web Server with node:http, Working with Databases: A REST API on PostgreSQL, Inside the Event Loop: Phases, Timers and setImmediate, process.nextTick, Promise Jobs and the Microtask Queue, The libuv Thread Pool and Blocking Work, Streams in Depth: Custom Streams, Backpressure and Pipelines, V8 Memory, Garbage Collection and Leaks, Profiling Node: CPU Profiles, Flame Graphs and Load Tests, Caching and Background Jobs in Node Services, Testing Node Code with node:test, Observability: Structured Logs, Metrics and Traces, Scaling and Deploying: Statelessness, Graceful Shutdown and Containers and Predict the Output: Timed Event Loop and Async Drills.
Part 1 · How to run this mock
Five prompts, five time boxes
The mock is five prompts, each with a time box, a model answer and a rubric. They run from a spoken explanation to a live coding task, a debugging case and a design discussion. None of them is a copy of an exercise from the other chapters, so you cannot answer from memory and have to use the method from the first chapter of this course.
| Prompt | Form | Time box | What it exercises |
|---|---|---|---|
| 1. A request that awaits a query | Explain aloud | 7 minutes | The path of a request through the event loop |
| 2. Timers and promises | Predict and explain | 8 minutes | The order of timers, promise jobs and await |
| 3. A thousand URLs, ten at a time | Live coding | 20 minutes | Bounded concurrency, timeouts, error handling |
| 4. The p99 that jumped | Debugging | 10 minutes | Reading a loop delay and a CPU profile |
| 5. Ten lakh rows into PostgreSQL | Design | 15 minutes | Streams, backpressure, batching, safe retries |
FormExplain aloud
Time box7 minutes
The rubric
Every prompt is scored on the same five criteria as the interview chapter, each from 1 to 4. The first table repeats them with what a 1 and a 4 look like, so you can score yourself without guessing. The rubric is this course's own and is not a claim about any employer. It follows the shape of public rubrics such as the Tech Interview Handbook, which name four criteria, communication, problem solving, technical competency and testing, and score each at four levels from strong no hire to strong hire.
| Criterion | What it covers | A 1 looks like | A 4 looks like |
|---|---|---|---|
| Runtime knowledge | what Node does underneath: the event loop and its queues, the thread pool, streams, memory | Says "Node is async" or "single-threaded" without saying what runs where; cannot name a queue or a phase | Names the queue or thread involved at each step, states the exceptions, and says what is not guaranteed |
| Async correctness | order, concurrency and failure in async code you write or read | Predicts the wrong order, forgets an await, starts unbounded work or loses an error | Predicts orders from the queues, bounds concurrency, handles every rejection and keeps results in order |
| Code quality | small readable code that refuses bad input and was run | Code does not run, or takes bad input without any check | Small functions with clear names, bad input refused with clear errors, and the code run to check it |
| Production judgement | limits, timeouts, memory, retries, measurement and shutdown | Ignores limits and failure, and guesses at performance | Sets limits and timeouts, measures before changing, plans retries and shutdown, and names what to monitor |
Scoring yourself
When the timer rings, stop typing. Score each of the five criteria from 1 to 4 for what you actually produced. A prompt then scores out of 20, and the five prompts together out of 100. A prompt total of 16 or more is a strong answer under the clock, 12 to 15 is solid, and below 12 is a prompt to repeat after you have revisited the chapters named in the score sheet at the end.
Then list your two lowest rows and pick one habit for the next prompt. If Communication is low, narrate the first minute out loud. If Code quality is low, run the code before you call it done. If Production judgement is low, say the limit and the timeout before you write the loop. Only after scoring should you read the model answer, and compare decisions rather than code: what did the answer assume, which queue or thread did it name, what did it measure?
Every model answer here was run. The code is unchanged from the files that produced the output shown, and the numbers come from runs on this machine. Timings vary on every run, so each timing is given as a range over several runs or as one run labelled as such, and none is used to rank two approaches from a single run.
| Term | Meaning |
|---|---|
| Time box | A fixed amount of time for a task; you stop when it ends |
| Rubric | A list of criteria with a description of each score |
| Model answer | One worked answer to compare your own attempt against |
Why is each score 1 to 4 and not a pass or fail?
- A number per criterion shows which skill to practise next. A pass or fail hides that a strong coder may be weak at explaining.
You score 3, 2, 4, 2, 2 on a prompt. What do you do next?
- The total is 13, which is solid. Repeat the lowest rows: pick one habit for each, such as stating limits first, and revisit the chapters the score sheet names.
Part 2 · Prompts 1 and 2 (15 minutes)
Prompt 1: a request that awaits a query
Time box: 7 minutes, spoken. A client sends GET /prices/sku-42 to a Node server. The handler awaits a database query before it replies. Describe, in order, what happens from the request arriving to the response leaving, and say what the process does for other clients while the query is out.
Model answer. The request starts as bytes arriving on a TCP socket. The operating system tells the loop that the socket is readable, and the loop reaches that event in its poll phase. Node's HTTP parser, running on the main thread, reads the request line and headers and emits a request event. That event is a callback, so the handler runs on the main thread, to completion, until its first await.
The handler calls the database driver, which writes the query to its own socket and returns a pending promise. Writing to a socket does not wait for the answer. The await suspends the function and the call stack empties. Nothing is blocked, and no thread sits waiting for this query: the wait is a socket the operating system is watching.
The loop goes back to poll, so a second client's request can be parsed and its handler started in the same way. When the database replies, its socket becomes readable, the driver's callback runs in poll and resolves the promise, and the rest of the handler runs as a promise job. It builds the response and calls res.end, which writes to the client socket. The thread pool is not involved at any point on this path, because network I/O uses the operating system's readiness mechanism, not pool threads.
Prompt 1: a run and the rubric
The run below checks the claim that no thread waits for the query. A server handler awaits a 500 ms timer, which stands in for the query, and 300 clients call it at once. The server records the most requests waiting together and, on Linux, reads the number of threads in the process from /proc at that moment.
const server = http.createServer(async (req, res) => { waiting++; if (waiting > peak) { peak = waiting; threadsAtPeak = threads(); } await sleep(500); // stands in for a database query waiting--; res.end('ok'); });
m1-threads.mjs, the server
threads before any request: 7 most requests waiting at once: 300 threads at that moment: 7
Node 24.18.0 on Linux (WSL). The same three lines in 20 runs.
Three hundred requests were waiting at the same moment, and the process had the same seven threads as before the first request. Waiting costs a socket and a few objects, not a thread. The seven threads are helpers that Node starts itself, and none was added for a request.
| Criterion | What a 3 needs here |
|---|---|
| Runtime knowledge | Names the poll phase, the parser and the request callback on the main thread; says the wait is a socket, not a blocked thread |
| Async correctness | Says the handler runs to completion up to the await, and resumes as a promise job after the reply |
| Code quality | Each step is one short sentence naming one thing that happens, so a listener could draw it |
| Production judgement | Notes that the pool is not used for sockets, and that one slow synchronous step in a handler would delay every other client |
| Communication | Answers in order, names what is not guaranteed, and checks the answer against a small run |
Prompt 2: timers and promises
Time box: 8 minutes. Read the script, write the exact output without running it, and explain each step. Then run it. Two workers wait for different times, a promise chain is queued, and the main body logs last.
import { setTimeout as sleep } from 'node:timers/promises'; async function worker(name, ms) { console.log(`${name} start`); await sleep(ms); console.log(`${name} after ${ms} ms`); await null; console.log(`${name} end`); } worker('A', 20); worker('B', 10); Promise.resolve().then(() => console.log('then')); console.log('main done');
m2-mixed.mjs
Model answer. The prediction is in the output below. The reasoning goes in four steps. First, the synchronous work: worker('A') runs until its first await, so A start prints, and the same for B start. The then callback is queued. main done prints last of the synchronous lines.
Second, the script ends, so the promise job runs and prints then. Third, nothing else is ready, so the loop waits in poll for the earliest timer. The 10 ms timer is due first, so B after 10 ms prints, and B's await null makes the next line a promise job that runs before the loop moves on, so B end follows at once. Fourth, 10 ms later the 20 ms timer fires and A finishes the same way. The timers decide the order of A and B, so the code does not depend on a race.
A start B start main done then B after 10 ms B end A after 20 ms A end
Node 24.18.0. The same eight lines in 20 runs, on Windows and on Linux.
| Criterion | What a 3 needs here |
|---|---|
| Runtime knowledge | Says that timers wait in the timers phase and the loop sleeps in poll until one is due |
| Async correctness | Gets all eight lines in order, with then before the timers and B end straight after B after 10 ms |
| Code quality | Writes the full output before running, in a form that can be checked line by line |
Part 3 · Prompt 3 (20 minutes): live coding
The prompt and a plan
Time box: 20 minutes. Write fetchAll(urls, { limit, timeoutMs }). It fetches every URL, never has more than limit requests in flight, gives up on a request after timeoutMs, and returns one result per URL in the same order as the input. One failing URL must not stop the rest. Use fetch and no libraries. You are given a local server where item n answers in 5 ms, every 50th item is slow (300 ms) and every 97th returns a 500.
Clarify before you code, and say your assumptions aloud. Here: a result is { ok: true, n } or { ok: false, error }; a non-2xx status counts as a failure, because fetch only rejects on network errors and timeouts; no retries; the timeout covers the whole request including reading the body.
A plan in one breath: a shared index and limit workers. Each worker loops: take the next index, fetch, store the result at that index, and repeat until the indexes run out. Storing by index keeps the order, and Promise.all over the workers waits for all of them. Because JavaScript runs one callback at a time, next++ is safe: there is no await between reading and incrementing the index, so two workers can never take the same one.
The slip to avoid is Promise.all(urls.map(fetch)). It starts every request at once, so limit means nothing. The run below shows what that does to the server.
The model solution
This is the whole function, 24 lines. The try block covers the fetch and the body read, so the timeout applies to both. AbortSignal.timeout creates a signal that aborts after the given time, and the error it causes has the name TimeoutError.
export async function fetchAll(urls, { limit, timeoutMs }) { const results = new Array(urls.length); let next = 0; async function worker() { while (next < urls.length) { const i = next++; try { const res = await fetch(urls[i], { signal: AbortSignal.timeout(timeoutMs), }); const body = await res.json(); results[i] = res.ok ? { ok: true, n: body.n } : { ok: false, error: `status ${res.status}` }; } catch (err) { results[i] = { ok: false, error: err.name }; } } } await Promise.all(Array.from({ length: limit }, worker)); return results; }
m3-fetch-all.mjs
Three decisions are worth saying aloud. The error is recorded in the result and not rethrown, so one failure cannot reject the whole call. A new signal is created for each request, so every request gets its own deadline. And the workers are plain async functions started with Array.from, so the limit is just the number of workers.
Running it, and the rubric
The check calls fetchAll on 1,000 URLs with a limit of 10 and a timeout of 150 ms. By the server's rules, 20 requests should time out (every 50th, which takes 300 ms) and 10 should return a 500 (every 97th), leaving 970 successes. The server counts how many requests are in flight at its peak.
limit 10: { ok: 970, TimeoutError: 20, 'status 500': 10 } server peak in flight: 10 order kept: true took 2135 ms
Node 24.18.0 on Windows, one of six runs. The server and client run in one process.
The counts matched in all six runs, and the server's peak in flight was 10 each time. The total time was 2,135 to 2,307 ms across the six runs on this machine. One run on Linux (WSL) gave the same counts and peak in 1,303 ms. The same call without a limit, with a longer timeout of 2,000 ms so that requests could finish, was run five times with the server in a separate process. The two runs shown are the first two.
Without the limit, and the rubric
unbounded: { fulfilled: 1000 }
server peak in flight: 68
unbounded: { fulfilled: 1000 }
server peak in flight: 80Unbounded Promise.allSettled, 1,000 requests, timeout 2,000 ms, two runs.
The server's peak was 68 and 80 in the runs shown, and 69, 94 and 97 in the other three, so it varies, but it is far above 10 and nothing bounds it. With the original 150 ms timeout, all 1,000 requests timed out in each of four runs and the server saw none of them in time. The clock starts when fetch is called, so a flood can use up the timeout before the work begins. That is probably because the client needed longer than 150 ms to start 1,000 requests, but the run does not prove the cause.
| Criterion | What a 3 needs here |
|---|---|
| Runtime knowledge | Explains that sockets are not threads and that the limit protects the server and the client alike |
| Async correctness | Bounded workers, results stored by index, every rejection handled, body read inside the try |
| Code quality | Short function, bad statuses and timeouts reported as results, and the code run on the 1,000 URLs |
| Production judgement | Gives a timeout per request, does not retry blindly, and names what it would add: a retry with backoff for 5xx and a total deadline |
| Communication | Clarifies the result shape and the status policy first, then explains why next++ is safe |
Why is next++ safe when several workers share the index?
- JavaScript runs one callback at a time and there is no
awaitbetween reading and incrementing the index, so two workers cannot take the same index.
Why does the solution store each result at results[i] and not push it?
Part 4 · Prompt 4 (10 minutes): debugging
The prompt and the evidence
Time box: 10 minutes. A service keeps a catalogue of 2 lakh items in memory, and GET /cheapest returns the five cheapest. After a release, the p99 latency of that route went from about 1 ms to hundreds of milliseconds, with no change in traffic. You are given two pieces of evidence and not the code. Say what is wrong, how you know, and what you would change. Then say how you would confirm the fix.
First, load-test results for the two versions, three runs each, 10 connections for five seconds on this machine. The loop delay is the p99 of the event loop delay histogram that Node reports, with a resolution of 10 ms, so an idle process reads close to the resolution: about 10 ms on Linux and about 15 ms on Windows.
v1: 21851 req/s, p50 0 ms, p99 1 ms, loop delay p99 10.8 ms v1: 22395 req/s, p50 0 ms, p99 1 ms, loop delay p99 10.7 ms v1: 17903 req/s, p50 0 ms, p99 1 ms, loop delay p99 10.9 ms v2: 16 req/s, p50 578 ms, p99 840 ms, loop delay p99 773.3 ms v2: 16 req/s, p50 620 ms, p99 772 ms, loop delay p99 701.5 ms v2: 17 req/s, p50 555 ms, p99 759 ms, loop delay p99 665.3 ms
autocannon 9.0.0 against each version; v2 is the release.
Second, a CPU profile of the release under the same load, taken with --cpu-prof. A short script lists the functions with the most self time, which is the time spent in the function itself and not in what it calls.
52% cheapest m4b-app.mjs:16 43% byPrice m4b-app.mjs:13 1% (garbage collector) :0 1% (program) :0 0% (anonymous) m4b-app.mjs:1
Self time by function, v2 under load.
Pause here and write your diagnosis before you read on.
The model answer
The loop delay is the key. In each v2 run it is close to the p99 latency: 665 to 773 ms against 759 to 840 ms. If a database or a downstream service were slow, requests would wait but the loop would stay healthy near 10 ms, as it does in v1. A loop delay that high means something is running on the main thread for hundreds of milliseconds at a time, and every request queues behind it.
The profile says what. Almost all the self time is in two places: cheapest and byPrice, a small function that compares two items and is the callback of a sort. A comparison function like this is normally the callback of a sort, so the release probably sorts something large on every request. At 16 to 17 requests per second, each request costs about 60 ms of main-thread time, and ten connections wait behind each other. Throughput fell from about 18,000 to 22,000 requests per second to about 16.
const byPrice = (a, b) => a.paise - b.paise; const sorted = VERSION === 'v1' ? [...catalogue].sort(byPrice) : null; function cheapest(n) { const list = sorted ?? [...catalogue].sort(byPrice); return list.slice(0, n); }
m4b-app.mjs, v1 sorts once at start-up, v2 sorts a copy per request
The fix is to sort once when the data is loaded (v1 does) and again only when the data changes, never per request. If the data changes often, a single pass that keeps the five smallest items needs no sort at all; its speed was not measured here, so it is an option to name, not a claim. To confirm the fix, run the same load test and expect the p99 and the loop delay to drop back to the first rows. The v1 rows in the table above are that measurement of the fixed code: p99 of 1 ms and a loop delay of 10.7 to 10.9 ms. A deeper answer adds a guard: alert on loop delay, since latency alone does not say whether the cause is the loop or something downstream.
Wrong answers and the rubric
Three tempting answers are wrong. Raising the thread pool size does nothing, since the stall is on the main thread and not in the pool. Adding instances hides the bug and multiplies the cost. Blaming the database ignores the loop delay, which shows the process, not the database, is the one that is busy. A good answer rules these out in a sentence each before it settles on the cause.
| Criterion | What a 3 needs here |
|---|---|
| Runtime knowledge | Reads a loop delay near the latency as a blocked main thread, and a healthy loop as a slow dependency |
| Async correctness | Explains that one synchronous call holds the main thread, so every other request waits, whatever the traffic |
| Code quality | Proposes sorting once when the data loads, with a refresh when it changes, and not a per-request sort |
| Production judgement | Says to measure again with the same load, and to monitor the loop delay as a health signal |
| Communication | States the diagnosis first, then the evidence for it from the two readings, then the fix |
Why does a loop delay close to the p99 latency point to the process itself?
- Requests wait for the main thread. A slow downstream service would delay the responses but leave the loop delay near its baseline.
What does self time in a profile tell you that total time does not?
- It shows where the function itself spends time, not time spent in the functions it calls, so it points at the code that does the work.
A profile of a slow route shows 43 percent self time in a function that compares two items. What do you look for in the code?
Part 5 · Prompt 5 (15 minutes): design, and the score sheet
The prompt and the answer
Time box: 15 minutes, a design discussion. Staff upload a CSV of 10 lakh orders to your Node API. Design the import into PostgreSQL so the service never runs out of memory, bad rows are reported and do not stop the import, and a retry after a crash is safe. Sketch the code for the core.
Model answer, in the order of the method. Clarify first: how big is a row, is one bad row a reason to stop, and does the user wait for the result. Assume about 40 bytes a row, bad rows are skipped and reported, and the user gets an answer at once and checks progress later. So the request returns 202 and a job id, and the import runs as a background job, as in the caching chapter.
The pipeline is a chain of streams. Read the file as a stream, split chunks into lines while keeping the partial line at the end of each chunk, validate each line, group valid rows into batches of 5,000, and insert each batch with one statement. Backpressure comes free from pipeline: the last step awaits each insert before it asks for more, so the reader only reads as fast as the database accepts.
Three design points carry the safety. The table has a primary key on the order id and the insert says on conflict do nothing, so running the whole file again after a crash adds only what is missing. A batch inserts through unnest with one array per column, so the statement has four parameters however large the batch. And progress is a counter the job updates, which the status endpoint reads. The faster bulk path worth naming is PostgreSQL's COPY, but how it reports bad rows differs, so it is a next step to check against its documentation, not part of this answer.
The core, run
The first block is the line splitter and the validator. Both are async generators, which pipeline accepts as stages. The validator counts bad rows and keeps two examples, and continue skips them without stopping the stream. The split on commas handles plain CSV only; a file with quoted fields that contain commas needs a CSV parser library in the same position, as the streams chapter said.
async function* lines(source) { let tail = ''; for await (const chunk of source) { const parts = (tail + chunk).split('\n'); tail = parts.pop(); yield* parts; } if (tail) yield tail; } async function* validate(source) { let first = true; for await (const line of source) { if (first) { first = false; continue; } // header stats.read++; const [id, customer, phone, amount, ...extra] = line.split(','); const paise = Number(amount); const good = !extra.length && customer && Number.isInteger(paise) && paise > 0; if (!good) { if (stats.bad++ < 2) stats.samples.push(line); continue; } yield { id: Number(id), customer, phone, paise }; } }
m5-import.mjs, lines and validate
The next block groups rows, inserts a batch, and wires the stages. The pool has two connections, one more than the single insert in flight needs.
async function* batches(source) { let rows = []; for await (const row of source) { rows.push(row); if (rows.length === BATCH) { yield rows; rows = []; } } if (rows.length) yield rows; }
m5-import.mjs, batches
async function save(source) { for await (const rows of source) { const r = await pool.query( `insert into imported (id, customer, phone, amount_paise) select * from unnest($1::int[], $2::text[], $3::text[], $4::int[]) on conflict (id) do nothing`, [rows.map((x) => x.id), rows.map((x) => x.customer), rows.map((x) => x.phone), rows.map((x) => x.paise)], ); stats.inserted += r.rowCount; stats.peakRss = Math.max(stats.peakRss, process.memoryUsage().rss); if (stats.read % 200_000 < BATCH) { console.log(`read ${stats.read}, saved ${stats.inserted}`); } } }
m5-import.mjs, save
await pipeline( createReadStream(file, { encoding: 'utf8' }), lines, validate, batches, save, );
m5-import.mjs, the pipeline
Evidence and the rubric
The file has 10 lakh rows, 36.6 MB, with every thousandth row bad. PostgreSQL ran in a separate process, which is PGlite behind a socket, so the numbers below belong to the importer alone. The second run is the retry after a crash.
$ node m5-import.mjs orders.csv read 200200, saved 200000 read 400400, saved 400000 read 600600, saved 600000 read 800800, saved 800000 read 1000000, saved 999000 read 1000000, rejected 1000, saved 999000 rejected: 1000,Divya 1000,0100001000,abc rejected: 2000,,0100002000,10000 peak rss 231 MB, took 7 s $ node m5-import.mjs orders.csv (again) read 1000000, rejected 1000, saved 0 rejected: 1000,Divya 1000,0100001000,abc rejected: 2000,,0100002000,10000 peak rss 231 MB, took 5 s
Node 24.18.0 on this machine; the times vary.
The first run saved 9,99,000 rows and rejected 1,000, with the two examples shown. The second run read the same file, rejected the same rows and saved none, because every id was already there. Memory needs care in the claim. The importer's peak rss was 125 to 127 MB on a file of 1 lakh rows over seven runs, and 218 to 233 MB on the full file over ten runs. A version that reads the whole file first peaked at 123 to 135 MB on the small file over five runs and at 426 to 428 MB on the full file over five runs. So the importer's memory is not flat, but it grows much less. A stronger check limits the heap.
$ node --max-old-space-size=64 m5-import.mjs orders.csv exit code: 0 peak rss 189 MB, took 4 s $ node --max-old-space-size=64 m5-naive.mjs orders.csv exit code: 134
The importer finishes with a 64 MB old-space limit; the naive version aborts. On Windows, in two runs of each: the importer peaked at 189 and 193 MB, and the naive version exited with code 134 both times.
| Criterion | What a 3 needs here |
|---|---|
| Runtime knowledge | Streams the file, splits lines across chunk boundaries, and explains that backpressure comes from awaiting each insert |
| Async correctness | Awaits every insert inside the pipeline, handles errors with pipeline, and does not fire inserts unbounded |
| Code quality | Skips and counts bad rows with examples, parameterised SQL, batches with one array per column |
The score sheet and what to revisit
Fill in one row per prompt, with a score from 1 to 4 in each column, and add them up. A prompt total of 16 or more is strong, 12 to 15 is solid, and below 12 is a prompt to repeat. Then add up each column across the five prompts, out of 20. The two lowest columns are what to revisit.
| Prompt | Runtime knowledge | Async correctness | Code quality | Production judgement | Communication | Total /20 |
|---|---|---|---|---|---|---|
| 1. A request that awaits a query | ||||||
| 2. Timers and promises | ||||||
| 3. A thousand URLs, ten at a time | ||||||
| 4. The p99 that jumped | ||||||
| 5. Ten lakh rows into PostgreSQL |
All chapters · Previous: Predict the Output: Timed Event Loop and Async Drills