Skip to content

Interview PrepMemory and debugging · Advanced

Debugging and Profiling ​

34. How would you debug high CPU usage in a Node.js process? ​

The short answer

Confirm what you see first: one core at 100%, rising event loop delay, and latency rising across all endpoints point to JavaScript blocking the main thread. Then capture a CPU profile of the busy process, with --cpu-prof, the inspector, or a sampling profiler, and read it as a flame graph: the widest bars are the functions using the most CPU. Typical culprits are heavy loops or sorting, huge JSON.parse or stringify calls, slow regular expressions, synchronous crypto or compression, and garbage collection caused by too many allocations.

Step by step:

  1. Check which kind of CPU it is. One core at 100% means the main thread is busy. All cores busy may be the thread pool or garbage collection threads. Also check whether event loop delay rose at the same time (question 10).
  2. Find when it started: a deploy, a traffic change, a specific endpoint, or one big customer's data.
  3. Profile the busy process:
bash
# start with profiling; a .cpuprofile file is written when the process exits
node --cpu-prof --cpu-prof-dir=/tmp/profiles dist/server.js

# or attach to a running process without restarting (Linux, macOS)
kill -USR1 <pid>           # opens the inspector on 127.0.0.1:9229
# then chrome://inspect → Profiler → record 30 seconds
  1. Read the flame graph. Open the .cpuprofile in Chrome DevTools or a flame graph tool. Each bar is a function; width is time spent. Look for wide bars from your own code or from a library you call.
  2. Fix and measure again with the same load.

Usual culprits and fixes:

CulpritSign in the profileFix
Big synchronous loopsYour function at the top, wideMove to SQL, cache, chunk or a worker (question 22)
JSON.parse or stringify of huge payloadsJSON.parse wideSmaller responses, pagination, streaming
Regex with catastrophic backtrackingRegExp exec, wide, on certain inputsRewrite the pattern, limit input length
Synchronous crypto or zlibpbkdf2Sync, gzipSyncAsync versions or streams
Garbage collection(garbage collector) largeAllocate less in hot paths; check for leaks (question 33)
LoggingThe logger's serialisation wideLower log level, a faster logger such as Pino

A regex that eats CPU, a classic interview example of ReDoS, regular expression denial of service:

ts
const emailLike = /^([a-zA-Z0-9]+)*@shop\.example$/     // nested quantifier
emailLike.test('a'.repeat(30) + '!')                    // takes seconds: backtracking explodes

The nested (…+)* lets the engine try an enormous number of ways to split the input before giving up. Attackers send such input on purpose.

35. How do you profile a Node.js application? ​

The short answer

Decide what you are measuring, then use the matching tool. For CPU time, record a CPU profile with --cpu-prof or the inspector and read the flame graph. For memory, take heap snapshots or record an allocation timeline. For responsiveness, measure event loop delay with perf_hooks. For where time goes in a request across services, use tracing with OpenTelemetry. Always profile under realistic load, with a production build, and compare before and after each change.

QuestionTool
Which functions use the CPU?CPU profile: --cpu-prof, Chrome DevTools, 0x flame graphs
What is using memory? Is something leaking?Heap snapshots, allocation timeline (question 33)
Is the event loop blocked?perf_hooks.monitorEventLoopDelay (question 10)
How often and how long does garbage collection run?--trace-gc, PerformanceObserver for gc entries
Where does a slow request spend its time?Distributed tracing with OpenTelemetry
How does the service behave under load?A load generator: autocannon, k6

Measuring one piece of code in production:

ts
import { performance, PerformanceObserver } from 'node:perf_hooks'

new PerformanceObserver((list) => {
  for (const e of list.getEntries()) metrics.timing(e.name, e.duration)
}).observe({ entryTypes: ['measure'] })

async function buildInvoice(orderId: string) {
  performance.mark('invoice-start')
  const pdf = await renderPdf(orderId)
  performance.measure('invoice.render', 'invoice-start')       // duration since the mark
  return pdf
}

A load test before and after a change:

