Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
If Node.js is single threaded then how to handles concurrency ?
Next article icon

How to handle concurrency in Node.js ?

Last Updated : 28 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Node.js is an open-source, cross-platform runtime environment built on Chrome's V8 Engine. It is used to develop highly scalable backend as well as server-side applications.

Node.js uses a single-threaded event loop architecture. It is also asynchronous in nature. These are the two main reasons why node.js can handle multiple concurrent requests easily and why it becomes an obvious choice for the development of such applications.

Working of Node.js

Working of Node.JS

Node.js works asynchronously. In other words, it does not block incoming requests from clients when the operating system has one I/O intensive request. Instead, it passes this I/O request to the internal C++ threads and takes up the next job from the event queue.

Note: The internal C++ threads may or may not be one, but that is not of concern here.

The event queue is nothing but a queue that stores the incoming requests in the order that it received them. It then passes on these requests to the Event Loop when it is available. For every I/O request, the event loop receives, passes it on to the internal C++ threads for processing and makes itself available for the other requests, and starts processing those. Then it uses the concept of callback functions from JavaScript to receive the responses of the tasks that were sent to the internal C++ threads earlier for processing and delivers them to the client.

Let's understand this with an example:

Example 1: Traditional Web Architecture

JavaScript
function func() {     console.log("Hey I am Line number 1");     setTimeout(function () {         console.log("Hey I am Line number 2");     }, 2000);     console.log("Hey I am Line number 3"); } console.log("Hey I am Line number 4");  func(); 

Here, we have 4 console.log() statements in the order of 1 to 4. Assuming this as a traditional architecture-based application, the output would look something like this.

Output:

Hey I am Line number 4 Hey I am Line number 1 Hey I am Line number 3 Hey I am Line number 2

Explanation: Here, the "Hey I am Line number 4" will get executed first as it is above the function call. After that, the function will be called. Then "Hey I am Line number 1" will be printed and the application will add callback passed to setTimeout into browser macrotask queue, print "Hey I am Line number 3" respectively and then when time specified as 2-nd argument of setTimeout exceedes, JS event loop will get callback function from queue and execute it, thus printing "Hey I am Line number 2".

Example 2: Node.js Application

JavaScript
function func() {     console.log("Hey I am Line number 1");     setTimeout(function () {         console.log("Hey I am Line number 2");     }, 2000);     console.log("Hey I am Line number 3"); } console.log("Hey I am Line number 4"); func(); 

Here, we have 4 console.log() statements in the order 1 to 4. Assuming this as a single-threaded non-blocking application, the output would look something like this.

Output:

Hey I am Line number 4 Hey I am Line number 1 Hey I am Line number 3 Hey I am Line number 2

Explanation: Here, the "Hey I am Line number 4" will get executed first as it is above the function call. After that, the function will be called. Then "Hey I am Line number 1" will be printed and the application will go into a timeout due to the function call, for 2 seconds (2000 ms).  Now, when the application is waiting for 2 seconds, it will not block further requests, it will instead process the next request and thus print "Hey I am Line number 3". Once the timeout is finished, the lines will now be executed and "Hey I am Line number 2" will be printed to the console.

In this way, the event loop never stays occupied or blocked by a particular request. This is what gives Node.js a competitive advantage over traditional web servers in terms of handling multiple user requests at the same time, i.e. concurrency.


Next Article
If Node.js is single threaded then how to handles concurrency ?
author
jaygala260
Improve
Article Tags :
  • Web Technologies
  • Node.js

Similar Reads

  • How to Handle Errors in Node.js ?
    Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
    4 min read
  • How to Copy a File in Node.js?
    Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
    2 min read
  • If Node.js is single threaded then how to handles concurrency ?
    Node js is an open-source virtual machine that uses javascript as its scripting language. Despite being single-threaded, it is one of the most popular web technologies. The reason why node js is popular despite being single-threaded is the asynchronous nature that makes it possible to handle concurr
    4 min read
  • How to Handle Errors for Async Code in Node.js ?
    Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
    4 min read
  • How to handle Child Threads in Node.js ?
    Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.Child Pro
    2 min read
  • How to Handle CPU Intensive Loads In Node JS ?
    Node is a Single-Threaded Non-blocking event-driven architecture. But when it comes to handling heavy CPU-intensive workloads it can face some challenges while handling it. In this article, we will explore strategies to tackle CPU-intensive loads in Node.js effectively, to handle demanding tasks lik
    5 min read
  • How to Access Cache Data in Node.js ?
    Caching is an essential technique in software development that helps improve application performance and scalability by temporarily storing frequently accessed data. In Node.js, caching can significantly reduce database load, minimize API response times, and optimize resource utilization. This artic
    5 min read
  • How to Avoid Callback Hell in Node.js ?
    Callback hell, often referred to as "Pyramid of Doom," occurs in Node.js when multiple nested callbacks lead to code that is hard to read, maintain, and debug. This situation arises when each asynchronous operation depends on the completion of the previous one, resulting in deeply nested callback fu
    3 min read
  • How to handle asynchronous operations in Node ?
    NodeJS, renowned for its asynchronous and event-driven architecture, offers powerful mechanisms for handling asynchronous operations efficiently. Understanding how to manage asynchronous operations is crucial for NodeJS developers to build responsive and scalable applications. What are Asynchronous
    2 min read
  • How To Handle Global Connection of MongoDB in NodeJs?
    Handling a global connection to MongoDB in a Node.js application is important for efficient resource management and performance optimization. By maintaining a single connection to the MongoDB database, you avoid the overhead of repeatedly establishing and closing connections, which can be resource-i
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences