Node.js Event Loop Phases: Understanding the Inner Workings

𝐇𝐨𝐰 𝐭𝐡𝐞 𝐍𝐨𝐝𝐞.𝐣𝐬 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 𝐖𝐨𝐫𝐤𝐬 𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥𝐥𝐲 At a high level, the Event Loop is a continuous cycle that checks for tasks, executes callbacks, and waits for new events. But internally, it’s more structured than most people think. It runs in phases, each handling specific types of callbacks: • 𝐓𝐢𝐦𝐞𝐫𝐬 → Executes callbacks from 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵() and 𝘴𝘦𝘵𝘐𝘯𝘵𝘦𝘳𝘷𝘢𝘭() whose delay has expired. • 𝐏𝐞𝐧𝐝𝐢𝐧𝐠 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 → Runs certain system-level I/O callbacks deferred from the previous loop. • 𝐏𝐨𝐥𝐥 → Retrieves completed I/O events and executes their callbacks; this is where most request handling happens. • 𝐂𝐡𝐞𝐜𝐤 → Executes callbacks scheduled with 𝘴𝘦𝘵𝘐𝘮𝘮𝘦𝘥𝘪𝘢𝘵𝘦(). • 𝐂𝐥𝐨𝐬𝐞 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 → Runs cleanup callbacks like socket.on('close'). • 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 (𝐛𝐞𝐭𝐰𝐞𝐞𝐧 𝐞𝐯𝐞𝐫𝐲 𝐩𝐡𝐚𝐬𝐞) → Executes 𝘱𝘳𝘰𝘤𝘦𝘴𝘴.𝘯𝘦𝘹𝘵𝘛𝘪𝘤𝘬() and resolved Promises before moving to the next phase. 𝐖𝐡𝐚𝐭 𝐓𝐡𝐢𝐬 𝐌𝐞𝐚𝐧𝐬 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥𝐥𝐲 • If you run heavy CPU code → the loop can’t move to the next phase • If the poll phase is blocked → no new requests are processed • If you flood microtasks → timers and I/O get delayed • Async I/O doesn’t block — but CPU work does If your Node.js app feels “slow,” measure event loop delay before blaming the database or framework. #NodeJS #JavaScript #BackendDevelopment #V8 #SystemDesign #PerformanceEngineering #EventLoop

  • text

To view or add a comment, sign in

Explore content categories