Core Node.js Questions
- Node.js single-threaded hai — phir bhi multiple requests efficiently kaise handle karta hai? Explain event loop and non-blocking I/O.
- Difference between
process.nextTick()andsetImmediate(). - How does Node.js handle 1000 concurrent requests? Explain async nature and event loop.
- Explain Event Loop phases.
- What are microtasks and macrotasks in Node.js? Give examples.
- How does Node.js handle CPU-intensive tasks?
- How do you debug performance issues (CPU/memory) in Node.js?
- Difference between
requireandimportin Node.js. - Explain Streams in Node.js and give a scenario where they are useful.
- Difference between
fs.readFileandfs.createReadStream.
Node.js Advanced & Tricky Questions
-
Explain the 6 phases of Node.js event loop in detail:
- Timers
- Pending callbacks
- Idle, prepare
- Poll
- Check
- Close callbacks
- What's the order of execution?
javascript
`setImmediate(() => console.log('immediate'));
process.nextTick(() => console.log('nextTick'));
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('sync');`
-
How do you handle CPU-intensive tasks without blocking the event loop?
- Worker threads
- Child processes
- Clustering
-
Explain the difference between
fork(),spawn(),exec(),execFile()in child_process. -
What is
libuv? Role in Node.js architecture. - How does Node.js utilize multiple CPU cores? Cluster module.
- Explain backpressure in streams — how to handle it?
- What's the difference between readable, writable, duplex, and transform streams?
- Implement a custom transform stream that converts input to uppercase.
- How do you prevent thread starvation in Node.js?
- Explain Node.js module resolution algorithm — node_modules lookup.
-
What's the purpose of
package-lock.json? Difference frompackage.json. - How to implement graceful shutdown in Node.js? Handle ongoing requests.
-
Explain the
uncaughtExceptionandunhandledRejectionevents — best practices. - What's the difference between
BufferandUint8Array? - How to detect memory leaks in production Node.js apps? Tools: heapdump, clinic.
-
Explain Node.js security best practices:
- Helmet
- Rate limiting
- Input validation
- HTTPS
- Dependency scanning
- What is N-API? Native addons in Node.js.
- How do you monitor Node.js application performance? Metrics to track.
-
Explain the
-inspectflag — debugging production apps.
Express.js Questions
- What is middleware in Express? Types and examples.
- Explain error-handling middleware in Express.
- How to handle async errors in Express routes?
- How does Express handle routing internally?
- Difference between
app.use()androuter.use(). - How do you handle file uploads in Express?
- Explain rate limiting in Express — scenario where multiple requests come simultaneously.
- How to implement CORS in Express?
- How to secure Express app against common vulnerabilities (XSS, CSRF, SQL injection)?
- How do you implement logging in Express applications?
Express.js Advanced & Tricky
- What's the order of middleware execution? How to control it?
- How do you handle async errors without try-catch in every route?
javascript
`const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};`
- Explain the request-response cycle in Express — detailed flow.
- How to implement custom middleware for authentication? JWT verification.
- What's the difference between
app.route()androuter.route()? - How to handle multipart/form-data? Multer internals.
- Implement a middleware that logs request time for every route.
- How to implement CSRF protection? Token-based approach.
- Explain the difference between:
javascript
`app.use('/api', router);
app.use(router);`
- How to implement request validation? Joi, express-validator.
-
What happens if you call
next()multiple times? Common mistakes. - How to implement compression in Express? gzip, brotli.
-
Explain the
res.localsobject — use cases. - How to implement API versioning? Multiple approaches.
- What's the difference between
res.send(),res.json(),res.end()?
MongoDB / Mongoose Questions
- Difference between
find(),findOne(), andfindById(). - Explain aggregation pipeline with an example.
- What is indexing? How does it improve query performance?
- What is
populate()in Mongoose? Give example. - Difference between embedded documents and references.
- How to design schema for a blog or e-commerce app?
- How to handle large collections efficiently?
- Explain transactions in MongoDB and when to use them.
- How to implement pagination in MongoDB?
- How to handle schema validation in Mongoose?
MongoDB Advanced & Tricky Questions
- Explain MongoDB ACID properties — transaction support.
- What's the difference between:
javascript
`Model.find({})
Model.find({}).lean()
Model.find({}).cursor()`
- How does MongoDB indexing work internally? B-tree structure.
- Explain compound indexes — order matters?
- What's the difference between covered query and indexed query?
- Implement text search in MongoDB — full-text search indexes.
- How to handle schema versioning? Migration strategies.
- Explain sharding in MongoDB — when to use it?
- What's the difference between replica set and sharding?
-
How to optimize aggregation pipeline performance?
$matchearly, indexes. -
Explain the aggregation stages:
-
$match,$group,$project,$sort,$limit,$skip -
$lookup(joins),$unwind,$addFields
-
- How to implement geospatial queries? 2dsphere indexes.
- What's the difference between:
javascript
`{ $set: { name: 'John' } }
{ name: 'John' }`
In update operations.
Explain write concerns in MongoDB — w, j, wtimeout.
How to handle large file storage? GridFS.
What's the difference between
updateOne,updateMany,replaceOne?Implement soft delete with Mongoose — plugin approach.
How to implement data auditing? Timestamp tracking, change history.
Explain the Mongoose middleware — pre/post hooks.
What's the difference between:
javascript
`schema.virtual()
schema.method()
schema.static()`
Authentication / Authorization Questions
- Explain JWT authentication flow.
- Difference between access token and refresh token.
- How to secure API routes in Express using JWT?
- How to implement role-based access control (RBAC) in Express?
- How to store JWT securely on client-side?
Auth Advanced & Tricky
- What's inside a JWT token? Header, payload, signature — explain each.
- How to handle token refresh without logout? Refresh token rotation.
- What's the difference between stateless and stateful authentication?
- Implement OAuth 2.0 flow — authorization code grant.
- How to prevent JWT replay attacks? Nonce, jti claim.
- Explain the difference between httpOnly and secure cookies.
- How to implement multi-factor authentication (MFA)? TOTP algorithm.
- What's the difference between authentication and authorization?
- How to implement API key authentication? Rate limiting per key.
- Explain session-based authentication — vs JWT comparison.
- How to handle password reset securely? Token expiration, one-time use.
- What is bcrypt and why use it? Salting, hashing rounds.
- Implement permission-based access control — granular permissions.
- How to secure refresh tokens? Rotation, revocation strategies.
- What's the difference between Bearer token and API key?
Scenario-Based / Practical Questions
- Async/Await vs Promises in error handling — reusable async wrapper.
- MongoDB slow query on 1 million+ documents — how to optimize?
- User token expired — how to handle refresh token scenario?
- Multiple users uploading large files simultaneously — backend crash scenario, optimization.
- Aggregation: Top 3 users with highest total orders in last month.
- Public API exposed — prevent DDOS / brute force attacks using rate limiting.
- Express app running slow under load — how to debug performance issues.
- You need to migrate MongoDB schema without downtime — approach?
- Implement search functionality in MongoDB with text indexes.
- How to implement soft delete (logical delete) in MongoDB.
- Implement caching in Node.js for frequently accessed DB data (Redis / memory).
- Scenario: Real-time notifications using Node.js and MongoDB — approach.
- Scenario: File upload + image processing pipeline — handle asynchronously.
- Scenario: Multiple microservices interacting with one MongoDB — how to maintain consistency?
- Scenario: Multi-tenancy in Node.js + MongoDB application.
Extreme Scenario-Based Questions (Real Production Issues)
- Your API suddenly returns 502 Bad Gateway for all requests — where do you start debugging?
- Memory usage keeps increasing in production Node.js app — hits 2GB and crashes. How to debug?
- Database connection pool exhausted — 100 concurrent users, all waiting. What's wrong?
- Race condition in checkout system — two users bought last item. How to prevent?
- MongoDB aggregation taking 30+ seconds on 10M documents — optimize without changing schema.
- JWT token size causing performance issues — payload too large. Solutions?
- API rate limiter blocking legitimate users — shared IP (corporate network). How to handle?
- Bulk email sending causing Express app to freeze — 10,000 emails. Architecture solution?
- File upload fails for files > 50MB — timeout errors. Complete solution?
- Redis cache hit rate is 5% — supposed to be 80%+. What's wrong?
- Mongoose query returns all 1M documents instead of paginated results — catastrophic error. Why?
- WebSocket connections keep dropping every 60 seconds — load balancer issue?
- Database indexes not being used — explain query plan shows COLLSCAN. Debug process?
- Concurrent API calls updating same document cause data loss — optimistic locking solution.
- Authentication fails randomly for some users — JWT verification errors. Debugging approach?
- Image processing queue backed up — 10,000 pending jobs. How to handle gracefully?
- Circular dependency in Node.js modules — causing undefined exports. How to resolve?
- API returns stale data despite database updates — caching issue. Multi-layer cache invalidation strategy?
- Server crashes when processing CSV with 5M rows — memory-efficient streaming solution.
- N+1 query problem in GraphQL — 1000 database queries for single request. Solutions?
- WebSockets not scaling horizontally — sticky sessions, Redis adapter solution.
- Transaction deadlock in MongoDB — two operations waiting for each other. Prevention?
- CDN serving old JavaScript bundle — aggressive caching. Cache busting strategies?
- Automated tests passing but production failing — environment differences. Investigation steps?
- API response time increased from 100ms to 5s overnight — no code changes. What to check?
System Design & Architecture Questions
- Design a URL shortener (like bit.ly) — complete backend architecture.
- Design a rate limiter — support distributed systems.
- Design a real-time chat application — WebSockets, scaling strategy.
- Design a file storage system (like Dropbox) — chunking, deduplication.
- Design a notification system — email, SMS, push notifications.
- Design an e-commerce cart system — handle race conditions, inventory management.
- Design a job queue system — Bull, Redis, failure handling.
- Design an analytics dashboard — handling time-series data efficiently.
- Design a payment gateway integration — security, idempotency.
- Design a microservices architecture for a blog platform — service boundaries, communication.
Performance & Optimization Questions
- How to optimize a Next.js app that has 3-second initial load time? Step-by-step approach.
- API endpoint taking 10 seconds to respond — profiling and optimization strategy.
- React app re-rendering 100 times on single user action — identify and fix.
- MongoDB query using 4GB of RAM — aggregation optimization techniques.
- Node.js app using 100% CPU — identify bottleneck without production downtime.
- Implement caching strategy for REST API — cache invalidation, TTL strategies.
- How to reduce Docker image size from 2GB to 200MB? Best practices.
- Optimize bundle size in React app — tree shaking, code splitting, dynamic imports.
- Database connection pool sizing — how to determine optimal pool size?
- Implement database read replicas — read/write split in Node.js application.
DevOps & Deployment Questions
- Explain CI/CD pipeline for Node.js application — GitHub Actions, Jenkins.
- Zero-downtime deployment strategy — blue-green, canary deployment.
- How to handle environment variables securely? Secrets management.
- Explain Docker multi-stage builds — optimize image layers.
- How to monitor Node.js app in production? PM2, New Relic, Prometheus.
- Implement health check endpoint — readiness vs liveness probes.
- How to handle database migrations in production? Rollback strategy.
- Explain horizontal vs vertical scaling — when to use each?
- How to implement logging in distributed systems? Centralized logging (ELK stack).
- Container orchestration — Kubernetes basics for Node.js apps.
Code Review & Best Practices Questions
- Review this code — find all issues:
javascript
app.get('/users/:id', (req, res) => {
User.findById(req.params.id).then(user => {
res.json(user);
});
});
- What's wrong with this Mongoose schema?
javascript
const userSchema = new Schema({
email: String,
password: String
});
- Review this React component:
javascript
function List({ items }) {
return items.map(item => <div>{item.name}</div>);
}
- What's the security issue here?
javascript
app.get('/search', (req, res) => {
const query = req.query.q;
db.collection('posts').find({ $where: query });
});
- Identify the performance problem:
javascript
useEffect(() => {
const data = expensiveOperation();
setData(data);
});
Testing Questions
- How to test async Express routes? Jest, Supertest.
- Difference between unit, integration, and E2E tests — examples for each.
- How to mock MongoDB in tests? mongodb-memory-server.
- Testing React components — React Testing Library best practices.
- How to test private functions? Should you test them?
- Implement test coverage — what percentage is ideal?
- How to test error scenarios? Error boundaries, API failures.
- Testing WebSocket connections — approach and tools.
- How to handle flaky tests? Identification and fixes.
- Test database transactions — rollback after each test.
Bonus: Algorithm & Data Structure Questions
- Implement LRU Cache — O(1) get and put.
- Two Sum problem — optimal solution.
- Reverse a linked list — iterative and recursive.
- Validate balanced parentheses — stack approach.
- Find duplicate in array — without extra space.
- Implement debounce and throttle — from scratch.
- Binary search — find element in sorted array.
- Merge two sorted arrays — in-place.
- Implement a trie (prefix tree) — autocomplete use case.
- Detect cycle in linked list — Floyd's algorithm.
Top comments (0)