0% found this document useful (0 votes)
3 views30 pages

Node Js Interview

The document provides a comprehensive list of over 90 Node.js backend interview questions commonly asked in product companies, covering topics such as Node.js fundamentals, asynchronous programming, middleware, Express.js, error handling, and database interactions. It includes explanations of key concepts like the event loop, non-blocking I/O, and various Node.js features such as streams, buffers, and clustering. Additionally, it discusses best practices for API security, versioning, and caching strategies.

Uploaded by

codelearner110
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Node Js Interview

The document provides a comprehensive list of over 90 Node.js backend interview questions commonly asked in product companies, covering topics such as Node.js fundamentals, asynchronous programming, middleware, Express.js, error handling, and database interactions. It includes explanations of key concepts like the event loop, non-blocking I/O, and various Node.js features such as streams, buffers, and clustering. Additionally, it discusses best practices for API security, versioning, and caching strategies.

Uploaded by

codelearner110
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

l/

pa
ep
de
an
/s
/in
om
.c
in
k ed
lin
w.
w
//w
s:
tp

Top 90+ [Link] Backend Interview Questions Asked in


ht

Product Companies

Follow for daily System Design, .NET, Node & Full Stack interview mastery
🔹 Q1. What is [Link] and why is it used in backend
systems?

Answer

l/
pa
[Link] is a JavaScript runtime built on Chrome’s V8 engine that allows executing JS on the
server side.

ep
Why product companies use [Link]:

de
●​ Non-blocking I/O model → handles high concurrency​

an
●​ Event-driven architecture​

/s
●​ Lightweight & fast startup​
/in
om

●​ Same language (JS/TS) across frontend + backend​


.c
in

Real-world example
ed

Netflix uses [Link] for edge services to handle millions of requests with minimal latency.
k

🔹 Q2. Explain the Event Loop in [Link] in depth


lin
w.
w

Answer
//w

[Link] uses a single-threaded event loop with a callback queue to handle async operations.
s:

Event loop phases:


tp

1.​ Timers (setTimeout, setInterval)​


ht

2.​ I/O callbacks​

3.​ Idle/prepare​

4.​ Poll (I/O execution)​

5.​ Check (setImmediate)​


6.​ Close callbacks​

Key insight:
●​ Heavy computation blocks the loop → bad for scalability​

l/
Production Example

pa
If your API processes image compression synchronously → all requests get blocked.​

ep
Solution: move to worker threads or queue (BullMQ).

de
🔹 Q3. Difference between [Link](),
an
setImmediate(), and setTimeout()
/s
/in
Method Execution Time
om

[Link] Immediately after current operation


k
.c

setImmediate After I/O events in next loop cycle


in
ed

setTimeout After specified delay


k

Real-world usage:
lin

Use nextTick for critical microtasks like error propagation.


w.

🔹 Q4. What is Non-Blocking I/O?


w
//w
s:

[Link] executes I/O operations asynchronously without blocking the main thread.
tp

Example
ht

[Link]('[Link]', (err, data) => {


[Link](data)
})
[Link]("Non-blocking continues...")

🔹 Q5. What are Streams in [Link]?


Streams process data in chunks instead of loading entire data in memory.
Types:
●​ Readable​

●​ Writable​

●​ Duplex​

l/
●​ Transform​

pa
ep
Production Example

de
Uploading a 1GB file using stream instead of loading in memory → avoids memory crash.

an
🔹 Q6. What is Buffer in [Link]?
/s
/in
Buffer is used to handle binary data directly in memory.
om

Used in:
●​ File handling​
.c

●​ TCP streams​
in
ed

●​ Image processing​
k
lin

🔹 Q7. What is the difference between spawn, exec, and


w.
w

fork?
//w

Method Use Case


s:

spawn Stream large data


tp

exec Run shell commands with buffer


ht

fork Create child Node process

Example
Use fork for parallel background job processing
🔹 Q8. What is clustering in [Link]?
Clustering allows multiple CPU cores to run [Link] instances.
const cluster = require('cluster')

Benefit:
Improves horizontal scaling on single machine

l/
pa
🔹 Q9. What are Worker Threads?

ep
de
Worker threads run CPU-heavy tasks in separate threads.

an
Example:

/s
●​ Image resizing​
/in
●​ PDF generation​
om

●​ ML processing​
.c
in

🔹 Q10. What is middleware in [Link]?


k ed

Middleware are functions executed during request lifecycle.


lin
w.

Express Example
w

