Node.js Interview Questions

A focused Node.js study set covering asynchronous execution, modules, streams, middleware, and production service design.

Explained Node.js questions

How does the Node.js event loop work, and how do nextTick, promises, and setImmediate differ?

JavaScript callbacks run on the event-loop thread. Node.js coordinates timers and I/O through libuv; the main loop phases include timers, pending callbacks, poll, check, and close callbacks. process.nextTick callbacks are drained before the promise microtask queue after the current operation. setImmediate callbacks run in the check phase, after poll. Exact ordering between a timer and setImmediate can depend on where they are scheduled, so avoid describing it as a universal fixed order.

Example

console.log('sync');
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
setImmediate(() => console.log('check phase'));
// sync, nextTick, promise, then setImmediate

Why it works

The current JavaScript stack finishes first. Node then drains its next-tick queue and promise jobs before returning to the event loop; setImmediate is scheduled for the check phase.

Common mistakes

  • Calling Node.js fully single-threaded: JavaScript callbacks run on one main thread, but the runtime and operating system also perform asynchronous work.
  • Claiming timers fire at an exact deadline; their callbacks become eligible after a threshold and may run later.
  • Recursively scheduling nextTick work, which can starve I/O.

Follow-up questions

  • What work uses the libuv thread pool?
  • How would you detect event-loop delay in production?

Real-world use

This model helps explain why synchronous CPU-heavy code slows unrelated requests in an API even when those requests are waiting on I/O.

Further reading: Node.js: The Node.js event loop

How do CommonJS and ECMAScript modules differ in Node.js?

CommonJS uses require() and module.exports; ECMAScript modules use import and export. ESM has static import declarations, supports top-level await, and is interpreted according to package type or file extension. Interoperability is possible, but resolution and default-export behavior differ, so a project should use a deliberate module configuration.

Example

// In a CommonJS file:
const { readFile: readFileCjs } = require('node:fs/promises');
module.exports = { readFile: readFileCjs };

// In a separate ESM file:
import { readFile as readFileEsm } from 'node:fs/promises';
export { readFileEsm as readFile };

Why it works

The syntax communicates different module-loading semantics. Static ESM imports can be analyzed before execution, while CommonJS dependencies are loaded through require calls at runtime.

Common mistakes

  • Assuming __dirname exists unchanged in every ESM file.
  • Mixing module systems without checking the package's type and Node.js version.

Follow-up questions

  • How can an ESM module obtain a path relative to its own file?
  • When can top-level await be useful or harmful?

Real-world use

Clear module boundaries make migrations, test isolation, and dependency analysis easier in long-lived services.

Further reading: Node.js: Modules · Node.js: ECMAScript modules

What is stream backpressure, and when would you use worker threads or child processes?

Streams process data incrementally instead of buffering an entire file or response. Backpressure is the signal that a writable destination cannot accept data as quickly as a readable source produces it; piping or awaiting drain-aware writes prevents unbounded memory growth. Worker threads suit CPU-intensive JavaScript that benefits from shared process memory. Child processes provide stronger isolation and can run separate programs, at the cost of process and communication overhead.

Example

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';

await pipeline(
  createReadStream('large-input.csv'),
  createWriteStream('copy.csv')
);

Why it works

pipeline propagates errors and coordinates flow control between streams. Choosing a worker or process based on CPU use and isolation avoids blocking request callbacks or overcomplicating I/O-bound code.

Common mistakes

  • Collecting a large stream into one in-memory buffer without a size limit.
  • Using worker threads for ordinary asynchronous file or network I/O.
  • Ignoring worker/process lifecycle, errors, and shutdown.

Follow-up questions

  • How would you bound a worker pool?
  • What should happen when a pipeline fails halfway through?

Real-world use

Use streaming for large uploads, exports, and proxy responses; isolate image processing or other CPU-heavy work from API request handling.

Further reading: Node.js: Streams · Node.js: Worker threads · Node.js: Child processes

How should Express middleware handle authentication, authorization, and errors?

Middleware runs in registration order and either ends the response, passes control with next(), or forwards an error with next(error). Authentication verifies a credential and establishes a trusted identity; authorization checks whether that identity may perform a specific action on a resource. Keep these checks explicit and place a final error handler after routes. Do not treat a decoded token or a client-supplied user ID as authorization by itself.

Example

app.get('/projects/:id', requireUser, async (req, res, next) => {
  try {
    const project = await projects.findById(req.params.id);
    if (!project || project.ownerId !== req.user.id) {
      return res.sendStatus(404);
    }
    res.json(project);
  } catch (error) {
    next(error);
  }
});

app.use((error, req, res, next) => {
  if (res.headersSent) return next(error);
  req.log?.error({ error }, 'request failed');
  res.status(500).json({ error: 'Request failed' });
});

Why it works

Separating identity verification from resource-level permission checks prevents an authenticated user from accessing another user's data. A central error handler keeps responses consistent without leaking internal details.

Common mistakes

  • Checking only that a user is signed in, not that the user owns or may access the resource.
  • Calling next() after sending a response.
  • Returning stack traces, credentials, or raw database messages to clients.

Follow-up questions

  • How would you validate and rotate session or token credentials?
  • How should an error handler behave after headers have been sent?

Real-world use

Apply authorization to every protected object lookup and log enough context for incident investigation without recording secrets.

Further reading: Express: Using middleware · Express: Error handling

How would you investigate a slow Node.js API and improve database performance safely?

Start with request traces and latency percentiles to identify whether time is spent in application code, a downstream service, or the database. Inspect query plans and slow-query data before changing indexes. Reuse a bounded connection pool, set query and request timeouts, and use caching only for data with a clear freshness and invalidation policy. For CPU-heavy work, measure event-loop delay and move suitable work to a bounded worker pool or separate service. Validate changes under representative load and watch errors, saturation, and tail latency.

Example

import { createPool } from 'mysql2/promise';

const pool = createPool({
  connectionLimit: 10,
  waitForConnections: true,
  queueLimit: 50,
});

const [rows] = await pool.execute(
  'SELECT id, status FROM orders WHERE customer_id = ? ORDER BY created_at DESC LIMIT ?',
  [customerId, pageSize]
);

Why it works

A bounded pool reuses database connections while limiting concurrent demand. A parameterized query avoids string-built SQL, and an index aligned with filtering and ordering can reduce work; the actual plan and workload must confirm that benefit.

Common mistakes

  • Adding indexes without checking write cost, storage, and the execution plan.
  • Opening a new database connection for every request or allowing an unlimited wait queue.
  • Caching private or rapidly changing data without a safe key and invalidation strategy.

Follow-up questions

  • How do you choose a pool limit across multiple application instances?
  • What metrics distinguish database saturation from event-loop blocking?

Real-world use

For a high-traffic service, combine bounded concurrency, measured query optimization, cache policy, and load tests before increasing infrastructure.

Further reading: Node.js: Diagnostics · OWASP: Database Security Cheat Sheet