Node.js & Express
Node.js runtime and event loop
Section titled “Node.js runtime and event loop”Q (basic): What is Node.js?
Say this (30 sec): Node.js is a JavaScript runtime built on Chrome’s V8 engine. It lets you run JS outside the browser. It uses an event-driven, non-blocking I/O model through a C library called libuv. So one thread can handle thousands of concurrent connections, because it never sits waiting for I/O.
Follow-ups they ask: “Is Node single-threaded?” Your JS runs on one thread, but Node itself is not. libuv has a thread pool, and V8 has its own GC threads.
Common wrong answer: “Node is a framework” or “Node is a language”. It is a runtime.
Q (basic): Is Node.js single-threaded?
Say this (30 sec): Your JavaScript runs on a single main thread, the event loop. Under the hood, libuv keeps a thread pool, 4 threads by default and configurable with UV_THREADPOOL_SIZE. It uses that pool for file system work, dns.lookup, crypto like pbkdf2/scrypt, and zlib. Network I/O does not use the pool. It uses OS mechanisms like epoll (Linux), kqueue (macOS), and IOCP (Windows).
Common wrong answer: “All async operations go to the thread pool.” No. TCP/HTTP sockets are handled by the OS’s non-blocking APIs, not by the pool.
Q (mid): Explain the event loop phases.
Say this (30 sec): Each loop iteration goes through phases, and each phase has a queue of callbacks:
- Timers:
setTimeout/setIntervalcallbacks whose time has passed. - Pending callbacks: some system-level I/O callbacks deferred from the previous loop (e.g. TCP errors).
- Idle/prepare: internal use only.
- Poll: gets new I/O events and runs their callbacks. If nothing else is scheduled, the loop can wait here.
- Check:
setImmediatecallbacks. - Close callbacks: e.g.
socket.on('close').
Between each callback, Node drains the process.nextTick queue first, then the Promise microtask queue.
Follow-ups they ask: “Where do Promises run?” In the microtask queue, which isn’t a phase. It’s drained after every callback.
Q (tricky): What's the output order?
Example:
console.log('1');setTimeout(() => console.log('timeout'), 0);setImmediate(() => console.log('immediate'));Promise.resolve().then(() => console.log('promise'));process.nextTick(() => console.log('nextTick'));console.log('2');Say this: 1, 2, nextTick, promise, then timeout and immediate. Synchronous code runs first, then nextTick, then Promise microtasks. The order of timeout vs immediate is not guaranteed in the main module, because it depends on whether 1 ms has passed when the loop starts. Inside an I/O callback, setImmediate always runs before setTimeout(0), because the check phase comes right after poll.
Common wrong answer: Saying timeout always comes before immediate.
Q (mid): process.nextTick vs setImmediate vs setTimeout(fn, 0)?
Say this (30 sec):
process.nextTickruns immediately after the current operation, before Promises and before the loop continues. It has the highest priority.setImmediateruns in the check phase of the current or next loop iteration.setTimeout(fn, 0)runs in the timers phase after at least about 1 ms.
The names are confusing: nextTick is actually more “immediate” than setImmediate.
Follow-ups they ask: “Danger of nextTick?” Calling nextTick recursively starves the event loop, so I/O never gets processed. The Node docs recommend setImmediate in most cases.
Q (basic): What does "blocking the event loop" mean? Give examples.
Say this (30 sec): While synchronous code is running, no other request can be served, because there’s only one JS thread. Examples: fs.readFileSync in a request handler, a CPU-heavy loop, JSON.parse of a huge payload, synchronous bcrypt.hashSync, catastrophic regex backtracking (ReDoS), or sorting a huge array.
Fixes: use async APIs, split work into chunks with setImmediate, move CPU work to worker threads or a job queue (e.g. BullMQ), and stream big payloads.
Q (mid): Worker threads vs cluster vs child_process?
Say this (30 sec):
- worker_threads: threads inside the same process, each with its own V8 isolate and event loop. They can share memory through
SharedArrayBuffer. Use them for CPU-heavy work like image processing or hashing. - cluster: forks multiple processes that share the same server port. Use it to use all CPU cores for handling requests. In production, PM2 or running several containers usually does this job.
- child_process: runs a separate program (
spawn,exec,fork). For example, running FFmpeg from Node.
Common wrong answer: “Worker threads make I/O faster.” They don’t. I/O is already non-blocking. Workers help with CPU work.
Q (mid): spawn vs exec in child_process?
Say this: spawn streams stdout/stderr and doesn’t use a shell by default. It’s good for long-running or large-output processes like FFmpeg. exec runs the command in a shell and buffers the whole output into memory, with a maxBuffer limit. It’s fine for small commands, but it’s risky with user input because of shell injection.
Example:
const { spawn } = require('node:child_process');const ff = spawn('ffmpeg', ['-i', 'in.mp4', '-c:v', 'libx264', 'out.mp4']);ff.stderr.on('data', d => console.log(d.toString())); // ffmpeg logs to stderrff.on('close', code => console.log('exit', code));Streams and buffers
Section titled “Streams and buffers”Q (basic): What is a Buffer?
Say this: A Buffer is a fixed-size chunk of raw binary memory that lives outside the V8 heap. Node uses it for binary data such as files, network packets, and images. Buffer is a subclass of Uint8Array. Create one with Buffer.from('hi') or Buffer.alloc(10).
Follow-ups they ask: “Buffer.alloc vs Buffer.allocUnsafe?” allocUnsafe skips zero-filling, so it’s faster, but it may contain old memory data.
Q (mid): What are streams? What types exist?
Say this (30 sec): Streams process data piece by piece instead of loading it all into memory. There are four types:
- Readable: e.g.
fs.createReadStream, orreqin an HTTP server - Writable: e.g.
fs.createWriteStream, orres - Duplex: both readable and writable, e.g. a TCP socket
- Transform: a duplex stream that changes data as it passes through, e.g.
zlib.createGzip()
Example use: serving a 2 GB video file without using 2 GB of RAM.
Example:
const { pipeline } = require('node:stream/promises');await pipeline(fs.createReadStream('big.log'), zlib.createGzip(), fs.createWriteStream('big.log.gz'));Q (tricky): What is backpressure?
Say this (30 sec): Backpressure happens when the writable side is slower than the readable side. writable.write() returns false when its internal buffer goes past highWaterMark. You should then stop writing and wait for the 'drain' event. pipe() and pipeline() do this for you. Prefer pipeline, because it also forwards errors and cleans up all streams. Plain .pipe() does not forward errors.
Error handling
Section titled “Error handling”Q (basic): How do you handle errors in sync vs async code?
Say this: For sync code and async/await, use try/catch. For Promises, use .catch(). For callbacks, use the error-first convention (err, data). For EventEmitters and streams, listen to 'error'. An unhandled 'error' event crashes the process.
Common wrong answer: Wrapping a callback-based async call in try/catch. It won’t catch the error, because the callback runs later on a different stack.
Q (mid): uncaughtException and unhandledRejection: what should you do in them?
Say this (30 sec): These are last-resort global handlers. Since Node 15, an unhandled promise rejection crashes the process by default. In uncaughtException, the app is in an unknown state, so log the error, clean up, and exit with process.exit(1). Let a process manager like PM2, Docker, or Kubernetes restart it. Don’t keep running as if nothing happened.
Example:
process.on('unhandledRejection', (reason) => { logger.error(reason); throw reason; });process.on('uncaughtException', (err) => { logger.fatal(err); process.exit(1); });Follow-ups they ask: “Graceful shutdown?” On SIGTERM: call server.close() to stop accepting connections, let in-flight requests finish, close DB pools, then exit.
Q (mid): Operational vs programmer errors?
Say this: Operational errors are expected runtime problems, like the DB being down, invalid user input, or a timeout. You handle them and return a proper status code. Programmer errors are bugs, like reading a property of undefined. You fix the code, and for crashes you restart the process.
Express
Section titled “Express”Q (basic): What is middleware in Express?
Say this (30 sec): Middleware is a function (req, res, next) that runs in the request–response cycle. It can read or modify req and res, end the response, or call next() to pass control on. Middleware runs in the order it’s registered. Common uses: body parsing, auth, logging, CORS, and rate limiting.
Example:
app.use(express.json());app.use((req, res, next) => { console.log(req.method, req.url); next(); });app.get('/me', requireAuth, (req, res) => res.json(req.user));Common wrong answer: Forgetting that if middleware neither sends a response nor calls next(), the request hangs.
Q (basic): Types of middleware?
Say this: Application-level (app.use), router-level (router.use), built-in (express.json, express.static, express.urlencoded), third-party (cors, helmet, morgan), and error-handling middleware (4 arguments).
Q (mid): How does error-handling middleware work?
Say this (30 sec): It has four parameters (err, req, res, next). Express identifies it by its arity, so you must declare all 4 even if you don’t use next. Register it after all routes. When you call next(err), Express skips the normal middleware and goes to the error handler.
Example:
app.use((err, req, res, next) => { const status = err.status || 500; res.status(status).json({ error: status === 500 ? 'Internal error' : err.message });});Follow-ups they ask: “Async errors?” In Express 4, a rejected promise in an async handler is not caught. You need try/catch plus next(err), or a wrapper like express-async-errors. Express 5 (stable since late 2024) forwards rejected promises to next automatically.
Q (basic): app.use vs app.get? What's express.Router?
Say this: app.get matches only the GET method and the exact path pattern. app.use matches all methods and any path that starts with the given prefix. express.Router() is a mini app for grouping routes and middleware by module. You mount it with app.use('/api/users', userRouter).
Q (basic): req.params vs req.query vs req.body?
Say this: params come from the path pattern: /users/:id gives req.params.id. query comes from the query string: ?page=2 gives req.query.page, and it’s always a string. body is the request payload, and it’s only populated after a body parser like express.json() runs.
Q (mid): How do you handle file uploads in Express?
Say this (30 sec): Use multer, which parses multipart/form-data. Choose disk storage or memory storage. Always set limits (file size, number of files) and a fileFilter for MIME types. For production, a better pattern is to upload straight from the client to object storage (S3, R2, Cloudinary) using a presigned URL or signed upload. That way large files never go through your server.
Example:
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024 } });app.post('/avatar', upload.single('avatar'), (req, res) => { /* req.file.buffer */ });Common wrong answer: Trusting the client-sent MIME type or extension. Check magic bytes if security matters.
Q (mid): How do you validate request input?
Say this: Validate at the edge of your API with a schema library like zod. It gives runtime validation and TypeScript types from the same schema. On failure, return 400 (or 422) with the field errors.
Example:
const CreateUser = z.object({ email: z.string().email(), age: z.coerce.number().int().min(13) });const validate = (schema) => (req, res, next) => { const r = schema.safeParse(req.body); if (!r.success) return res.status(400).json({ errors: r.error.flatten() }); req.body = r.data; next();};app.post('/users', validate(CreateUser), handler);Follow-ups they ask: “Why validate on the server if the frontend validates?” Because anyone can call your API directly with curl or Postman. Client-side validation is only for UX.
Q (mid): How do you implement rate limiting?
Say this (30 sec): Use express-rate-limit, e.g. 100 requests per 15 minutes per IP. Return 429 Too Many Requests with a Retry-After header. With multiple server instances, an in-memory store doesn’t work because each instance counts separately, so use a Redis store. Common algorithms are fixed window, sliding window, and token bucket. Apply stricter limits on login and OTP routes. Behind a proxy, set app.set('trust proxy', 1) so you get the real client IP.
Q (basic): How do you manage environment config?
Say this: Keep config in environment variables (12-factor app). Locally, load .env with dotenv, or use Node 20.6+’s built-in --env-file=.env. Never commit .env. Commit a .env.example instead. Validate env at startup with zod so the app fails fast. In production, use the platform’s secret store, such as Wrangler secrets or Azure Key Vault.
Q (mid): How do you do logging in production?
Say this: Use a structured JSON logger like pino (fast) or winston, with log levels (error, warn, info, debug). Add a request ID to every log line so you can trace one request. Use morgan or pino-http for access logs. Never log passwords, tokens, or PII. Send logs to a central system like Grafana Loki, Datadog, or ELK.
Common wrong answer: “console.log everywhere”. It’s unstructured, has no levels, and is synchronous when writing to files or terminals.
Q (mid): What does helmet / cors do?
Say this: helmet sets security headers: Content-Security-Policy, X-Content-Type-Options, Strict-Transport-Security, and others. cors sets Access-Control-Allow-Origin and related headers, so browsers allow cross-origin requests from origins you choose. CORS is a browser rule. It does not protect your API from curl.
REST API design
Section titled “REST API design”Q (basic): What makes an API RESTful?
Say this (30 sec): Resources are nouns in URLs (/users/42/posts), HTTP methods are the verbs, the server is stateless (each request carries everything it needs, like a token), it uses proper status codes, and responses can be cached. Example: GET /posts, POST /posts, GET /posts/:id, PATCH /posts/:id, DELETE /posts/:id.
Common wrong answer: POST /createPost or GET /deleteUser?id=1. Those are verbs in URLs, and the second one uses GET to change data.
Q (basic): Key HTTP status codes?
Say this:
- 200 OK, 201 Created (send it with a
Locationheader), 204 No Content (e.g. after a DELETE) - 301/308 Permanent redirect, 302/307 Temporary redirect, 304 Not Modified (caching)
- 400 Bad Request, 401 Unauthorized (actually means unauthenticated), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict (e.g. duplicate email), 422 Unprocessable Content (validation), 429 Too Many Requests
- 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout
Common wrong answer: Mixing up 401 and 403. 401 = not logged in or bad token. 403 = logged in but no permission.
Q (mid): What is idempotency? Which methods are idempotent?
Say this (30 sec): A method is idempotent if calling it N times has the same effect on the server as calling it once. GET, HEAD, PUT, DELETE, OPTIONS are idempotent. POST is not, because two POSTs create two orders. PATCH is not guaranteed to be idempotent (e.g. { op: "increment" }). Safe methods (GET, HEAD, OPTIONS) don’t change state at all.
Follow-ups they ask: “How do you make POST safe to retry, e.g. payments?” Use an Idempotency-Key header. The server stores the key with the result and returns the same result for a repeated key.
Common wrong answer: “DELETE isn’t idempotent because the second call returns 404.” Idempotency is about server state, not the response code.
Q (basic): PUT vs PATCH?
Say this: PUT replaces the whole resource with the payload. Fields you leave out are removed or reset. It’s idempotent. PATCH partially updates only the fields you send. In practice, most “update profile” endpoints should be PATCH.
Q (mid): Offset vs cursor pagination?
Say this (30 sec): Offset: ?page=3&limit=20 becomes LIMIT 20 OFFSET 40. It’s simple and you can jump to any page. But it gets slow for deep pages, because the DB still scans the skipped rows, and items shift if new rows are inserted. Cursor (keyset): ?after=<lastId>&limit=20 becomes WHERE id < $last ORDER BY id DESC LIMIT 20. It’s fast because it uses an index and stays stable for feeds, but you can’t jump to page N. Use cursor pagination for infinite-scroll feeds.
Q (mid): How do you version an API?
Say this: URL versioning (/api/v1/...) is the most common and the easiest to see. Alternatives are a header (Accept: application/vnd.app.v2+json) or a query param. Make only additive, non-breaking changes within a version.
Q (mid): How would you structure an Express project?
Say this: Use layers: routes (URL to handler), controllers (HTTP in/out), services (business logic), and data access/repositories (ORM queries), plus middlewares/, config/, and utils/. This keeps business logic testable without HTTP. Use a central error handler and validation at the routes.