DEV Community

Nitin Malviya
Nitin Malviya

Posted on

Backend Interview Questions

Core Node.js Questions

  1. Node.js single-threaded hai — phir bhi multiple requests efficiently kaise handle karta hai? Explain event loop and non-blocking I/O.
  2. Difference between process.nextTick() and setImmediate().
  3. How does Node.js handle 1000 concurrent requests? Explain async nature and event loop.
  4. Explain Event Loop phases.
  5. What are microtasks and macrotasks in Node.js? Give examples.
  6. How does Node.js handle CPU-intensive tasks?
  7. How do you debug performance issues (CPU/memory) in Node.js?
  8. Difference between require and import in Node.js.
  9. Explain Streams in Node.js and give a scenario where they are useful.
  10. Difference between fs.readFile and fs.createReadStream.

Node.js Advanced & Tricky Questions

  1. Explain the 6 phases of Node.js event loop in detail:
    • Timers
    • Pending callbacks
    • Idle, prepare
    • Poll
    • Check
    • Close callbacks
  2. 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');`
Enter fullscreen mode Exit fullscreen mode
  1. How do you handle CPU-intensive tasks without blocking the event loop?
    • Worker threads
    • Child processes
    • Clustering
  2. Explain the difference between fork(), spawn(), exec(), execFile() in child_process.
  3. What is libuv? Role in Node.js architecture.
  4. How does Node.js utilize multiple CPU cores? Cluster module.
  5. Explain backpressure in streams — how to handle it?
  6. What's the difference between readable, writable, duplex, and transform streams?
  7. Implement a custom transform stream that converts input to uppercase.
  8. How do you prevent thread starvation in Node.js?
  9. Explain Node.js module resolution algorithm — node_modules lookup.
  10. What's the purpose of package-lock.json? Difference from package.json.
  11. How to implement graceful shutdown in Node.js? Handle ongoing requests.
  12. Explain the uncaughtException and unhandledRejection events — best practices.
  13. What's the difference between Buffer and Uint8Array?
  14. How to detect memory leaks in production Node.js apps? Tools: heapdump, clinic.
  15. Explain Node.js security best practices:
    • Helmet
    • Rate limiting
    • Input validation
    • HTTPS
    • Dependency scanning
  16. What is N-API? Native addons in Node.js.
  17. How do you monitor Node.js application performance? Metrics to track.
  18. Explain the -inspect flag — debugging production apps.

Express.js Questions

  1. What is middleware in Express? Types and examples.
  2. Explain error-handling middleware in Express.
  3. How to handle async errors in Express routes?
  4. How does Express handle routing internally?
  5. Difference between app.use() and router.use().
  6. How do you handle file uploads in Express?
  7. Explain rate limiting in Express — scenario where multiple requests come simultaneously.
  8. How to implement CORS in Express?
  9. How to secure Express app against common vulnerabilities (XSS, CSRF, SQL injection)?
  10. How do you implement logging in Express applications?