bash
npx autocannon -c 50 -d 30 http://localhost:3000/products   # 50 connections for 30 s

Compare requests per second and latency percentiles, especially p99, before and after your fix.

36. What are Async Hooks, and what are they used for? ​

The short answer

Async hooks are a low-level Node.js API, node:async_hooks, that tells you when asynchronous resources such as promises, timers and sockets are created and when their callbacks run, so tools can follow work across asynchronous boundaries. The raw createHook API is complex, adds overhead, and its use is discouraged. The part you should use is AsyncLocalStorage, built on the same idea, which keeps a value, such as a request ID or the current user, available to every function called during one request, including after await, without passing it as an argument.

ts
import { AsyncLocalStorage } from 'node:async_hooks'
import { randomUUID } from 'node:crypto'

type RequestContext = { requestId: string; userId?: string }
export const context = new AsyncLocalStorage<RequestContext>()           // (1)

app.use((req, res, next) => {
  const requestId = req.get('x-request-id') ?? randomUUID()
  res.set('x-request-id', requestId)
  context.run({ requestId, userId: req.user?.id }, next)                  // (2)
})

export function log(message: string, fields: Record<string, unknown> = {}) {
  const ctx = context.getStore()                                          // (3)
  logger.info({ ...fields, requestId: ctx?.requestId, userId: ctx?.userId }, message)
}

async function chargeCard(orderId: string) {
  await paymentApi.charge(orderId)
  log('card charged', { orderId })                                        // (4) has the request ID
}
  1. One store for the whole app.
  2. run starts a context for this request; everything called from next, however deep and however many awaits later, sees it.
  3. getStore() reads the current request's context.
  4. Deep in the code, logs automatically carry the request ID, without passing it through every function.

Where it is used: request IDs in logs, tracing libraries such as OpenTelemetry, per-request database transactions, and multi-tenant apps that need the current tenant everywhere.

Pitfalls: a context is lost if work is queued through a mechanism Node.js cannot follow, such as some old callback-based libraries or a custom pool of objects reused between requests. Test that logs from those paths still carry the ID.

37. What is the Node.js Inspector, and how do you debug an application with it? ​

The short answer

The inspector is Node.js's built-in debugging server, which speaks the same protocol as Chrome DevTools. Start Node.js with --inspect, or --inspect-brk to pause on the first line, then connect from Chrome at chrome://inspect or from VS Code. You can set breakpoints, step through code, inspect variables, watch the call stack, and record CPU profiles and heap snapshots. By default it listens only on 127.0.0.1:9229; exposing it to a network gives anyone full control of the process.

bash
node --inspect dist/server.js            # debug a running app
node --inspect-brk dist/server.js        # pause before the first line, to debug start-up
node --inspect=127.0.0.1:9230 app.js     # a different port

VS Code launch configuration for a TypeScript project:

json
{
  "type": "node",
  "request": "launch",
  "name": "Debug API",
  "program": "${workspaceFolder}/src/server.ts",
  "runtimeArgs": ["--enable-source-maps"],
  "skipFiles": ["<node_internals>/**"]
}

Useful techniques:

TechniqueWhen
Conditional breakpoint, such as orderId === 'A12'A bug that appears for one input among thousands
LogpointPrint a value without changing code or stopping
debugger; statementPause at a specific line when the inspector is attached
Pause on caught exceptionsFind where an error is first thrown
Async stack tracesSee the chain of awaits that led here

Debugging in a container: expose port 9229 only to your machine, for example with kubectl port-forward pod/api-7d9 9229:9229, and start the process with --inspect=0.0.0.0:9229 inside that one debug pod only. Never leave the inspector open in production: it allows running any code in the process.

38. What are source maps, and how do they help with debugging? ​

The short answer

A source map is a file that maps each position in compiled or bundled JavaScript back to the original source line, such as a line in your TypeScript. Without it, stack traces and breakpoints point at the compiled output, which is hard to read. With it, debuggers and error trackers show your real files and line numbers. In Node.js, compile with source maps enabled and run with --enable-source-maps, so stack traces in logs point at your .ts files.