[Link]((req, res, next) => {


//w

[Link]("Logging")
next()
})
s:
tp

🔹 Q11. Explain error handling in [Link]


ht

Types:
1.​ Sync errors → try/catch​

2.​ Async errors → callbacks/promises​


3.​ Global errors → [Link]('uncaughtException')​

Best Practice
Use centralized error handler middleware

🔹 Q12. What is REPL in [Link]?

l/
pa
ep
REPL = Read Eval Print Loop​
Used for interactive debugging

de
🔹 Q13. What is [Link]?
an
/s
It manages: /in
●​ dependencies​
om

●​ scripts​
.c

●​ metadata​
in
ed

Example
k

"scripts": {
lin

"start": "node [Link]"


w.

}
w

🔹 Q14. Difference between dependencies &


//w
s:

devDependencies
tp

Type Purpose
ht

dependencies Production runtime

devDependencie Dev tools (jest, eslint)


s
🔹 Q15. What is NPM vs NPX?
Tool Purpose

npm installs packages

npx executes
packages

l/
pa
🔹 Q16. What is the difference between CommonJS and ES

ep
de
Modules?

an
Feature CommonJS ES Modules

/s
Syntax require import
/in
Loading synchronou asynchronou
s s
om

🔹 Q17. What is callback hell?


.c
in
ed

Nested callbacks causing unreadable code.


k

Solution
lin

Use:
w.

●​ Promises​
w

●​ Async/await​
//w
s:

🔹 Q18. Explain Promises in [Link]


tp
ht

Promise has 3 states:


●​ Pending​

●​ Resolved​

●​ Rejected​
🔹 Q19. What is async/await?
Syntactic sugar over promises for cleaner async code.

🔹 Q20. What are environment variables?

l/
Stored in .env

pa
PORT=3000
DB_URL=...

ep
Used to store secure configuration

de
🔹 Q21. What is [Link] and why is it widely used?
an
/s
/in
Answer
om

[Link] is a minimal, unopinionated web framework for [Link] used to build REST APIs
and web servers.
.c

Why product companies use it:


in
ed

●​ Lightweight & fast​


k

●​ Middleware-based architecture​
lin

●​ Huge ecosystem​
w.
w

●​ Flexible routing​
//w
s:

Real-world example
tp

Building microservices APIs for an e-commerce platform (orders, users, payments) using
Express.
ht

🔹 Q22. Explain [Link] request lifecycle


Lifecycle Flow
Incoming Request → Middleware → Route Handler → Response → Error Middleware
Example
[Link](authMiddleware)
[Link]('/orders', orderController)
[Link](errorHandler)

🔹 Q23. What is routing in Express?

l/
pa
Routing maps HTTP request → handler function.

ep
[Link]('/users/:id', getUser)
[Link]('/orders', createOrder)

de
RESTful best practice:

an
●​ GET → read​

/s
●​ POST → create​
/in
om

●​ PUT/PATCH → update​

●​ DELETE → remove​
.c
in
ed

🔹 Q24. What are route parameters vs query parameters?


k
lin

Type Example
w.

Route param /users/10


w
//w

Query /users?page=
param 2
s:

🔹 Q25. What is middleware chaining?


tp
ht

Multiple middleware executed in sequence.


[Link]('/secure',
authMiddleware,
roleMiddleware,
controller
)
🔹 Q26. What is centralized error handling in Express?
Best Practice
Use a global error middleware:
[Link]((err, req, res, next) => {
[Link]([Link] || 500).json({

l/
message: [Link]

pa
})
})

ep
🔹 Q27. How do you structure a production-level Express

de
an
project?

/s
Recommended structure
/in
src/
om

├── controllers/
├── services/
.c

├── repositories/
in

├── middlewares/
├── routes/
ed

├── utils/
k

└── config/
lin

Why important?
w.

●​ Separation of concerns​
w
//w

●​ Clean architecture​
s:

●​ Testability​
tp
ht

🔹 Q28. How do you handle validation in [Link] APIs?


Tools:
●​ Joi​

●​ Yup​
●​ Zod​

●​ express-validator​

Example (Joi)
const schema = [Link]({

l/
email: [Link]().email().required()

pa
})

ep
🔹 Q29. What is request sanitization?

de
an
Sanitization removes malicious input.

/s
Example threats: /in
●​ XSS​
om

●​ SQL Injection​
.c
in

Libraries:
ed

●​ [Link]​
k
lin

●​ DOMPurify​
w.

🔹 Q30. What is rate limiting and why is it needed?


w
//w
s:

