One waiter (the JS thread) serves many tables. He doesn’t stand at the kitchen waiting for food: he takes an order, hands it to the kitchen (the OS / thread pool for I/O), and serves other tables. When food is ready, he’s notified. That works great for waiting-heavy work (database, network), terribly for CPU-heavy work where the waiter himself has to cook.
Say it like this in the interview
“JavaScript runs on one thread with an event loop, while I/O is non-blocking and handled by the OS and libuv’s thread pool. So Node handles many concurrent I/O-bound requests efficiently. CPU-heavy work like image processing or big JSON parsing blocks the loop for everyone, so I move it to worker threads, a separate service, or a queue.”
They will probably ask next
“How would you use all CPU cores?” Cluster mode / PM2 or multiple containers behind a load balancer.
app.get('/report', (req, res) => {
const data = fs.readFileSync('big.json');
const parsed = JSON.parse(data);
const result = heavyCalculation(parsed); // 3 seconds of CPU
res.json(result);
});
In simple words
This endpoint makes the one waiter cook a 3-second meal himself. During that time nobody else gets served.
Say it like this in the interview
“It blocks the event loop: synchronous file read plus CPU-heavy work. I’d use async fs.promises, move the calculation to a worker thread or background job, cache the result, and stream large files. To detect it I monitor event loop lag with perf_hooks.monitorEventLoopDelay or APM tools.”
“Streams process data incrementally, keeping memory constant for large files, uploads, CSV exports and proxies. pipeline connects them and handles errors and backpressure, meaning a fast producer is slowed down for a slow consumer.”
Each turn of the loop visits stations in order: run due timers, finish some leftover system callbacks, wait for and handle I/O (poll), run setImmediate callbacks (check), then close callbacks. Promise callbacks run between every step.
Say it like this in the interview
“libuv phases: timers (setTimeout/setInterval), pending callbacks, idle/prepare (internal), poll (retrieve I/O events, may block waiting), check (setImmediate), close callbacks. process.nextTick and promise microtasks drain after each callback, before the loop moves on.”
process.nextTick jumps to the very front of the line, even before promises. setImmediate runs in the check phase, usually after timers when called from the main module, but the timer vs immediate order there is not guaranteed.
Say it like this in the interview
“sync, nextTick, promise, then timeout and immediate, whose relative order isn’t guaranteed from the main module. Inside an I/O callback, setImmediate always runs before the timeout.”
In a request handler, the sync call freezes the whole server for every user while the file is read.
Say it like this in the interview
“Sync APIs block the event loop. In a one-off script nothing else is waiting, so it’s fine and simpler. In a server, every concurrent request stalls. Use fs.promises there, and read static config once at startup.”
Older Express doesn’t catch errors from async functions, so a rejected promise escapes the safety net. The request never gets a response, or Node crashes on an unhandled rejection.
Say it like this in the interview
“In Express 4, rejected promises aren’t passed to the error middleware. I wrap handlers with try/catch and next(err) or an asyncHandler wrapper, or use Express 5, which forwards rejected promises automatically. Then a central error middleware (err, req, res, next) logs and returns a clean response. I also handle unhandledRejection for logging, then let the process restart.”
Middleware are checkpoints the request passes through in order: log it, parse the body, check the login, then reach the route. Each checkpoint either passes it on with next() or sends a response and stops.
“Functions with (req, res, next) that run in order for matching requests. They can modify request and response, end the cycle, or call next(). Order matters: body parsing before routes, error handlers last with four arguments.”
Traps that make people fail
Forgetting to call next() or return a response, so the request hangs.
Separate the layers: routes (URLs), controllers (HTTP in/out), services (business rules), and data access. Each layer has one job.
Say it like this in the interview
“Routes map URLs to controllers; controllers handle request and response; services contain business logic and are framework-agnostic; repositories handle the database. Plus validation middleware with Zod or Joi, central error handling, config from env, structured logging, and tests at the service and HTTP levels. Grouped by feature for larger apps.”
“A schema library like Zod: safeParse the body, return 400 with field errors on failure, and use the parsed, typed data afterwards, never the raw body.”
Don’t load a 2GB file into memory. Stream it, or better, let the browser upload directly to cloud storage.
Say it like this in the interview
“Stream uploads with Busboy or Multer to disk or storage, enforce size and type limits, and validate content. For large files, presigned URLs so the client uploads directly to S3 or similar, and the API just records metadata. Then process in a background job.”
Session: the server keeps a list of who’s logged in and gives the browser a ticket number. Easy to log someone out: delete them from the list. JWT: the server gives a signed pass containing the user info; it doesn’t need a list, but you can’t easily cancel a pass before it expires.
Say it like this in the interview
“Sessions store state server-side, are easy to revoke, and work well with HttpOnly cookies. JWTs are stateless, signed tokens, convenient across services, but revocation is hard, so I keep them short-lived with refresh tokens. For a typical web app, I’d use secure cookie sessions; for service-to-service or mobile, short-lived JWTs. Never store tokens in localStorage if XSS is a risk.”
A short-lived access pass (minutes) for each request, and a long-lived refresh pass (days) kept safely, used only to get new access passes. If one leaks, damage is limited.
Say it like this in the interview
“Short-lived access JWTs, about 15 minutes, plus long-lived opaque refresh tokens stored server-side and in secure device storage. Refresh token rotation: each use issues a new one and invalidates the old; reuse of an old token signals theft and revokes the whole family. Logout revokes server-side.”
Secrets (database passwords, API keys) never go in the code or Git. They’re given to the app from outside through environment variables.
Say it like this in the interview
“Environment variables, loaded from .env only in development (Node has --env-file built in now), validated at startup with a schema so the app fails fast if one is missing. In production, secrets come from the platform’s secret manager. .env is git-ignored and I keep a .env.example without values.”
Slow attackers down: limit attempts per IP and per account, add delays, and alert.
Say it like this in the interview
“Rate limiting per IP and per username, ideally in Redis so it works across instances, with exponential backoff or temporary lockouts; CAPTCHA or bot detection after several failures; generic error messages so attackers can’t enumerate accounts; 2FA; logging and alerts; and a WAF at the edge.”
After an unexpected crash-level error, the app’s state may be broken. The safe move is: log it, stop accepting work, finish what you can, exit, and let the process manager restart it.
Say it like this in the interview
“Register uncaughtException and unhandledRejection handlers only to log with context and exit gracefully; never keep running in an unknown state. A supervisor like Kubernetes, PM2 or systemd restarts it. Prevent them by handling errors in async code and using central error middleware.”
When the server is told to stop (during deploys), it should stop taking new requests, finish the ones in progress, close database connections, then exit.
“Listen for SIGTERM and SIGINT, call server.close() to stop accepting connections, wait for in-flight requests, close DB pools and queues, then exit, with a timeout to force exit if it hangs. Readiness probes should fail first so the load balancer stops sending traffic.”
Something keeps collecting objects and never lets them go. Take memory snapshots at two points in time and compare what grew.
Say it like this in the interview
“Confirm with metrics that heap grows over time. Take heap snapshots via --inspect or v8.writeHeapSnapshot() at intervals and compare retained objects in Chrome DevTools. Usual causes: unbounded in-memory caches or maps, listeners added per request, closures holding request objects, global arrays, unclosed timers. Fix and add a cache size limit or use Redis.”
Logs are how you understand what happened at 3am. Make them structured (JSON), consistent, and searchable, without passwords or personal data.
Say it like this in the interview
“Structured JSON logs with a fast logger like pino, log levels, a request ID on every line for tracing, errors with stack traces, no secrets or PII, and logs shipped to a central system. Plus metrics and traces via OpenTelemetry for the full picture.”
Cluster starts several copies of your whole server (one per CPU core) sharing the same port, so you handle more requests. Worker threads run heavy calculations in the background inside one server.
Say it like this in the interview
“Cluster forks processes, each with its own event loop and memory, sharing a port; it scales request throughput across cores, as PM2 does. In containers I usually run one process per container and scale horizontally instead. worker_threads share a process and can share memory via SharedArrayBuffer; they’re for CPU-bound tasks without blocking the main loop.”
Store the result in a fast memory store (Redis) with an expiry. Next time, return the stored result instead of querying again.
Say it like this in the interview
“Cache-aside with Redis: check the key, return on hit, otherwise query, store with a TTL, return. Invalidate or update the key when the data changes. I add jitter to TTLs and request coalescing to prevent a stampede when hot keys expire.”
Push the job (send email, resize image) to a queue; separate worker processes pick it up and do it, retrying if it fails.
Say it like this in the interview
“BullMQ with Redis, or a managed queue like SQS. Producers enqueue jobs with IDs; workers process them with concurrency limits, retries with backoff, and dead-letter handling. Jobs must be idempotent. Workers run as separate processes so they scale independently.”
When the producer is faster than the consumer (reading a fast disk, uploading to a slow network), data piles up in memory. Backpressure is the consumer saying “slow down”.
Say it like this in the interview
“When writable.write() returns false, the internal buffer exceeded highWaterMark; the producer should pause until drain. pipe and pipeline handle this automatically. Ignoring it causes memory growth and crashes under load.”
Opening a database connection is slow. A pool keeps a few connections open and lends them out to requests, then takes them back.
Say it like this in the interview
“A pool reuses a bounded set of connections, avoiding connection setup per query and protecting the database from too many connections. I size it based on database limits and number of instances. In serverless environments I use a pooler like PgBouncer or the provider’s proxy.”
Validate everything that comes in, limit how much and how often people can call you, keep secrets out of code, and keep dependencies updated.
Say it like this in the interview
“Input validation, parameterised queries, authentication and per-resource authorisation, rate limiting, Helmet for security headers, strict CORS, body size limits, secrets in env or a secret manager, npm audit and Dependabot, avoiding eval, and logging without sensitive data.”
The lock file records the exact version of every package installed, so everyone and every server installs exactly the same thing.
Say it like this in the interview
“The lock file pins the full dependency tree. npm ci installs exactly from it, fails if it’s out of sync with package.json, and starts clean, which makes it ideal for CI and Docker builds. Commit the lock file.”
__dirname and require only exist in CommonJS. ES modules use import.meta instead.
Say it like this in the interview
“ESM doesn’t have __dirname, __filename or require. In modern Node I use import.meta.dirname and import.meta.filename, or derive them from import.meta.url with fileURLToPath. For JSON, import attributes or fs.”
Start the app in tests and send real HTTP requests to it, using a test database, then check the responses.
Say it like this in the interview
“Integration tests with Supertest against the app instance, with Vitest or the built-in node:test, and a real test database in a container, reset between tests. Unit tests for services. External APIs mocked with nock or MSW.”