Event loop blocking: synchronous code chiếm CPU lâu khiến event loop không xử lý được I/O callbacks, timers, requests khác.
Ví dụ thực tế:
JSON.parse(fs.readFileSync('huge.json'))— 200MB JSON parse tốn ~2s block hoàn toàn;- regex backtracking —
/^(a+)+$/.test('aaaaaaaaab')chạy exponential time với input độc hại (ReDoS); - crypto sync —
crypto.pbkdf2Sync()trong request handler; - nested loops O(n²) trên large arrays
Đo blocking: node --prof app.js tạo V8 profile; clinic doctor -- node app.js từ clinic.js package hiển thị event loop lag rõ ràng; perf_hooks API đo eventLoopUtilization().
Fix: chia nhỏ task với setImmediate() để yield event loop giữa chunks; offload sang Worker Threads cho CPU-intensive; dùng streaming thay vì load toàn bộ vào memory; safe-regex package detect ReDoS vulnerable patterns.
Threshold: bất kỳ synchronous operation > 10ms trong request handler là vấn đề cần xem xét.
Event loop blocking: synchronous code occupies the CPU for so long that the event loop cannot process I/O callbacks, timers, or other requests.
Real-world examples:
JSON.parse(fs.readFileSync('huge.json'))— parsing a 200MB JSON file takes ~2s and blocks completely;- regex backtracking —
/^(a+)+$/.test('aaaaaaaaab')runs in exponential time with malicious input (ReDoS); - sync crypto —
crypto.pbkdf2Sync()inside a request handler; - nested O(n²) loops on large arrays
Measuring blocking: node --prof app.js creates a V8 profile; clinic doctor -- node app.js from the clinic.js package shows event loop lag clearly; the perf_hooks API measures eventLoopUtilization().
Fixes: break up tasks with setImmediate() to yield the event loop between chunks; offload to Worker Threads for CPU-intensive work; use streaming instead of loading everything into memory; use the safe-regex package to detect ReDoS-vulnerable patterns.
Threshold: any synchronous operation taking longer than 10ms in a request handler is worth investigating.