How Node.js Handles Concurrent Requests Efficiently
non-blocking I/O. It processes many requests by delegating operations like file or network access to the system, allowing the event loop to continue handling other requests without waiting.Syntax
Node.js uses an event-driven model with asynchronous callbacks or promises to handle concurrent requests. The core pattern involves creating a server that listens for requests and processes them without blocking the main thread.
Key parts:
http.createServer(): creates the server.requestListener: function called on each request.event loop: manages callbacks and asynchronous tasks.
import http from 'http'; const server = http.createServer((req, res) => { // Handle request asynchronously res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World'); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
Example
This example shows a Node.js server handling multiple requests concurrently. It uses setTimeout to simulate a slow operation without blocking the event loop, allowing other requests to be processed immediately.
import http from 'http'; const server = http.createServer((req, res) => { if (req.url === '/slow') { // Simulate slow operation setTimeout(() => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Slow response finished'); }, 3000); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Fast response'); } }); server.listen(3000, () => { console.log('Server running on port 3000'); });
Common Pitfalls
Common mistakes when handling concurrent requests in Node.js include blocking the event loop with heavy computations or synchronous code. This causes delays for all requests because Node.js runs on a single thread.
Always use asynchronous APIs and avoid long-running synchronous tasks in request handlers.
import http from 'http'; // Wrong: Blocking event loop with synchronous code const server = http.createServer((req, res) => { if (req.url === '/block') { // Blocking loop for 5 seconds const start = Date.now(); while (Date.now() - start < 5000) {} res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Blocked for 5 seconds'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Fast response'); } }); server.listen(3000, () => { console.log('Server running on port 3000'); });
Quick Reference
- Event Loop: Core mechanism that handles callbacks and asynchronous tasks.
- Non-blocking I/O: Allows Node.js to start operations and continue without waiting.
- Asynchronous APIs: Use callbacks, promises, or async/await to avoid blocking.
- Single Thread: Node.js runs JavaScript on one thread but delegates I/O to the system.