<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sachin Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sachin Kumar on Medium]]></description>
        <link>https://medium.com/@notreallystatic?source=rss-10d230ffc98a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-AX7511SWdkruBfU.jpg</url>
            <title>Stories by Sachin Kumar on Medium</title>
            <link>https://medium.com/@notreallystatic?source=rss-10d230ffc98a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:58:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@notreallystatic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Is Node Js Single-threaded? The Architecture of Node Js.]]></title>
            <link>https://medium.com/swlh/is-node-js-single-threaded-the-architecture-of-node-js-69f8c0d59b00?source=rss-10d230ffc98a------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f8c0d59b00</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Sachin Kumar]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 08:23:00 GMT</pubDate>
            <atom:updated>2020-09-29T12:51:34.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to understanding Node Js and to write better code.</h4><p>Well, yes and no. Okay, first of all, don’t get overwhelmed with the wide range of crazy answers on this question. Also, I am not at all saying that they are wrong, but let’s see what happens under the hood.</p><p>To understand what magic the <em>Node Js</em> potion performs, you should be aware of its ingredients first. <em>Node Js </em>has two main dependencies:</p><ol><li>V8<br>It provides the Javascript Engine i.e., to run JS outside the browser.</li><li>libuv:<br>This is a<em> C </em>library used to access the underlying OS features such as networking, file systems, concurrency, cryptography, etc<em>(I/O intensive &amp; CPU-intensive tasks)</em>. Libuv includes a thread pool for offloading work for some things that can’t be done asynchronously at the OS level.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*0-sExR87yqqJ05SQS6vzdw.jpeg" /></figure><p>In Node Js there are two types of threads:</p><ol><li><strong>Event Loop</strong>: <em>Handles the initialization &amp; callbacks(aka: main loop, the main thread, event thread, etc).</em></li><li><strong>Threadpool</strong>: A <em>pool of k Workers in a Worker Pool.</em></li></ol><p>Whenever you run a js file, Node first creates a single thread and runs everything in that thread, called the Event Loop. But, when it comes across some tasks like fs.readFile() (<em>fs is the File System module, it enables you to interact with the file system</em>) or using crypto.pbkdf2()(<em>crypto module provides you with cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions. </em>pbkdf2()<em> is one such function to hash your password</em>), <em>Node</em> offloads this work to the thread pool.</p><p>That’s enough theory, let us write some code to understand it better.<br>Make a file called <em>“hashing.js”</em> and write the following <a href="https://pastebin.com/AtWFDdnT">code</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nHWt7rS1Dvtbbks-ggMpTQ.jpeg" /></figure><p>If you want to learn more about pbkdf2() function, go <a href="https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">here</a>. For now, you can just think that it hashes your password and takes a considerable amount of time to execute.</p><p>If you execute this code, you will see that it takes approximately one second to finish execution(957ms on my machine). This time might vary on your machine, but it’ll be close to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*jsHs-RCOAKVCgvD2e9TRaQ.jpeg" /><figcaption>Output 1</figcaption></figure><p>So far, so good. Now uncomment <em>line 16</em> and run the program again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*Bsr8zO_Il9_9KI1xv5tBQA.jpeg" /><figcaption>Output 2</figcaption></figure><p>This time we see that it takes approximately one second again to execute the whole program, but if <em>Node </em>truly was single-threaded then it would have taken two seconds to execute this. It ain’t the case though, what happens is Node offloads this work to the <em>Thread Pool, </em>which has four threads by default. Since my machine has two cores(two processors), both the threads can run simultaneously and hence, the execution takes one second.</p><p>Now, uncomment line 17–19 and run the program. This time you will see some amazing results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*2NlhN0PtCZ52vyAYYlUNqw.jpeg" /></figure><p>It takes 1.7 seconds(approx, 1700ms) for the first four function calls and almost one second extra(0.8s to be specific) for the last function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*jpQUqpaV5hyhzAqMVZYbxw.png" /></figure><p>Since the default size of t<em>hreadpool</em> is four, the first four pbkdf2()calls are assigned to all the four threads. Now, each thread gets a fair share of CPU time, and since we have four tasks, each taking approx one second to finish their execution and since we have two CPU cores, it will take a total of two seconds(approx) for all the tasks to complete their execution. As soon as one of the threads in the <em>threadpool </em>finishes it’s execution, it will take up the next task in the queue, pbkdf2() [hash(5)]in this case and will begin its execution.</p><h3>Can you change the threadpool size?</h3><p>Yes, you can.<br>On a Windows machine, you can do it by setting it before calling the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*nKIqkRl12w0mYNk0lPb3YQ.jpeg" /><figcaption>set UV_THREADPOOL_SIZE=1</figcaption></figure><p>In this case, you can see that it takes approximately one second(around 0.9s) for the first execution of “pbkdf2”. Since we have set the size of Threadpool to just one, it will take a total of 4.4s to execute five “pbkdf2” calls as the event loop will take only one task at a time.</p><p>On a Linux system, you can do it by writing process.env.UV_THREADPOOL_SIZE = size;at the start of your program.</p><h3>Things you should cling to:</h3><ol><li>Never put any heavyweight tasks in the callbacks as it is executed by the event loop. By doing so, you will block the <em>event-loop </em>thread and your other tasks won’t get executed, like API calls in a server.</li><li>Always keep work associated with each client minimal as it ensures the maximum throughput(client request/second) of your server.</li><li>Avoid vulnerable regular expression in callbacks as they are computationally expensive.</li><li>Minimize the use of JSON.parse and JSON.stringify as they have a time complexity of O(n) , where n is the length of the input. So for large values of n, they can take a surprisingly long time.</li></ol><h4>References:</h4><ol><li><em>Node Js </em><a href="https://nodejs.org/en/docs/guides/dont-block-the-event-loop/"><em>Docs</em></a></li><li><em>Node Js: Advanced Concepts</em> course on <a href="https://www.udemy.com/course/advanced-node-for-developers/">Udemy</a></li></ol><p>So, this is how the mysterious Node Js works behind the scenes. If this piece has helped you get a clearer picture of <em>Node</em>, spread a word on <a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fmedium.com%2F%40notreallystatic%2F69f8c0d59b00%3Fsource%3Dfriends_link%26sk%3D06b4972db2e699b8ef35d3a1a3ead02c&amp;via=notreallystatic&amp;text=Hey%21%20Check%20out%20this%20cool%20blog%20to%20understand%20the%20architecture%20of%20Node%20js.%20%20&amp;hashtags=nodejs%2Cnode%2Carchitecture%2Cbackend%2Cjavascript%2Cdevcommunity">twitter</a> and share with your friends as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f8c0d59b00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/is-node-js-single-threaded-the-architecture-of-node-js-69f8c0d59b00">Is Node Js Single-threaded? The Architecture of Node Js.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>