Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Comparing Data Structures in JavaScript (Arrays vs Objects)

    JavaScript

    Agile Software Development, Scrum part 1

    Interview

    Interview with Stepan

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, November 12
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js
    JavaScript

    Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js

    Shadid HaqueBy Shadid HaqueJanuary 24, 2020No Comments8 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Advanced Node.Js: A Hands on Guide to Event Loop, Child Process and Worker Threads in Node.Js
    Advanced NodeJs
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Advanced NodeJs
    Advanced NodeJs

    What makes Node.js so performant and Scalable? Why is Node the technology of choice for so many companies? In this article, we will answer these questions and look at some of the advanced concepts that make Node.js unique. We will discuss:

    1. Event Loop ➰
    2. Concurrency Model 🚈
    3. Child Process 🎛️
    4. Threads and Worker Threads 🧵

    JavaScript developers with a deeper understanding of Node.js reportedly earn 20% ~ 30% more than their peers. If you are looking to grow your knowledge of Node.js then this blog post is for you. Let’s dive in 🤿!!

    What happens when you run a Node.js Program?

    when we run our Node.js app it creates

    • 1 Process 🤖
    • 1 Thread 🧵
    • 1 Event Loop ➰

    A process is an executing program or a part of an executing program. An application can be made out of many processes. Node.js runtime, however, initiates only one process.

    A thread is a basic unit to which the operating system allocates processor time. Think of threads as a unit that lets you use part of your processor.

    An event loop is a continuously running loop (just like a while loop). It executes one command at a time, more on this later. For now, let’s think of it as a while loop that will run until Node has executed every line of code.

    Now, let’s take a look at how our code runs inside of Node.js instance.

    console.log('Task 1');
    console.log('Task 2');
    // some time consuming for loop
    for(let i = 0; i < 1000000000; i++) {
    }
    console.log('Task 3');

    What happens when we run this code? It will first print out `Task 1` then `Task 2` and then it will run the time consuming for loop (we won’t see anything in the terminal for a couple seconds) and finally it will print out `Task 3`. Let’s look at a diagram of what’s actually happening.

    Component 1
    Component 1

    Node puts all our tasks into an Events queue and sends them one by one to the event loop. The event loop is single-threaded and it can only run one thing at a time. So it goes through Task 1 and Task 2 then the very big for loop and then it goes to Task 3. This is why we see a pause in the terminal after Task 2 because it is running the for a loop.

    Now let’s do something different. Let’s replace that for loop with an I/O event.

    console.log('Task 1');
    console.log('Task 2');
    fs.readFile('./ridiculously_large_file.txt', (err, data) => {
        if (err) throw err;
        console.log('done reading file');
        process.exit();
    });
    console.log('Task 3');

    Pro tip: you can generate a 100mb file in linux or mac just by running this command `dd if=/dev/urandom of=ridiculously_large_file.txt bs=1048576 count=100`

    We would naturally assume that this will output something similar. Just like the for loop reading big files takes time and the execution on the event loop will take some time. We however, get something totally different.

    Task 1
    Task 2
    Task 3
    done reading file

    But what caused this? How did Task 3 get executed before the file was read. Well let’s take a look at the visuals below to see what’s happening

    Component 2
    Component 2

    I/O tasks, network requests, database processes are classified as blocking tasks in Node.js. So whenever the event loop encounters these tasks it sends them off to a different thread and moves on to the next task in events queue. A thread gets initiated from the thread pool to handle each blocking tasks and when it is done, it puts the result in a call-back queue. When the event loop is done executing everything in the events queue it will start executing the tasks in the call-back queue.  So that’s why we see `done reading file` at the end.

    Read More:  Contentful+Gatsby = Smarter content management

    What makes the Single Threaded Event Loop Model Efficient? ⚙️

    JavaScript was created to do just a simple things in the web browsers such as form validation or simple animations. This is why it was built with the single-threaded event loop model. Running everything in one thread is considered as a disadvantage.

    However, in 2009 Ryan Dahl the creator of Node saw this simple event loop model as an opportunity to build a lightweight web server.

    To better understand what problem Node.js solves we should look at the what typical web servers were like before Node.js came into play.

    This is how a traditional multi-threaded web application model handles request:

    1. It maintains a thread pool (a collection of available threads)
    2. When client request comes in a thread is assigned
    3. This thread will take care of reading Client requests, processing Client requestS, performing any Blocking IO Operations (if required) and preparing Response.
    4. This thread is not free until a response is sent back

    Main drawback of this model is handling concurrent users. So let’s say if we have more users visiting our sites than there are available threads then some users will need to wait until a thread frees up to get response. If a lot of users are performing blocking I/O tasks then this wait time also increases. This is also very resource-heavy if we are expecting one million concurrent users we better make sure we have enough threads to handle those requests.

    Moreover, the server itself start to slow down because of increasing load. There’s also the overhead of context switching between threads and writing applications to optimize threads resource sharing can be painful.

    Because of the single-threaded model Node.js, it doesn’t need to spin off new threads for every single request. Node.js also delegates blocking tasks to other components as we saw earlier. Since we don’t really care about many threads it makes node.js very lightweight and ideal for microservice-based architecture.

    Drawbacks of Node’s Single Threaded Model !!!

    The single-threaded event loop architecture uses resources efficiently but it doesn’t have some drawbacks. The Node.js instance cannot immediately benefit from multiple cores in your CPU. A Java application can have immediate access to more memory as we upgrade our hardware but Node runs on a single thread.

    This is 2020 😄 and we are seeing more and more complicated web applications. What if our application needs to do complex computation, run a machine learning algorithm? Or What if we want to run a complicated crypto algorithm? In this case we have to harness the power of multiple cores to increase performance.

    Read More:  How to Upload Images to a Cloud Storage(Imgur) in an Angular Application

    Languages like Java and C# can programmatically initiate threads and harness the power of multiple cores. In Node.js that is not an option as we saw earlier. Node’s way of solving this problem is child_process.

    Child Process in Node

    The child_process module gives node the ability to spawn child process by accessing operating system commands.

    Let’s assume we have a REST endpoint that has a long-running function and we would like to use multiple cores in our processor to execute this function.

    Here’s our code

    const { fork } = require('child_process');
     
    app.get('/endpoint', (request, response) => {
       // fork another process
       const process_ml_algo = fork('./process_data.js');
       const data = request.body.data;
       // send send the data to forked process
       process_ml_algo.send({ data });
       // listen to forked process 
       process.on('ml_algo', (result) => {
         log.info(`ml_algo executed with ${result}`);
       });
       return response.json({ status: true, sent: true });
    });
    
    // receive message from master process
    process.on('ml_algo', async (message) => {
        const result = await runMachineLearningProcess(message.mails); 
     
        // send response to master process
        process.send({ result: result });
    });
    

    In the example above we demonstrate how we can spin off a new process and share data between them. Using the forked process we can take advantage of multiple cores of CPU.

    You can take a look at all the methods of child processes in the official node docs.

    Here is a diagram of how child process work

    Component 3
    Component 3

    child_process is a good solution but there’s another option. child_process module spins off new instances of Node to distribute the workload all these instances will each have 1 event loop 1 thread and 1 process. In 2018 Node.js introduced worker_thread. This module allows node the ability to have

    • 1 Process
    • Multiple threads
    • 1 Event Loop per thread

    Yes!! You read that right 😄.

    Component 4
    Component 4
    const { Worker, workerData, isMainThread, parentPort } = require('worker_threads');
     
    if (isMainThread) {
      const worker1 = new Worker(__filename, { workerData: 'Worker Data 1'});
      worker1.once('message', message => console.log(message));
      const worker2 = new Worker(__filename, { workerData: 'Worker Data 2' });
      worker2.once('message', message => console.log(message));
    } else {
      parentPort.postMessage('I am ' + workerData);
    }
    

    We check if it is the main thread and then create two workers and pass on messages. On the worker thread the data gets passed on through `postMessage` method and the workers execute the command.

    Since worker_threads makes new threads inside the same process it requires less resources. Also we are able to pass data between these threads because they have the shared memory space.

    As of January 2020 worker_threads are fully supported in the Node LST version 12. I highly recommend reading up the following post if you want to learn more about worker_threads.

    Node.js multithreading

    And that’s it!!!

    In this we looked over how the event loop model works in Node.js, we discussed some of the pros and cons of single-threaded model and looked at couple of solutions. We didn’t go over all the functionalities of child_process and worker_threads. However, I hope that this article provided you with a brief introduction to these concepts and why they exist. Please let me know if you have any feedback. Until next time 👋👋

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Shadid Haque

      Related Posts

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Conducting Effective Post-Project Evaluations: A Guide

      December 16, 2024

      Strategies for Keeping Projects on Track and Meeting Deadlines

      December 10, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Remote Job April 10, 2019

      How Google, Apple, and Other Tech Companies Organize Their Remote Teams

      What are the best practices that tech companies use to organize their remote teams? Let’s find out!

      13. Уроки Node.js. Разработка, supervisor

      September 21, 2016

      Implementing Machine Learning in Web Applications with Python and TensorFlow

      April 7, 2023

      Tim Burgess: The Future of Work Will Revolve Heavily Around Flexibility

      August 3, 2019

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Interview with Philipp

      Interview September 20, 2017

      Mastering the Interview Process for Management Roles

      Interview December 7, 2024

      Essential Recruitment Metrics: Key Measures for Success

      Recruitment November 25, 2024

      Mastering Lean Project Management: Essential Principles Guide

      JavaScript December 4, 2024

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Programming

      MongoDb. Capped collections

      Development

      Enhancing Development Quality Through Effective Code Reviews

      B2B Leads

      Effective Strategies to Boost B2B Lead Conversion Rates

      Most Popular

      Best Background Check Services Assessments

      Consultation

      The Role of Microservices in Modern Software Development

      Programming

      Interview with Roman

      Interview
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.