json
// tsconfig.json
{ "compilerOptions": { "sourceMap": true, "outDir": "dist" } }
bash
node --enable-source-maps dist/server.js

Before and after:

text
Error: card declined
    at chargeCard (/app/dist/payments.js:41:15)        without source maps

Error: card declined
    at chargeCard (/app/src/payments.ts:27:11)         with source maps

Things to know:

PointDetail
CostStack traces with source maps are slower to build; fine for errors, not for stack traces in hot loops
Front-end appsUpload source maps to your error tracker instead of serving them publicly, if you do not want the source visible
BundlersVite, esbuild and webpack produce them with a setting (question 58)

39. What are native add-ons in Node.js? ​

The short answer

Native add-ons are modules written in C, C++ or Rust and compiled to machine code, which Node.js loads like a JavaScript module. They are used for speed, as in image processing with sharp, and to reach system libraries, as in better-sqlite3 or bcrypt. Modern add-ons use Node-API, a stable interface that keeps working across Node.js versions. The downsides: they must be compiled for each platform and processor, can crash the whole process with a native bug, and complicate Docker images and upgrades.

AspectDetail
Built withnode-gyp, cmake-js, or napi-rs for Rust
InterfaceNode-API: stable across Node.js versions
DistributionOften prebuilt binaries per OS and CPU; otherwise compiled at install
Common examplessharp, bcrypt, better-sqlite3, canvas

Problems you will meet:

  1. Install fails in a slim Docker image because compilers or system libraries are missing.
  2. Wrong architecture: node_modules installed on a Mac with an ARM chip, copied into an amd64 Linux container, crashes on start. Always install dependencies inside the image you run.
  3. A native crash, such as a segmentation fault, kills the process with no JavaScript stack trace.

Alternatives: a pure JavaScript library if speed allows, WebAssembly, which runs anywhere and is sandboxed, or a separate service.

40. What are Node.js domains, and why are they considered legacy? ​

The short answer

Domains, from node:domain, were an early attempt to catch errors from a group of related asynchronous operations in one place, so a crash in one request would not take down the whole server. They were deprecated because they were unreliable: errors could escape them, they hid the real state of the program after an error, and they slowed things down. Today you use promises with async/await and try/catch, central error-handling middleware, AsyncLocalStorage for request context, and process-level handlers only for logging and a clean exit.

Need domains tried to meetModern replacement
Catch errors from a chain of async callsasync/await with try/catch
Turn a request's error into a 500 responseFramework error middleware, such as Express's four-argument error handler
Keep per-request contextAsyncLocalStorage (question 36)
Avoid crashing on any errorHandle errors properly; restart crashed processes with a supervisor

The lesson behind it: after an unexpected error, the process may be in a broken state, such as a half-finished transaction or a leaked lock. Continuing to serve traffic is risky; logging, finishing in-flight requests and restarting is safer.

41. What is the REPL, and when is it useful? ​

The short answer

The REPL, read-eval-print loop, is the interactive Node.js prompt you get by running node with no file. You type JavaScript, it runs immediately and prints the result. It is useful for trying out an API, checking how a library behaves, testing a regular expression or a date calculation, and exploring data. It supports top-level await, tab completion, _ for the last result, and commands such as .help, .load and .editor.

text
$ node
> const items = [{ price: 3.5, qty: 2 }, { price: 8, qty: 1 }]
undefined
> items.reduce((sum, i) => sum + i.price * i.qty, 0)
15
> new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }).format(_)
'£15.00'
> _.length
6
> const { readFile } = await import('node:fs/promises')
undefined
> .exit

_ holds the last result, so the third line formats 15, and the fourth measures the string '£15.00'. The last line shows top-level await working at the prompt.

Uses beyond experiments: a project can start a custom REPL with its own modules preloaded, for example an admin console with the database client ready. That is powerful and dangerous: it runs with full access to production data, so it must be protected like a database shell, used rarely, and logged.

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