Prevents abuse by limiting number of requests.


tp

Example
ht

const rateLimit = require('express-rate-limit')

Real-world example
Login API limited to 5 attempts per minute
🔹 Q31. What is CORS and how do you configure it?
CORS allows cross-origin requests.
[Link](cors({
origin: '[Link]
}))

🔹 Q32. What is [Link]?

l/
pa
ep
Helmet secures Express apps by setting HTTP headers.
[Link](helmet())

de
Prevents:
●​ XSS​

an
●​ Clickjacking​

/s
/in
●​ MIME sniffing​
om

🔹 Q33. How do you secure REST APIs?


.c
in
ed

Best practices:
k

●​ HTTPS​
lin
w.

●​ JWT authentication​
w

●​ Input validation​
//w

●​ Rate limiting​
s:

●​ Helmet​
tp
ht

●​ Logging & monitoring​

🔹 Q34. What is JWT authentication?


JWT = JSON Web Token
Flow:
1.​ User login​

2.​ Server generates token​

3.​ Client sends token in headers​

🔹 Q35. What is refresh token mechanism?

l/
pa
ep
Access token expires quickly​
Refresh token used to generate new access token

de
Benefit

an
Improves security + UX

/s
/in
🔹 Q36. What is OAuth in [Link]?
om

OAuth allows login using:


.c

●​ Google​
in

●​ Facebook​
k ed

●​ GitHub​
lin

Used in SSO systems


w.

🔹 Q37. What is API versioning?


w
//w

Versioning prevents breaking existing clients.


s:
tp

Methods:
ht

●​ URL versioning /v1/users​

●​ Header versioning​

●​ Query versioning​
🔹 Q38. What is pagination in APIs?
Used to fetch large datasets in chunks.

Example
GET /products?page=1&limit=20

l/
🔹 Q39. What is API caching?

pa
ep
Caching improves performance.

de
Types:

an
●​ In-memory (Node cache)​

/s
●​ Redis​
/in
om

●​ CDN caching​
.c

Example
in

Cache product list for 60 seconds


ed

🔹 Q40. What are HTTP status codes best practices?


k
lin
w.

Code Meaning
w
//w

200 OK

201 Created
s:
tp

400 Bad Request


ht

401 Unauthorized

403 Forbidden

404 Not Found

500 Server Error


🔹 Q41. How does [Link] interact with databases?
Answer
[Link] interacts with databases using drivers/ORM/ODM libraries.

Common stacks:

l/
●​ SQL → PostgreSQL, MySQL (pg, mysql2, Sequelize, TypeORM)​

pa
ep
●​ NoSQL → MongoDB (Mongoose)​

de
Production Example

an
Order service using PostgreSQL with TypeORM and connection pooling.

🔹 Q42. What is connection pooling and why is it /s


/in
om

important?
.c

Connection pooling maintains a set of reusable DB connections.


in
ed

Benefits:
●​ Reduces connection overhead​
k
lin

●​ Improves performance​
w.

●​ Prevents DB overload​
w
//w

Real-world Example
s:

High-traffic login API handling 1000+ concurrent users


tp
ht

🔹 Q43. What is ORM vs Query Builder?


ORM Query Builder

Abstracts DB to objects Write SQL-like queries

e.g., TypeORM, [Link]


Sequelize
Tradeoff
ORM → productivity​
Query builder → performance control

🔹 Q44. What is database indexing?

l/
Indexes improve query performance by reducing full table scans.

pa
ep
Example
CREATE INDEX idx_user_email ON users(email);

de
🔹 Q45. What are ACID properties?
an
/s
●​ Atomicity​
/in
om

●​ Consistency​
.c

●​ Isolation​
in

●​ Durability​
ed

Used in transactional systems like payments


k
lin

🔹 Q46. What is eventual consistency?


w.
w

Used in distributed systems


//w

Data is not immediately consistent but becomes consistent over time.


s:

Example
tp

Order created → inventory updated asynchronously


ht

🔹 Q47. SQL vs NoSQL — when to use what?


Use SQL Use NoSQL

Transactions High scalability

Structured data Flexible schema


Banking Social media
systems feeds

🔹 Q48. What is database sharding?


Splitting database into smaller pieces (shards)

l/
pa
Example

ep
Users split by region:
●​ India shard​

de
●​ US shard​

an
🔹 Q49. What is replication? /s
/in
om

Replication copies data across multiple servers.


.c

Types:
in
ed

●​ Master-Slave​
k

●​ Multi-master​
lin
w.

