Skip to main content

Command Palette

Search for a command to run...

The Node.js Event Loop Explained

Updated
5 min read

What are We Gonna Study?

Hey there folks! Hope you are doing great in your life, and enjoying the coding part of it too!

Today, we'll be talking about some topics realtion to NodeJS Event Loop which are:

  1. What the event loop is

  2. Why Node.js needs an event loop

  3. Task queue vs call stack (conceptual only)

  4. How async operations are handled

  5. Timers vs I/O callbacks (high level)

  6. Role of event loop in scalability

Understanding the event loop is like looking under the hood of a high-performance engine.

This is what allows NodeJS to perform non-blocking I/O tasks, despite operating on a single thread!

So, bear with me till the very end of it, with all your focus here (don't focus on her, she isn't focusing on you is she?)


The Problem: Why NodeJS needs Event Loop?

What other web servers do:

  • Most of the traditional servers handle every request by creating a new thread for it.

  • It is effective but is it memory-efficient? The answer is No, it consumes a lot of memory.

But NodeJS on the other hand takes a different path:

  • it has a single main thread which executes your code, If the thread stucks, your server will freeze.

  • To prevent this blocking, it requires a manager and that is where Event loop comes into the picture.

It is relatable isn't it? You also need her to manage you and NodeJS also needs Event loop to manage it...

But the only difference is that, Event Loop manages NodeJS, but she doesn't even care about you :)

Relatable++


What is Event Loop?

So, now you understand why NodeJS needs the Event Loop, let's now understand what Event Loop is?

  • Think about it as the Task Manager or a traffic police for NodeJS, its job is to monitor the status of your code, and decide what to do next.

  • It also coordiantes your code with the device's resource (like hard drive or network, etc) that takes time to respond.


Task Queue VS Call Stack

Call Stack

  • This is the place where code is currently living when its been executed.

  • They are pushed inside call stack, get executed, and then removed.

Task Queue

  • When an asynchronous operation (like reading a file) finishes, its "callback" (the code that should run afterward) sits in this queue, waiting for its turn.

  • And when the turn comes, it gets executed.


Analogy

Imagine a Fast Food Restaurant:

  1. The Register (Call Stack): You place your order, The cashier takes it and immediately hands it to the kitchen.

  2. The Waiting Area (Task Queue): You don't stand there, you move to the side so the next person can order. You are now in the "queue."

  3. The Event Loop: Once the register is empty, the cashier looks at the waiting area and calls the next person whose food is ready to come back to the counter.

That is your Call Stack, Task Queue and Event Loop!

Well i found one more thing relatable...

It looks like she never putted you in the Call Stack, you were always in her Task Queue (always waiting, but never replied 😔)


Handling Async Operations

  • When you trigger an asynchronous operation (such as reading file or hashing password), NodeJS never waits for it to get finished.

  • Instead, it assigns the task to the System Kernel or Worker Pool.

  • The main thread stays free and keeps running the code, like nothing happened.

  • Once, the task is completed, the system notifies the Node, and the callback is moved to the Task Queue, where it will eventually be processed to Call Stack by Event Loop.


Here is a diagram to visulaize the flow:


Timers VS I/O Callbacks

  • See, I am keeping the blog. beginner friendly but still i would like to tell that, Event Loop doesn't gives same priority to each tasks.

  • Yes, it is just like her, she doesn't also gives you less priority 💔🥀

  • Timers: Functions like setTimeout() or setInterval(), The Event Loop checks if the specified time has elapsed and executes them as soon as possible.

  • I/O Callbacks: These are responses from the "outside world," such as reading a file from a disk, a database query result, or an incoming network request.

  • The Event Loop cycles through these, ensuring that timers and I/O tasks both get their fair share of execution time.


Here is another diagram for visulaization:


Why This Makes NodeJS Scalable?

Oh come on, you already know that!

  • NodeJS is memory efficient (single threaded).

  • Event loop allows it to handle requests without blocking.

  • A multithreaded might crash at thousands not because of efficiency but becasue of lack of memory, but NodeJS handles it out of the box.


Wrap Up!

So, that was it for today's blog, I recommend you to go to the original NodeJS Documentation for deeper understanding and checkout this video too!

https://youtu.be/Q6boRNAoDr0?si=jvQVO4qHrtKqt24k

But it is in hindi langauge.

Anyways, hope you enjoyed this video, i know you may have got traumatized too! But that's also necessary!

Let's end it here, I'll catch you up in the next blog until then keep coding and enjoynig your life.

NodeJS Backend

Part 4 of 15

This is an ongoing series that will most likely cover the following topics - Async Code in Node.js: Callbacks and Promises - Sessions vs JWT vs Cookies: Understanding Authentication Approaches - Storing Uploaded Files and Serving Them in Express - URL Parameters vs Query Strings in Express.js - How Node.js Handles Multiple Requests with a Single Thread - Setting Up Your First Node.js Application Step-by-Step - Creating Routes and Handling Requests with Express - JWT Authentication in Node.js Explained Simply - What is Node.js? JavaScript on the Server Explained - Handling File Uploads in Express with Multer - What is Middleware in Express and How It Works - Why Node.js is Perfect for Building Fast Web Applications - REST API Design Made Simple with Express.js - Blocking vs Non-Blocking Code in Node.js - The Node.js Event Loop Explained

Up next

Why Node.js is Perfect for Building Fast Web Applications

What are We Gonna Study? Hey there folks, hope you are doing great in your life and enjoying every bit of it! Today we'll not discuss about any code or something like that but we'll discuss why even w

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!