Express.js Advanced & Tricky

  1. What's the order of middleware execution? How to control it?
  2. 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);
};`
Enter fullscreen mode Exit fullscreen mode
  1. Explain the request-response cycle in Express — detailed flow.
  2. How to implement custom middleware for authentication? JWT verification.
  3. What's the difference between app.route() and router.route()?
  4. How to handle multipart/form-data? Multer internals.
  5. Implement a middleware that logs request time for every route.
  6. How to implement CSRF protection? Token-based approach.
  7. Explain the difference between:

javascript

`app.use('/api', router);
app.use(router);`
Enter fullscreen mode Exit fullscreen mode
  1. How to implement request validation? Joi, express-validator.
  2. What happens if you call next() multiple times? Common mistakes.
  3. How to implement compression in Express? gzip, brotli.
  4. Explain the res.locals object — use cases.
  5. How to implement API versioning? Multiple approaches.
  6. What's the difference between res.send(), res.json(), res.end()?

MongoDB / Mongoose Questions

  1. Difference between find(), findOne(), and findById().
  2. Explain aggregation pipeline with an example.
  3. What is indexing? How does it improve query performance?
  4. What is populate() in Mongoose? Give example.
  5. Difference between embedded documents and references.
  6. How to design schema for a blog or e-commerce app?
  7. How to handle large collections efficiently?
  8. Explain transactions in MongoDB and when to use them.
  9. How to implement pagination in MongoDB?
  10. How to handle schema validation in Mongoose?

MongoDB Advanced & Tricky Questions

  1. Explain MongoDB ACID properties — transaction support.
  2. What's the difference between:

javascript

`Model.find({})
Model.find({}).lean()
Model.find({}).cursor()`
Enter fullscreen mode Exit fullscreen mode
  1. How does MongoDB indexing work internally? B-tree structure.
  2. Explain compound indexes — order matters?
  3. What's the difference between covered query and indexed query?
  4. Implement text search in MongoDB — full-text search indexes.
  5. How to handle schema versioning? Migration strategies.
  6. Explain sharding in MongoDB — when to use it?
  7. What's the difference between replica set and sharding?
  8. How to optimize aggregation pipeline performance? $match early, indexes.
  9. Explain the aggregation stages:
    • $match, $group, $project, $sort, $limit, $skip
    • $lookup (joins), $unwind, $addFields
  10. How to implement geospatial queries? 2dsphere indexes.
  11. What's the difference between:

javascript

`{ $set: { name: 'John' } }
{ name: 'John' }`
Enter fullscreen mode Exit fullscreen mode

In update operations.

  1. Explain write concerns in MongoDB — w, j, wtimeout.

  2. How to handle large file storage? GridFS.

  3. What's the difference between updateOne, updateMany, replaceOne?

  4. Implement soft delete with Mongoose — plugin approach.

  5. How to implement data auditing? Timestamp tracking, change history.

  6. Explain the Mongoose middleware — pre/post hooks.

  7. What's the difference between:

javascript

`schema.virtual()
schema.method()
schema.static()`
Enter fullscreen mode Exit fullscreen mode

Authentication / Authorization Questions

  1. Explain JWT authentication flow.
  2. Difference between access token and refresh token.
  3. How to secure API routes in Express using JWT?
  4. How to implement role-based access control (RBAC) in Express?
  5. How to store JWT securely on client-side?

Auth Advanced & Tricky

  1. What's inside a JWT token? Header, payload, signature — explain each.
  2. How to handle token refresh without logout? Refresh token rotation.
  3. What's the difference between stateless and stateful authentication?
  4. Implement OAuth 2.0 flow — authorization code grant.
  5. How to prevent JWT replay attacks? Nonce, jti claim.
  6. Explain the difference between httpOnly and secure cookies.
  7. How to implement multi-factor authentication (MFA)? TOTP algorithm.
  8. What's the difference between authentication and authorization?
  9. How to implement API key authentication? Rate limiting per key.
  10. Explain session-based authentication — vs JWT comparison.
  11. How to handle password reset securely? Token expiration, one-time use.
  12. What is bcrypt and why use it? Salting, hashing rounds.
  13. Implement permission-based access control — granular permissions.
  14. How to secure refresh tokens? Rotation, revocation strategies.
  15. What's the difference between Bearer token and API key?

Scenario-Based / Practical Questions

  1. Async/Await vs Promises in error handling — reusable async wrapper.
  2. MongoDB slow query on 1 million+ documents — how to optimize?
  3. User token expired — how to handle refresh token scenario?
  4. Multiple users uploading large files simultaneously — backend crash scenario, optimization.
  5. Aggregation: Top 3 users with highest total orders in last month.
  6. Public API exposed — prevent DDOS / brute force attacks using rate limiting.
  7. Express app running slow under load — how to debug performance issues.
  8. You need to migrate MongoDB schema without downtime — approach?
  9. Implement search functionality in MongoDB with text indexes.
  10. How to implement soft delete (logical delete) in MongoDB.
  11. Implement caching in Node.js for frequently accessed DB data (Redis / memory).
  12. Scenario: Real-time notifications using Node.js and MongoDB — approach.
  13. Scenario: File upload + image processing pipeline — handle asynchronously.
  14. Scenario: Multiple microservices interacting with one MongoDB — how to maintain consistency?
  15. Scenario: Multi-tenancy in Node.js + MongoDB application.

Extreme Scenario-Based Questions (Real Production Issues)

  1. Your API suddenly returns 502 Bad Gateway for all requests — where do you start debugging?
  2. Memory usage keeps increasing in production Node.js app — hits 2GB and crashes. How to debug?
  3. Database connection pool exhausted — 100 concurrent users, all waiting. What's wrong?
  4. Race condition in checkout system — two users bought last item. How to prevent?
  5. MongoDB aggregation taking 30+ seconds on 10M documents — optimize without changing schema.
  6. JWT token size causing performance issues — payload too large. Solutions?
  7. API rate limiter blocking legitimate users — shared IP (corporate network). How to handle?
  8. Bulk email sending causing Express app to freeze — 10,000 emails. Architecture solution?
  9. File upload fails for files > 50MB — timeout errors. Complete solution?
  10. Redis cache hit rate is 5% — supposed to be 80%+. What's wrong?
  11. Mongoose query returns all 1M documents instead of paginated results — catastrophic error. Why?
  12. WebSocket connections keep dropping every 60 seconds — load balancer issue?
  13. Database indexes not being used — explain query plan shows COLLSCAN. Debug process?
  14. Concurrent API calls updating same document cause data loss — optimistic locking solution.
  15. Authentication fails randomly for some users — JWT verification errors. Debugging approach?
  16. Image processing queue backed up — 10,000 pending jobs. How to handle gracefully?
  17. Circular dependency in Node.js modules — causing undefined exports. How to resolve?
  18. API returns stale data despite database updates — caching issue. Multi-layer cache invalidation strategy?
  19. Server crashes when processing CSV with 5M rows — memory-efficient streaming solution.
  20. N+1 query problem in GraphQL — 1000 database queries for single request. Solutions?
  21. WebSockets not scaling horizontally — sticky sessions, Redis adapter solution.
  22. Transaction deadlock in MongoDB — two operations waiting for each other. Prevention?
  23. CDN serving old JavaScript bundle — aggressive caching. Cache busting strategies?
  24. Automated tests passing but production failing — environment differences. Investigation steps?
  25. API response time increased from 100ms to 5s overnight — no code changes. What to check?

System Design & Architecture Questions

  1. Design a URL shortener (like bit.ly) — complete backend architecture.
  2. Design a rate limiter — support distributed systems.
  3. Design a real-time chat application — WebSockets, scaling strategy.
  4. Design a file storage system (like Dropbox) — chunking, deduplication.
  5. Design a notification system — email, SMS, push notifications.
  6. Design an e-commerce cart system — handle race conditions, inventory management.
  7. Design a job queue system — Bull, Redis, failure handling.
  8. Design an analytics dashboard — handling time-series data efficiently.
  9. Design a payment gateway integration — security, idempotency.
  10. Design a microservices architecture for a blog platform — service boundaries, communication.

Performance & Optimization Questions

  1. How to optimize a Next.js app that has 3-second initial load time? Step-by-step approach.
  2. API endpoint taking 10 seconds to respond — profiling and optimization strategy.
  3. React app re-rendering 100 times on single user action — identify and fix.
  4. MongoDB query using 4GB of RAM — aggregation optimization techniques.
  5. Node.js app using 100% CPU — identify bottleneck without production downtime.
  6. Implement caching strategy for REST API — cache invalidation, TTL strategies.
  7. How to reduce Docker image size from 2GB to 200MB? Best practices.
  8. Optimize bundle size in React app — tree shaking, code splitting, dynamic imports.
  9. Database connection pool sizing — how to determine optimal pool size?
  10. Implement database read replicas — read/write split in Node.js application.

DevOps & Deployment Questions

  1. Explain CI/CD pipeline for Node.js application — GitHub Actions, Jenkins.
  2. Zero-downtime deployment strategy — blue-green, canary deployment.
  3. How to handle environment variables securely? Secrets management.
  4. Explain Docker multi-stage builds — optimize image layers.
  5. How to monitor Node.js app in production? PM2, New Relic, Prometheus.
  6. Implement health check endpoint — readiness vs liveness probes.
  7. How to handle database migrations in production? Rollback strategy.
  8. Explain horizontal vs vertical scaling — when to use each?
  9. How to implement logging in distributed systems? Centralized logging (ELK stack).
  10. Container orchestration — Kubernetes basics for Node.js apps.

Code Review & Best Practices Questions

  1. Review this code — find all issues:

javascript

app.get('/users/:id', (req, res) => {
User.findById(req.params.id).then(user => {
res.json(user);
});
});

  1. What's wrong with this Mongoose schema?

javascript

const userSchema = new Schema({
email: String,
password: String
});

  1. Review this React component:

javascript

function List({ items }) {
return items.map(item => <div>{item.name}</div>);
}

  1. What's the security issue here?

javascript

app.get('/search', (req, res) => {
const query = req.query.q;
db.collection('posts').find({ $where: query });
});

  1. Identify the performance problem:

javascript

useEffect(() => {
const data = expensiveOperation();
setData(data);
});


Testing Questions

  1. How to test async Express routes? Jest, Supertest.
  2. Difference between unit, integration, and E2E tests — examples for each.
  3. How to mock MongoDB in tests? mongodb-memory-server.
  4. Testing React components — React Testing Library best practices.
  5. How to test private functions? Should you test them?
  6. Implement test coverage — what percentage is ideal?
  7. How to test error scenarios? Error boundaries, API failures.
  8. Testing WebSocket connections — approach and tools.
  9. How to handle flaky tests? Identification and fixes.
  10. Test database transactions — rollback after each test.

Bonus: Algorithm & Data Structure Questions

  1. Implement LRU Cache — O(1) get and put.
  2. Two Sum problem — optimal solution.
  3. Reverse a linked list — iterative and recursive.
  4. Validate balanced parentheses — stack approach.
  5. Find duplicate in array — without extra space.
  6. Implement debounce and throttle — from scratch.
  7. Binary search — find element in sorted array.
  8. Merge two sorted arrays — in-place.
  9. Implement a trie (prefix tree) — autocomplete use case.
  10. Detect cycle in linked list — Floyd's algorithm.

Top comments (0)