Benefit:
w

●​ High availability​
//w

●​ Fault tolerance​
s:
tp

🔹 Q50. What is Redis and why is it used?


ht

Redis is an in-memory data store.

Used for:
●​ Caching​
●​ Session store​

●​ Pub/Sub messaging​

●​ Rate limiting​

🔹 Q51. What is caching strategy?

l/
pa
ep
Types:

de
1.​ Cache-aside​

an
2.​ Write-through​

3.​ Write-back​
/s
/in
om

Example
.c

Product catalog cached for 30 seconds


in

🔹 Q52. How do you implement caching in [Link]?


k ed
lin

const redis = require('redis')


const client = [Link]()
w.
w

Pattern:
//w

●​ Check cache​
s:

●​ If miss → fetch DB → store in cache​


tp
ht

🔹 Q53. What is cache invalidation?


Removing stale data from cache.

Strategies:
●​ TTL expiration​
●​ Manual invalidation​

●​ Event-driven invalidation​

🔹 Q54. What is message queue?

l/
pa
Message queue enables async communication between services

ep
Tools:

de
●​ RabbitMQ​

an
●​ Kafka​

/s
●​ BullMQ (Redis-based)​ /in
om

🔹 Q55. When to use message queues?


.c
in

Use when:
●​ Background jobs​
k ed

●​ Email sending​
lin

●​ Payment processing​
w.
w

●​ Order fulfillment​
//w

🔹 Q56. What is Pub/Sub pattern?


s:
tp
ht

Publisher sends messages → multiple subscribers receive.

Example
Order placed → notify:
●​ Inventory service​

●​ Notification service​
🔹 Q57. What is Kafka used for?
Kafka is used for:
●​ Event streaming​

●​ Log aggregation​

●​ Real-time analytics​

l/
pa
ep
Example

de
Tracking user activity events

🔹 Q58. What is BullMQ?


an
/s
/in
BullMQ is a Redis-based job queue for [Link].
om

Use cases:
●​ Email jobs​
.c
in

●​ Image processing​
ed

●​ Report generation​
k
lin

🔹 Q59. What is idempotency in APIs?


w.
w
//w

Idempotency ensures same request multiple times = same result


s:

Example
tp

Payment API should not charge twice.


ht

🔹 Q60. What is distributed locking?


Used to prevent multiple processes modifying same data

Tools:
●​ Redis locks​
●​ Zookeeper​

🔹 Q61. What is horizontal vs vertical scaling?


Type Description

l/
pa
Vertical Increase CPU/RAM

ep
Horizontal Add more servers
Node apps usually scale horizontally

de
🔹 Q62. What is load balancing?
an
/s
Distributes traffic across multiple servers.
/in
om

Tools:
●​ Nginx​
.c
in

●​ AWS ELB​
ed

🔹 Q63. What is circuit breaker pattern?


k
lin
w.

Prevents system failure when downstream service fails.


w
//w

Example
If payment service down → stop retrying → fallback response
s:
tp

🔹 Q64. What is API gateway?


ht

API gateway is single entry point for microservices.

Responsibilities:
●​ Authentication​

●​ Routing​
●​ Rate limiting​

●​ Logging​

🔹 Q65. What is CQRS pattern?

l/
pa
CQRS = Command Query Responsibility Segregation
Separate:

ep
●​ Read operations​

de
●​ Write operations​

an
/s
Benefit: /in
Better scalability for large systems
om

🔹 Q66. How do you design a scalable [Link] backend


.c
in

architecture?
k ed

Answer
lin

Use layered + modular architecture with horizontal scalability.


w.

Production Architecture
w
//w

Client → CDN → Load Balancer → API Gateway → Node Services → DB/Cache/Queue


s:

Key design principles:


tp

●​ Stateless services​
ht

●​ Horizontal scaling​

●​ Externalized state (Redis, DB)​

●​ API gateway for routing​


🔹 Q67. What is microservices architecture in [Link]?
Microservices split application into independent deployable services.

Example services:
●​ Auth Service​

l/
●​ Order Service​

pa
●​ Payment Service​

ep
de
●​ Notification Service​

an
Benefits:

/s
●​ Independent deployment​
/in
om

●​ Team ownership​

●​ Scalability per service​


.c
in

🔹 Q68. What is monolith vs microservices?


k ed
lin

Monolith Microservices
w.

Single Multiple services


w

codebase
//w

Simple to start Complex but


scalable
s:

Tight coupling Loose coupling


tp
ht

