Production Recipe Vault
Node.js Production Performance Cheat Sheet
Robust recipes for event loop microtasks, streams pipelines, buffer allocations, and graceful shutdowns.
Event Loop & Scheduling Primitives
setImmediate vs setTimeout(0)
Scheduling execution order in poll vs check phases
// Inside I/O callback, setImmediate ALWAYS runs before setTimeout:
fs.readFile('file.txt', () => {
setImmediate(() => console.log('Immediate (Check Phase)'));
setTimeout(() => console.log('Timeout (Timers Phase)'), 0);
});Pro Tip: setImmediate executes immediately after the Poll phase, without waiting for the 1ms timer clock.
Microtask Flush with queueMicrotask
Standard Web API for scheduling Promise microtasks
queueMicrotask(() => {
console.log('Runs before any Timers or I/O callbacks');
});Pro Tip: Standardized replacement for Promise.resolve().then(fn).
Streams & Pipeline Utilities
Robust Stream Pipeline with pipeline()
Automatic backpressure handling and error cleanup
import { pipeline } from 'stream/promises';
import fs from 'fs';
import zlib from 'zlib';
await pipeline(
fs.createReadStream('input.txt'),
zlib.createGzip(),
fs.createWriteStream('input.txt.gz')
);Pro Tip: pipeline() automatically destroys all streams if any stream in the chain emits an error.
Safe Buffer Allocation
Zero-filled memory allocation
// Always use Buffer.alloc for security: const safeBuffer = Buffer.alloc(1024); // Zero-filled // NEVER send allocUnsafe without full overwrite: const fastBuffer = Buffer.allocUnsafe(1024);
Pro Tip: allocUnsafe can leak previous RAM secrets if sent directly to network sockets.
Production Hardening & Graceful Shutdown
Graceful Shutdown Handler
Drain HTTP connections before exit
process.on('SIGTERM', () => {
server.close(() => {
// Disconnect DB pools
process.exit(0);
});
// Fallback kill after 10s:
setTimeout(() => process.exit(1), 10000).unref();
});Pro Tip: .unref() prevents the fallback timer from keeping the process alive.