𝗡𝗼𝗱𝗲.𝗷𝘀 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱

Node.js uses a single thread. You might wonder how it handles thousands of requests at once.

The secret is the Event Loop.

Instead of waiting for a task to finish, Node.js sends time consuming tasks to the operating system. It keeps moving to the next task. This makes your applications fast and responsive.

Blocking vs Non-blocking

If you use sync functions like readFileSync, the server stops. It waits for the file to finish reading. No other user gets a response. This kills your performance.

If you use fs.readFile, the server keeps running. It handles other requests while the file reads in the background.

How the Event Loop works

The loop moves through several stages:

• Timers: Handles setTimeout and setInterval. • Pending Callbacks: Handles system level errors. • Poll: Receives new connections and handles I/O like database queries. • Check: Handles setImmediate. • Close Callbacks: Handles socket closures.

The Priority Order

Not all tasks are equal. Node.js uses two queues:

  1. Microtask Queue: This holds Promises.
  2. Callback Queue: This holds setTimeout and I/O.

The Microtask Queue always runs first. If you have a Promise and a setTimeout, the Promise will finish before the timer.

The Call Stack and Queues

The Call Stack tracks what code runs right now. When a task finishes, its callback enters a queue. The Event Loop waits until the Call Stack is empty before it pulls tasks from the queue.

Avoid these mistakes:

• Do not use infinite loops. This freezes your entire app. • Do not use synchronous file methods in production. • Do not run heavy math or video processing on the main thread.

For heavy tasks, use Worker Threads or background jobs.

Summary

Node.js is fast because it does not wait. It delegates I/O tasks and uses the Event Loop to manage results. This architecture allows one thread to serve many users.

What part of the Event Loop was hardest for you to learn? Tell me in the comments.

Source: https://dev.to/synfinity-dynamics-pvt-ltd/nodejs-event-loop-explained-how-nodejs-handles-thousands-of-concurrent-requests-1heo