🔹 Q69. What is API Gateway in production?


API gateway acts as single entry point.

Responsibilities:
●​ Auth verification​
●​ Rate limiting​

●​ Routing​

●​ Response aggregation​

l/
Tools:

pa
●​ Kong​

ep
●​ NGINX​

de
●​ AWS API Gateway​

an
🔹 Q70. What is service discovery? /s
/in
om

Services dynamically discover each other.


.c

Tools:
in

●​ Consul​
ed

●​ Eureka​
k
lin

●​ Kubernetes DNS​
w.
w

🔹 Q71. What is Docker and why is it used with [Link]?


//w
s:

Docker packages app + dependencies into container.


tp

Benefits:
ht

●​ Same environment everywhere​

●​ Easy deployment​

●​ Isolation​
🔹 Q72. Example Dockerfile for [Link]
FROM node:20
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "[Link]"]

l/
pa
🔹 Q73. What is Kubernetes (K8s)?

ep
de
Kubernetes orchestrates containers.

an
Features:

/s
●​ Auto scaling​ /in
●​ Self healing​
om

●​ Rolling deployment​
.c
in

🔹 Q74. What is CI/CD pipeline?


k ed
lin

Automates:
●​ Build​
w.

●​ Test​
w
//w

●​ Deploy​
s:
tp

Tools:
ht

●​ GitHub Actions​

●​ Jenkins​

●​ Azure DevOps​
🔹 Q75. How do you manage environment configurations?
Use:
●​ .env files​

●​ Secret managers (Azure Key Vault, AWS Secrets Manager)​

l/
🔹 Q76. What is logging in [Link] production apps?

pa
ep
Logging tracks system activity.

de
Tools:

an
●​ Winston​

/s
●​ Pino​
/in
om

Best practice:
.c

Log:
in

●​ request id​
ed

●​ user id​
k
lin

●​ error stack​
w.
w

🔹 Q77. What is monitoring?


//w
s:

Monitoring checks system health.


tp

Tools:
ht

●​ Prometheus​

●​ Grafana​

●​ Datadog​
🔹 Q78. What is distributed tracing?
Tracks request across microservices.

Tools:
●​ Jaeger​

l/
●​ Zipkin​

pa
ep
🔹 Q79. What is health check endpoint?

de
an
Used by load balancers to verify service health.
[Link]('/health', (req, res) => [Link]("OK"))

🔹 Q80. What is blue-green deployment? /s


/in
om

Two environments:
.c

●​ Blue (current)​
in

●​ Green (new)​
ed

Switch traffic after testing.


k
lin

🔹 Q81. What is canary deployment?


w.
w

Release to small % of users first.


//w

Example
s:
tp

Deploy to 5% users → monitor → full rollout


ht

🔹 Q82. What is rollback strategy?


Revert to previous stable version if failure occurs.

🔹 Q83. How do you handle secrets in Node apps?


Never store secrets in code.
Use:
●​ env variables​

●​ vault services​

🔹 Q84. What is rate limiting at infrastructure level?

l/
pa
Implemented at:

ep
●​ API gateway​

de
●​ NGINX​

an
●​ Cloudflare​

/s
/in
🔹 Q85. What is zero downtime deployment?
om

Deploy without interrupting active users.


.c
in

Techniques:
ed

●​ Rolling updates​
k
lin

●​ Blue-green​
w.

●​ Canary​
w
//w

🔹 Q86. What is CDN and why used?


s:
tp

CDN caches static content globally.


ht

Example
Cloudflare for:
●​ images​

●​ js files​
🔹 Q87. What is SSR vs CSR in Node ecosystem?
SSR CSR

Server renders HTML Browser renders

SEO friendly Faster client


interactions

l/
pa
🔹 Q88. What is BFF (Backend for Frontend)?

ep
de
Separate backend tailored for each frontend.

an
Example

/s
●​ Mobile BFF​ /in
●​ Web BFF​
om

🔹 Q89. What is feature flagging?


.c
in
ed

Enable/disable features without deployment.


k
lin

Tools:
w.

●​ LaunchDarkly​
w

●​ Firebase Remote Config​


//w

🔹 Q90. What is graceful shutdown in [Link]?


s:
tp
ht

Ensures:
●​ No data loss​

●​ Close DB connections​

●​ Finish ongoing requests​

[Link]('SIGTERM', async () => {


await [Link]()
})
ht
tp
s:
//w
w
w.
lin
ked
in
.c
om
/in
/s
an
de
ep
pa
l/

You might also like