Node.js uses a single-threaded event loop. If a synchronous function runs for a long time, it blocks the event loop. This means new incoming requests cannot be processed until the function finishes, increasing response time.
const http = require('http'); http.createServer(async (req, res) => { const data = await fetchDataFromDB(); res.end(data); }).listen(3000);
Using async/await lets Node.js pause the current request handler without blocking the event loop. This allows the server to process other incoming requests while waiting for the database, improving overall response time.
app.use((req, res, next) => {
const start = Date.now();
while (Date.now() - start < 100) {
// busy wait for 100ms
}
next();
});The busy wait loop blocks the event loop for 100ms on every request. This prevents Node.js from handling other requests during that time, increasing response time significantly.
setImmediate to defer a CPU-heavy task without blocking the response?app.get('/heavy', (req, res) => { // CPU-heavy task here res.end('Done'); });
Option B defers the CPU-heavy task using setImmediate, allowing the response to be sent immediately. This prevents blocking the event loop and improves response time.
/data endpoint?const http = require('http'); let cache = null; async function fetchData() { return new Promise(resolve => setTimeout(() => resolve('data'), 100)); } http.createServer(async (req, res) => { if (req.url === '/data') { if (cache) { res.end(cache); } else { const data = await fetchData(); cache = data; res.end(data); } } else { res.end('Not found'); } }).listen(3000);
The first request calls fetchData, which takes 100ms. The result is stored in cache. The second request uses the cached data and responds immediately, reducing response time.