Information Technology
Node.js Interview Questions & Answers
JavaScript runtime environment optimized for building scalable network apps.
Advanced Node.js
All 15 questionslibuv is the C library underlying Node.js that provides the event loop, thread pool, and asynchronous I/O abstractions across operating systems -- it handles file system operations…
Running node --inspect (or --inspect-brk to pause on the first line) opens a WebSocket debugging port that Chrome DevTools or VS Code can attach to, exposing the CPU profiler, heap…
process.nextTick() queues a callback to run immediately after the current operation completes, before the event loop continues to any phase -- it has the highest priority and can s…
A diagnostic report (enabled via --report-uncaught-exception, --report-on-signal, or triggered programmatically) is a JSON snapshot of the process's state at a point in time -- inc…
- What is V8's hidden class mechanism, and why does it matter for writing performant Node.js code? Advanced
V8 optimizes object property access by internally assigning objects a 'hidden class' based on the shape (set and order of properties) of the object -- objects sharing the same shap…
Architecture & Design Patterns
All 15 questionsThe Module pattern uses each file's own function scope (whether via CommonJS's implicit wrapper function or ESM's module scope) to keep variables and functions private by default,…
- How is the Factory pattern commonly applied in Node.js applications, and what problem does it solve? Intermediate
A factory function or factory class centralizes object creation logic behind a single function, hiding the specific class or configuration details from the calling code -- useful w…
- What is the Singleton pattern, and what are the specific risks of using it in a Node.js application? Intermediate
A Singleton ensures only one instance of a class or module-level object exists and is shared across the entire application -- in Node.js this is trivially achieved because a requir…
A layered architecture separates an application into distinct responsibilities, commonly: the routing/controller layer (handling HTTP requests and responses), the service/business-…
The Repository pattern defines an abstraction (an interface or a consistent set of functions) for accessing and persisting domain objects, hiding the specific database technology a…
Async Patterns
All 15 questionsA callback is a function passed as an argument to another function, invoked once that function's asynchronous work completes -- Node's original core APIs (fs, http, etc.) are all b…
A Promise is an object representing the eventual result of an asynchronous operation, existing in exactly one of three states at any time: pending (the operation hasn't completed y…
- What is the difference between Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any()? Intermediate
Promise.all() resolves when every promise in the array resolves, but rejects immediately as soon as any single promise rejects (short-circuiting the rest). Promise.allSettled() alw…
- How does async/await relate to Promises under the hood, and what does 'await' actually do to program execution? Intermediate
async/await is syntactic sugar built directly on top of Promises -- an async function always implicitly returns a Promise, and 'await' pauses execution of that specific async funct…
Writing 'const a = await taskA(); const b = await taskB();' runs the two tasks sequentially -- taskB doesn't even start until taskA fully completes, wasting time when the tasks are…
Authentication & Authorization
All 15 questionsAuthentication verifies who a user is -- confirming their identity, typically through a username/password, a token, or a third-party identity provider. Authorization determines wha…
In session-based authentication, after a successful login the server creates a session record (containing the user's identity and any relevant data) stored server-side, and sends t…
A JWT is a compact, self-contained, digitally signed token used to represent claims (like a user's identity and permissions) that can be verified without needing a server-side look…
A single long-lived JWT, if stolen, remains valid and dangerous for its entire lifetime. Refresh token rotation instead issues a short-lived access token (minutes) alongside a long…
In the Authorization Code flow, a user is redirected to the authorization server (like Google) to log in and consent; the authorization server redirects back to the application wit…
Authentication & Authorization (JWT, OAuth, Passport)
All 5 questions- How do JWTs, OAuth, and Passport.js fit together in a typical Node.js authentication architecture? Intermediate
They operate at different layers: OAuth 2.0 is the protocol governing how a user grants a third-party application access without sharing their password directly; JWT is a token for…
Token introspection is a live call to the authorization server (via a defined OAuth endpoint) to ask 'is this token still valid, and what does it represent?' -- necessary for opaqu…
- How would you implement 'Sign in with GitHub' using Passport's OAuth strategy in an Express application? Intermediate
Using passport-github2 (or a similar strategy package), you register the strategy with your app's client ID and secret, define a callback that receives the authenticated GitHub pro…
PKCE adds a dynamically generated secret (a 'code verifier' and its hashed 'code challenge') to the Authorization Code flow, binding the initial authorization request to the specif…
- How do you validate a JWT's claims (issuer, audience, expiration) beyond just verifying its cryptographic signature? Intermediate
Verifying a JWT's signature alone only confirms it hasn't been tampered with and was signed by the expected key -- a complete verification also needs to check the 'exp' claim (has…
Background Jobs & Queues
All 15 questionsA background job is a unit of work executed outside the request/response cycle -- sending emails, generating reports, processing images -- so the HTTP response can return to the us…
- How does BullMQ (built on Redis) implement a job queue in Node.js, and what are its core building blocks? Intermediate
BullMQ uses Redis as a durable, shared broker between producers (application code adding jobs) and one or more worker processes (consuming and processing jobs) -- its core building…
- What is job idempotency, and why is it critical when designing background job processing? Intermediate
A job is idempotent if running it more than once produces the same end result as running it exactly once -- this matters because most queue systems provide 'at-least-once' delivery…
A dead-letter queue holds jobs that have permanently failed after exhausting all configured retry attempts, rather than discarding them silently -- this preserves the failed job's…
A cron job runs on a fixed, recurring schedule defined by a cron expression (minute, hour, day-of-month, month, day-of-week) -- in Node.js this can be implemented with a lightweigh…
Caching
All 15 questions- What is caching, and why is it commonly used to improve the performance of a Node.js application? Beginner
Caching stores the result of an expensive operation (a database query, an API call, a computed value) temporarily, so subsequent requests for the same data can be served from the f…
- What is the difference between in-memory caching (like a Map or node-cache) and a distributed cache (like Redis)? Intermediate
An in-memory cache lives entirely within a single Node.js process's memory -- extremely fast with no network overhead, but limited to that one process (useless once an application…
Time-to-live (TTL) expiration simply lets cached entries expire automatically after a fixed duration -- simple, but can serve stale data until expiration. Cache-aside (lazy loading…
Cache stampede occurs when a popular cached entry expires and many concurrent requests simultaneously discover the cache miss and all rush to recompute the same expensive underlyin…
Cache-Control specifies directives like max-age (how long a response can be cached) and public/private (whether shared caches like CDNs may store it); ETag provides a unique finger…
Caching with Redis
All 5 questionsThe node-redis package (v4+) provides a promise-based client -- you create a client with createClient(), specifying the connection URL, call connect() to establish the connection,…
Beyond simple key-value strings, Redis supports Hashes (field-value maps within a single key, efficient for representing an object like a user profile), Lists (ordered collections,…
A distributed lock uses Redis's atomic SET with the NX (only set if not exists) and EX (expiration) options to acquire a lock -- only one instance can successfully set the key, gua…
- How would you implement a simple rate limiter using Redis's INCR command with expiration? Intermediate
A fixed-window rate limiter increments a counter keyed by the client's identifier and current time window, setting an expiration on first creation of that key -- if the counter exc…
Redis Pub/Sub lets clients subscribe to named channels and receive messages published to those channels in real time -- useful for broadcasting an event (like a chat message or a l…
Child Processes & Process Management
All 5 questions- What are the four main methods for creating a child process in Node.js, and how do they differ? Beginner
spawn() launches a command and streams its stdout/stderr incrementally, suited for long-running processes or large output. exec() runs a command through a shell and buffers its ent…
- How does inter-process communication (IPC) work between a parent process and a child created with fork()? Intermediate
fork() automatically establishes a communication channel between the parent and child, letting both sides send and receive JSON-serializable messages via process.send() (in the chi…
Both exec() and execFile() support a 'timeout' option that automatically sends a kill signal to the child process if it hasn't completed within the specified duration; for spawn(),…
Each child process's stdout and stdin are Node.js streams, so you can use .pipe() directly to connect one process's stdout to another's stdin, replicating a shell pipeline like 'ca…
By default, a child process is tied to its parent's lifecycle in certain ways depending on the platform -- the { detached: true } option allows the child to continue running indepe…
CLI Tools & Scripting with Node.js
All 5 questionsA shebang line (#!/usr/bin/env node) tells Unix-like operating systems which interpreter should execute the file when it's run directly as a program (like ./my-script.js) rather th…
- How would you parse command-line arguments and flags in a Node.js CLI tool using a library like commander or yargs? Intermediate
Rather than manually parsing process.argv (which requires hand-written logic to distinguish flags, positional arguments, and their values), libraries like commander or yargs provid…
- How do you write cross-platform shell scripts in Node.js that work identically on Windows, macOS, and Linux? Intermediate
Rather than relying on OS-specific shell commands or path separators, cross-platform Node.js scripts use Node's built-in modules (fs, path) instead of shelling out to 'rm', 'cp', o…
Inquirer.js provides a set of prompt types (input, list/select, checkbox for multi-select, confirm) that render interactive terminal UI, collecting a structured object of answers a…
process.exitCode = n sets the exit code the process will use once it naturally finishes all pending work, without abruptly terminating the process (letting any pending I/O, like a…
Cloud & DevOps
All 15 questionsThe twelve-factor methodology is a set of best practices for cloud-native apps: storing configuration in environment variables (so the same build deploys unchanged across environme…
Kubernetes distinguishes liveness probes (is the process alive and not deadlocked? failing restarts the container) from readiness probes (is the instance ready for traffic right no…
- What is a CI/CD pipeline for a Node.js application, and what stages does a typical one include? Advanced
A typical pipeline includes: installing dependencies, running linters/type checks, running the test suite, building a production artifact (a Docker image), and deploying it to stag…
IaC defines cloud infrastructure in version-controlled configuration rather than manual console clicks, enabling reproducible, reviewable infrastructure changes. The AWS CDK lets t…
Horizontal scaling adds more instances behind a load balancer rather than making one instance more powerful -- this requires the application to be stateless: any instance must hand…
Clustering & Worker Threads
All 15 questions- Why does Node.js provide a cluster module, given that a single Node.js process is single-threaded? Intermediate
A single process runs JavaScript on one main thread, using only one CPU core -- the cluster module forks multiple worker processes (typically one per core), each an independent cop…
Each cluster worker is a separate OS process with its own memory -- an in-memory cache exists separately and inconsistently in each worker. The fix is moving shared state to an ext…
- How does PM2's cluster mode compare to manually using Node's built-in cluster module directly in application code? Intermediate
PM2's cluster mode achieves the same goal at the process-manager level, without needing cluster-aware application code, and additionally provides zero-downtime reloads, automatic r…
SharedArrayBuffer allocates memory multiple worker threads can access directly without copying -- writes from one thread are immediately visible to others, requiring careful synchr…
postMessage() sends data using the structured clone algorithm, supporting most types (objects, arrays, Maps, typed arrays) but not functions or DOM nodes -- transferable objects li…
Core Node.js Modules
All 15 questionsThe node: prefix explicitly signals a built-in core module rather than a third-party package -- introduced partly to remove ambiguity in module resolution and support scenarios whe…
util.inspect() converts a value into a formatted, human-readable string, including nested objects -- it's what console.log() uses internally (rather than JSON.stringify, which can'…
The path module provides platform-aware utilities -- join(), resolve(), dirname(), extname() -- that correctly handle the difference between path separators on different OSes, wher…
- What does the node:crypto module provide, and what's the difference between hashing and encryption? Intermediate
crypto provides hashing (createHash), symmetric/asymmetric encryption, HMAC signing, and secure random generation. Hashing is one-way, producing a fixed-size fingerprint that can't…
URL and URLSearchParams (globally available, matching the browser API) provide a complete, spec-compliant way to parse a URL and manipulate query strings, handling edge cases like…
Databases
All 15 questionsA relational database (PostgreSQL, MySQL) organizes data into structured tables with a fixed schema and enforces relationships via foreign keys, well suited for data with clear, st…
A connection pool maintains a set of already-established database connections that are reused across requests rather than opening and closing a new (relatively expensive to establi…
A transaction groups multiple database operations so they're treated as a single atomic unit -- either every operation within it commits successfully, or if any fails, the entire t…
SQL injection occurs when untrusted user input is concatenated directly into a SQL query string, letting an attacker craft input that changes the query's actual meaning (like appen…
An index is a separate data structure (commonly a B-tree) that the database maintains alongside a table, allowing it to look up rows matching a specific column value without scanni…
Databases & ORMs (MongoDB/Mongoose, SQL/Sequelize)
All 5 questionsMongoose is an Object Document Mapper (ODM) for MongoDB, adding schema definition and validation (MongoDB itself is schemaless by default), typed model classes with instance and st…
- How does Sequelize define models and relationships for a relational (SQL) database in Node.js? Intermediate
Sequelize defines models as JavaScript classes mapped to database tables, with each column's type and constraints declared explicitly, and relationships (one-to-many, many-to-many,…
The N+1 problem occurs when fetching a list of N parent records, then separately querying for each one's related data individually (N additional queries) instead of fetching everyt…
Sequelize's transaction() method wraps multiple operations so that either all of them commit together or, if any operation throws, all of them are automatically rolled back -- esse…
A migration is a version-controlled script describing an incremental change to a database schema (adding a column, creating a table, adding an index) -- migration tools track which…
Debugging & Diagnostics
All 5 questionsPlacing a 'debugger;' statement directly in code creates a programmatic breakpoint -- when the script is run with 'node --inspect-brk' and a debugger client (Chrome DevTools or VS…
- How do you use Node's built-in heap snapshot capability to diagnose a suspected memory leak? Intermediate
Node.js can generate a heap snapshot (a complete picture of all objects currently in memory and their retaining relationships) via the --heapsnapshot-signal flag, the inspector's M…
A source map maps locations in generated/compiled code back to the corresponding locations in the original source code -- without it, stack traces and debugger breakpoints for a Ty…
clinic doctor runs an application under load and produces a diagnostic report highlighting likely categories of problems (event loop blocking, I/O bottlenecks, memory issues) based…
The 'debug' package lets library and application code create namespaced debug loggers that are silent by default, only producing output when the DEBUG environment variable is set t…
Deployment & Process Managers (PM2)
All 5 questionsRunning 'node server.js' directly leaves the process with no automatic restart if it crashes, no built-in way to run multiple instances across CPU cores, no persistent log manageme…
- How do you configure PM2 using an ecosystem.config.js file rather than passing options directly on the command line? Intermediate
An ecosystem file defines one or more applications' configuration (script path, instance count, environment variables per environment, restart behavior, memory limits) in a single…
PM2 automatically captures each managed process's stdout and stderr into log files under ~/.pm2/logs by default, but without rotation these files grow indefinitely and can eventual…
- How do you configure PM2 to automatically restart your Node.js application after a server reboot? Intermediate
PM2's 'startup' command generates and configures a system-specific init script (systemd on most modern Linux distributions) that starts PM2 itself automatically on system boot; com…
'pm2 monit' provides a real-time terminal dashboard showing each managed process's CPU usage, memory usage, and a live tail of recent log output; PM2 Plus (a paid hosted service) e…
Docker & Containerization for Node.js
All 5 questionsA Dockerfile is a text file with sequential instructions describing how to build a Docker image -- for a Node.js app this typically means: starting from an official Node.js base im…
- What is a multi-stage Docker build, and how does it produce a smaller final image for a Node.js application? Intermediate
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an earlier stage can install build tools, dev dependencies, and compile/transpile code (like TypeScr…
- Why is it considered a security best practice to run a Node.js Docker container as a non-root user? Advanced
By default, a Docker container's process runs as root unless explicitly configured otherwise -- if an attacker manages to exploit a vulnerability in the application and achieve cod…
Rather than baking environment-specific configuration into the image itself, values are injected at container runtime via -e flags, an --env-file, or docker-compose.yml's environme…
Docker Compose defines multiple related services (the Node.js app, a PostgreSQL database, a Redis cache) in a single docker-compose.yml file, including their networking (services c…
Docker & Deployment
All 15 questionsA Dockerfile is a text file with step-by-step instructions for building a Docker image -- for a Node.js app, this typically means starting from an official Node base image, setting…
- What is a multi-stage Docker build, and why is it commonly used for Node.js applications? Intermediate
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an early stage (with full build tools, dev dependencies, and a compiler) builds or compiles the appl…
When Docker (or Kubernetes) stops a container, it sends SIGTERM and waits a grace period before forcibly sending SIGKILL -- a Node.js app must explicitly listen for SIGTERM and use…
- What is the difference between the CMD and ENTRYPOINT instructions in a Dockerfile for a Node.js application? Intermediate
ENTRYPOINT defines the fixed, primary command that always runs when the container starts, while CMD provides default arguments to that entrypoint (or, if ENTRYPOINT isn't set, CMD…
Running a container's process as root means that if an attacker manages to exploit a vulnerability in the application, they gain root-level access within the container, which combi…
Email & Notifications
All 15 questionsNodemailer is the most widely used Node.js library for sending email, supporting SMTP (talking directly to a mail server or provider like Gmail, SendGrid, or Amazon SES over the st…
Sending an email involves a network call to an external mail provider that can be slow or occasionally fail -- doing this synchronously inside a request handler makes the user wait…
SPF (Sender Policy Framework) publishes a DNS record listing which mail servers are authorized to send email on behalf of a domain, letting receiving servers verify a message wasn'…
- How would you send a push notification from a Node.js backend to a mobile app using Firebase Cloud Messaging (FCM)? Intermediate
The backend uses the Firebase Admin SDK, authenticated with a service account, to send a message targeting a specific device (via a registration token the client app previously obt…
A common approach defines a common Notification interface/abstraction and separate channel-specific adapters (EmailChannel, SmsChannel, PushChannel) each implementing a consistent…
Environment Variables & Configuration
All 5 questions- How does the dotenv package work, and what problem does it solve for local Node.js development? Beginner
dotenv reads key-value pairs from a local .env file and loads them into process.env at application startup, letting developers configure local environment variables (database URLs,…
Validating configuration eagerly at startup (using a schema validation library like zod, joi, or envalid) causes the application to fail fast with a clear error message immediately…
A common pattern centralizes all configuration access through a single config module that reads from process.env once at startup, provides sensible defaults for non-sensitive value…
Build-time configuration is baked into the application artifact when it's built (like a value substituted during a bundler's build step), meaning a different value requires rebuild…
Environment variables containing secrets (database passwords, API keys) can accidentally leak through overly broad logging (like logging the entire process.env object for debugging…
Error Handling
All 15 questionsOperational errors are expected, recoverable failures that arise from the runtime environment or external conditions (a failed network request, invalid user input, a database conne…
Extending the built-in Error class lets you attach additional context (an HTTP status code, an error code, whether the error is operational) and lets calling code distinguish error…
Express supports a special error-handling middleware signature (with four parameters: err, req, res, next) placed at the end of the middleware chain -- any error passed to next(err…
In Express 4 and earlier, if an async function passed as a route handler throws (or its returned promise rejects), Express's underlying error-handling doesn't automatically catch i…
4xx status codes indicate the client made a mistake (invalid input, missing authentication, requesting a nonexistent resource) -- these are typically operational errors that should…
Event Loop & Non-blocking IO
All 15 questionsThe event loop is the core mechanism that lets Node.js perform non-blocking I/O -- it continuously checks for completed asynchronous operations (a finished file read, an incoming n…
The event loop cycles through several phases each iteration: timers (executes callbacks scheduled by setTimeout/setInterval whose time has elapsed), pending callbacks (certain syst…
Non-blocking I/O means initiating an I/O operation (reading a file, querying a network resource) and immediately continuing to execute other code rather than pausing to wait for th…
Event loop lag measures the delay between when a scheduled callback (like a timer) should ideally fire and when it actually does, serving as a proxy for how 'busy' or blocked the e…
- How does setImmediate() differ from process.nextTick() in terms of timing and typical use cases? Intermediate
process.nextTick() schedules a callback to run at the very end of the current operation, before the event loop proceeds to any of its formal phases -- it has the highest possible p…
Events & EventEmitter
All 5 questions- How do you create a custom class that emits events by extending Node's built-in EventEmitter? Beginner
A class extends EventEmitter (from node:events) to inherit its .on(), .emit(), .once(), and .removeListener() methods, letting instances of that class emit named events at appropri…
- What happens when an EventEmitter emits an event that has an 'error' listener versus one that doesn't? Intermediate
The 'error' event is treated specially by EventEmitter -- if it's emitted and there is no registered listener for it, Node.js throws the error and, by default, crashes the process,…
By default, an EventEmitter instance warns (via a MaxListenersExceededWarning) if more than 10 listeners are added for the same event name -- this default limit exists specifically…
- How does the 'once' method differ from 'on' when subscribing to an EventEmitter's events, and when would you use it? Intermediate
.once() registers a listener that automatically removes itself after being invoked exactly one time, whereas .on() keeps a listener attached indefinitely, firing every time the eve…
emit() can pass any number of additional arguments after the event name, which are delivered as separate arguments to the listener function -- but the common and generally recommen…
Express & Middleware
All 15 questionsExpress is a minimal, unopinionated web framework built on top of Node's core http module, providing routing (mapping URLs and HTTP methods to handler functions), middleware compos…
- What is middleware in Express, and what is the significance of the order in which middleware is registered? Intermediate
Middleware functions receive the request, response, and a 'next' callback, executed in the exact order they're registered via app.use() or as route-specific handlers -- order matte…
An async middleware function performs its await-based work and then calls next() to continue the chain, or next(err) to forward an error -- because Express (pre-v5) doesn't automat…
- What is the difference between application-level, router-level, and route-specific middleware in Express? Intermediate
Application-level middleware (app.use()) applies to every request reaching the app (or matching a specified path prefix). Router-level middleware works the same way but is scoped t…
Validation middleware defines an expected schema for the request body, query parameters, or route parameters, validates the incoming request against it before the route handler run…
File System & File Processing
All 15 questionsfs.readFile() reads an entire file into memory at once before invoking its callback with the complete contents -- simple, but problematic for large files since the whole file must…
fs.readdir() with the 'recursive' option (Node 20+) returns every file and subdirectory path within a directory tree in one call, or for finer control (like filtering or processing…
fs.watch() monitors a file or directory for changes, emitting events when something is modified, renamed, or removed -- but its behavior is notoriously inconsistent across operatin…
- How would you safely check if a file exists in Node.js before attempting to read it, avoiding a race condition? Intermediate
Rather than checking existence with fs.access() or fs.exists() and then separately attempting to read the file (a pattern vulnerable to a race condition -- a TOCTOU, time-of-check…
A direct write to a file's final path risks leaving it partially written (corrupted) if the process crashes or is killed mid-operation -- the standard atomic-write pattern instead…
File System (fs) Module
All 5 questionsEvery core fs operation is available in three forms: a synchronous version (like fs.readFileSync, which blocks the entire event loop until it completes -- appropriate only for star…
fs.createReadStream() reads a file incrementally in chunks, emitting 'data' events (or usable via .pipe() or async iteration) as each chunk becomes available, rather than buffering…
fs.watch() emits events ('change', 'rename') when the watched file or directory is modified, but its behavior is notoriously inconsistent across operating systems -- the specific e…
Every open file, network socket, or pipe consumes a file descriptor, and the operating system imposes a limit on how many a single process can have open simultaneously (often 1024…
fs.rename() performs an atomic move operation when the source and destination are on the same filesystem -- the file appears to move instantly with no window where it exists in nei…
File Uploads & Media Processing
All 15 questionsmultipart/form-data is the HTTP content type browsers use to submit forms containing file uploads, encoding each form field (including file contents) as a separate 'part' within th…
multer accepts a 'fileFilter' function to reject files based on their reported MIME type or extension before they're even fully processed, and a 'limits' option to cap the maximum…
sharp is a high-performance image-processing library built on the native libvips library, dramatically faster and more memory-efficient than pure-JavaScript image manipulation for…
Rather than having the client upload a file to your Node.js server, which then re-uploads it to S3 (doubling bandwidth usage and tying up server resources for the duration of poten…
Rather than using multer's disk storage (which writes the complete file to disk first) you can use multer's memory storage for smaller files, or for genuinely large files, use a li…
Git & Project Management
All 15 questionspackage-lock.json records the exact resolved version of every installed dependency (including nested transitive dependencies), ensuring that running 'npm install' produces byte-for…
A monorepo houses multiple related, independently versionable packages (a shared library, a backend API, a frontend app) within a single Git repository, rather than splitting them…
Git hooks are scripts that run automatically at specific points in the Git workflow (before a commit, before a push) -- Husky is a popular tool that makes configuring these hooks s…
Semantic versioning uses a MAJOR.MINOR.PATCH format, where a PATCH increment indicates a backward-compatible bug fix, a MINOR increment indicates new backward-compatible functional…
Conventional Commits is a specification for structuring commit messages with a type prefix (feat, fix, docs, chore, BREAKING CHANGE, and others) followed by a concise description -…
Global Objects & the process Object
All 5 questionsprocess is a global object providing information about, and control over, the currently running Node.js process -- commonly used members include process.env (environment variables)…
- What is the difference between __dirname/__filename in CommonJS and their equivalents in ES Modules? Intermediate
In CommonJS, __dirname and __filename are automatically available in every module, providing the absolute path to the current file's directory and the file itself. ES Modules don't…
- What is process.memoryUsage(), and how would you use it to monitor a Node.js application's memory consumption? Intermediate
process.memoryUsage() returns an object describing the current process's memory usage across several categories: rss (Resident Set Size, total memory allocated for the process incl…
process.on('SIGTERM', ...) and process.on('SIGINT', ...) let an application intercept termination signals sent by an orchestrator (SIGTERM, typically during a deployment or scale-d…
Buffer is a global class (no require() needed) for working with raw binary data directly, predating and complementing JavaScript's later-added standard TypedArray classes -- like p…
GraphQL
All 15 questionsGraphQL is a query language and runtime for APIs where the client specifies exactly which fields it needs in a single request, and the server returns precisely that shape of data -…
- How would you set up a basic GraphQL server in Node.js using Apollo Server, defining a schema and resolvers? Intermediate
Apollo Server requires a GraphQL schema (defined using the Schema Definition Language, describing available types, queries, and mutations) and a corresponding set of resolver funct…
Because each field in a GraphQL query has its own independent resolver, a query returning a list of parent objects (like 100 posts) followed by each post's author field naturally t…
- What is the difference between a GraphQL Query, Mutation, and Subscription operation type? Intermediate
A Query fetches data without modifying anything, analogous to a REST GET request. A Mutation performs a write operation that changes data (creating, updating, or deleting a resourc…
Authentication is typically handled the same way as a REST API -- verifying a JWT or session from the request headers before the GraphQL execution begins, attaching the resulting u…
GraphQL with Node.js
All 5 questionsA GraphQL server needs a schema (written in GraphQL's Schema Definition Language, describing the available types and operations) and resolvers (functions that actually fetch or com…
Because a GraphQL query can request nested related data (like a list of posts, each with their author), a naive resolver implementation ends up calling the database once per post t…
- How do GraphQL Mutations differ from Queries, and how would you define one to create a new resource? Intermediate
Queries are for reading data and are expected to have no side effects, while Mutations are explicitly for operations that change server-side state (creating, updating, or deleting…
Since GraphQL typically exposes just one HTTP endpoint (unlike REST's many distinct routes), authentication is usually handled once via a context function that runs for every reque…
- What is over-fetching and under-fetching in REST APIs, and how does GraphQL specifically address both? Intermediate
Over-fetching happens when a REST endpoint returns more data than the client actually needs (like a full user object when the client only wanted the name), wasting bandwidth. Under…
HTTP & HTTPS Modules
All 5 questionshttp.createServer() takes a callback (or listener function) that's invoked for every incoming request, receiving a request object (with method, url, and headers) and a response obj…
- How does Node's node:https module differ from node:http, and what additional configuration does it require? Intermediate
The https module provides the same API surface as http but wraps connections in TLS encryption -- creating an HTTPS server requires providing a TLS certificate and private key (eit…
Modern Node.js (v18+) includes a global fetch() function matching the browser's Fetch API, providing a much more ergonomic, promise-based interface for making HTTP requests without…
- What is HTTP keep-alive, and how does Node's http.Agent manage connection reuse for outgoing requests? Intermediate
HTTP keep-alive lets a single TCP connection be reused for multiple sequential HTTP requests to the same host, avoiding the overhead of establishing a new TCP (and, for HTTPS, TLS)…
The http2 module provides native support for the HTTP/2 protocol, which offers multiplexed requests over a single connection (avoiding the head-of-line blocking of HTTP/1.1's conne…
HTTP & Web Servers
All 15 questionsThe http.createServer() function accepts a callback (or request listener) invoked for every incoming request, receiving request (req) and response (res) objects -- req provides det…
- What is the difference between HTTP/1.1 and HTTP/2, and how does Node.js support HTTP/2 via the node:http2 module? Intermediate
HTTP/1.1 opens a new TCP connection (or reuses a limited number via keep-alive) for each set of requests, processing them largely sequentially per connection, leading to head-of-li…
SSE keeps a single HTTP response open indefinitely, with the server writing formatted text events to it over time (rather than closing the connection after one response) -- the cli…
Keep-alive allows a single underlying TCP connection to be reused for multiple sequential HTTP requests/responses, rather than opening and closing a brand new TCP connection (with…
HTTP/2 server push lets a server proactively send resources to a client before the client explicitly requests them (like pushing a CSS file alongside the HTML page that references…
Logging & Monitoring
All 5 questionsStructured logging outputs each log entry as a machine-parseable object (typically JSON) with consistent fields (timestamp, level, message, and contextual metadata) rather than a f…
Log levels categorize the severity/importance of a log entry, letting a logger be configured to only actually output entries at or above a certain threshold -- typically 'debug' le…
OpenTelemetry is a vendor-neutral standard and set of libraries for generating traces, metrics, and logs -- for distributed tracing specifically, each service creates 'spans' repre…
A correlation (or request/trace) ID is generated once when a request first enters the system (or extracted if it was already provided by an upstream caller), attached to the reques…
An APM tool (like New Relic, Datadog APM, or Dynatrace) automatically instruments an application to capture detailed performance data -- transaction traces showing exactly where ti…
Message Queues (RabbitMQ & Kafka)
All 5 questions- How would you publish and consume messages using RabbitMQ in a Node.js application via the amqplib package? Intermediate
amqplib provides a client for connecting to RabbitMQ, declaring queues (or more commonly, exchanges that route messages to queues based on rules), publishing messages to an exchang…
Kafka organizes messages into topics, each split into multiple partitions for parallelism, with messages retained on disk for a configurable period (or indefinitely) rather than be…
Auto-acknowledgment marks a message as successfully processed the instant it's delivered to a consumer, before any actual processing logic has even run -- if the consumer then cras…
A dead-letter exchange (DLX) is configured on a queue to automatically receive messages that are rejected (nack'd without requeue), expire (via a message TTL), or exceed a queue's…
Direct HTTP calls create tight temporal coupling -- both services must be available simultaneously, and the calling service blocks waiting for a response, with a failure in the dow…
Microservices Architecture with Node.js
All 5 questions- What are the key benefits and tradeoffs of splitting a Node.js monolith into microservices? Intermediate
Microservices allow independent deployment (a team can ship changes to one service without redeploying the entire application), independent scaling (scaling just the specific servi…
In a dynamic environment (containers being created and destroyed, auto-scaling adjusting instance counts), hardcoding a downstream service's IP address doesn't work -- service disc…
- What is an API Gateway, and what role does it play in front of a collection of Node.js microservices? Intermediate
An API Gateway acts as a single entry point for external clients, routing incoming requests to the appropriate backend microservice, while also centralizing cross-cutting concerns…
In a microservices architecture, each service should own its data exclusively, exposing it to other services only through its own API rather than allowing other services to query i…
Common approaches include mutual TLS (mTLS, where each service presents a certificate verified by the other, providing strong cryptographic identity for both sides of the connectio…
Node.js Fundamentals & Runtime Architecture
All 5 questions- What is Node.js, and how does it differ fundamentally from running JavaScript in a web browser? Beginner
Node.js is a JavaScript runtime built on Google Chrome's V8 engine, extended with additional APIs (file system access, networking, process management) that let JavaScript run outsi…
- What is the V8 JavaScript engine, and what role does it play within the Node.js runtime? Intermediate
V8 is Google's open-source, high-performance JavaScript and WebAssembly engine (also used in Chrome), responsible for parsing, compiling (via just-in-time compilation), and executi…
Node.js follows a predictable release cadence where a new major version is released roughly every six months, alternating between 'Current' (receiving the latest features, but with…
Node.js's single-threaded JavaScript execution model is combined with an event-driven, non-blocking I/O architecture -- when an I/O operation (a network request, a file read, a dat…
npm (Node Package Manager) is the default package manager bundled with Node.js installations, providing a command-line tool for installing, publishing, and managing third-party Jav…
Path & OS Modules
All 5 questions- What is the difference between path.join() and path.resolve(), and when would you use each? Beginner
path.join() concatenates path segments together and normalizes the result (resolving '..' and '.' segments), but doesn't guarantee an absolute path -- if all inputs are relative, t…
The regular path module's behavior automatically adapts to whichever OS it's running on (using '/' on POSIX systems, '\' on Windows) -- but path.posix and path.win32 provide explic…
- How would you use the node:os module to make a script's behavior adapt correctly across different operating systems? Intermediate
os.platform() (returning 'win32', 'darwin', 'linux', etc.) lets a script branch its logic for OS-specific behavior, such as choosing the correct command to open a file with the sys…
path.parse() breaks a path string down into an object with its component parts: root, dir, base, ext, and name (the filename without its extension) -- useful for extracting or modi…
Path traversal is a vulnerability where user-supplied input containing '../' sequences is used to construct a file path, potentially letting an attacker escape an intended director…
Performance Optimization & Profiling
All 5 questions- How would you generate and interpret a CPU profile for a Node.js application using the built-in --prof flag? Intermediate
Running 'node --prof app.js' generates a V8 profiling log capturing where CPU time is spent during execution -- afterward, running 'node --prof-process' on the generated log file p…
V8 initially interprets JavaScript, then compiles frequently executed ('hot') functions into optimized machine code for much faster execution -- but if that optimized function late…
Load testing simulates many concurrent users or requests against an application to measure how its throughput (requests handled per second) and latency (response time, particularly…
JSON.stringify() can become a measurable bottleneck for very large objects or extremely high-frequency serialization -- optimizations include using a schema-based fast serializer (…
Vertical optimization improves the efficiency of the existing code and single-instance resource usage (fixing an N+1 query, adding caching, reducing unnecessary object allocation,…