Node.js Architecture - How does Node.js handle asynchronous tasks?

Node.js Architecture - How does Node.js handle asynchronous tasks?

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » Read more

Problem

In the previous article, we learned about Node.js being single-threaded and the differences between synchronous and asynchronous I/O tasks. In this article, I will talk about how Node.js handles asynchronous tasks.

First, let me review some concepts to give you a clearer understanding before diving into how Node.js handles asynchronous tasks.

What is asynchronous?

If you have worked with other languages like C, PHP, or Java before learning JavaScript, you might be familiar with synchronous programming. Synchronous programming runs the code sequentially, meaning it executes one line of code after another. Let's take an example of reading a file in PHP:

<?php
$content = readfile("file.txt");
echo $content;
?>

In this PHP code, the readfile function reads the content of "file.txt" and immediately echoes it to the screen using the echo statement, because echo is called after readfile has the result. This is synchronous programming.

Now, in JavaScript, a similar file reading function looks like this:

const content = readFile("file.txt");
console.log(content);

The output will not be the content of "file.txt" because readFile is an asynchronous function. It does not get processed immediately. Instead, it delegates this task to another entity (specifically the Thread Pool) and continues executing the console.log function right away. At this point, the content does not have the result of reading the file, so the output will definitely be something else.

You might ask:

Why is asynchronous useful for Node.js?

How does Node.js handle asynchronous tasks?

Let's start by looking at the components in the Node.js architecture:

Thành phần Node.js

The Call Stack is responsible for running JavaScript code in a specific order. Since there is only one Call Stack, only one piece of JavaScript code can be executed at a time. This can cause a bottleneck if the code takes a long time to process.

The Node.js Standard Library contains components that interact with the system, such as files, HTTP requests, DNS resolution, provided by libuv. In other words, these components handle asynchronous I/O tasks.

The Event Loop is simply an infinite loop that always checks if the Call Stack is empty. If it is empty, it moves the callback functions from the Event Queue to the Call Stack in a First-In-First-Out (FIFO) order. The callback functions in the Event Queue are added by the Thread Pool after completing an I/O operation.

In summary, Here is how Node.js handles a JavaScript code snippet with asynchronous code:

When running a JavaScript file, the JavaScript code is pushed into the Call Stack for processing. If it encounters any asynchronous code, it delegates that code to the Thread Pool and continues with the processing. The Thread Pool takes the task from the Call Stack and processes it immediately. Once it has the result, it places the result into the callback function registered in the Event Queue for that I/O operation.

Meanwhile, the Event Loop continuously checks if the Call Stack has finished processing all the JavaScript code in the file. If it is empty, it moves the callback functions from the Event Queue to the Call Stack for further processing.

If there are more asynchronous code snippets in the callback functions, the process continues repeating the steps mentioned above.

We can see that even though Node.js only has one Call Stack for processing JavaScript code, there are multiple Thread Pools for handling asynchronous I/O tasks, which can take a longer time. Node.js leverages the power of V8 for handling JavaScript code execution, so the speed of JavaScript code execution depends entirely on V8, which is known for its "fast" performance.

By default, there are 4 Thread Pools created upon startup, but this number can be increased up to 1024 depending on the server configuration to tune it accordingly.

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...