Concurrency in Node.js

Distinguish concurrency, parallelism, asynchronous I/O, and CPU-bound execution.

Lesson content

๐ŸŽฏ Goal By the end of this lesson, you'll understand: What is Concurrency? How Node.js handles concurrency Concurrency vs Parallelism Why Node.js is fast Real-world examples Interview questions What is Concurrency? Concurrency means handling multiple tasks at the same time without waiting for each task to finish before starting another. Simple Definition: Node.js can manage many tasks simultaneously , even though JavaScript runs on a single thread. Real-Life Example ๐Ÿฝ๏ธ Imagine a waiter in a restaurant. Customer 1 โ†’ Order Food Customer 2 โ†’ Order Drink Customer 3 โ†’ Ask for Bill The waiter doesn't wait for one meal to cook before taking another order. Instead, the waiter handles multiple customers efficiently. Node.js works the same way. How Node.js Handles Concurrency Node.js uses: โœ… Single JavaScript Thread โœ… Event Loop โœ… libuv โœ… OS Background Threads JavaScript (Main Thread) โ”‚ โ–ผ Event Loop โ”‚ โ–ผ libuv โ”‚ โ–ผ Background Tasks (File, API, Database) When a task takes time (file read, API call, database query), Node.js sends it to libuv , continues executing other code, and processes the result later. Example console . log( "Start" ); setTimeout (() => { console . log( "Task 1" ); }, 2000 ); setTimeout (() => { console . log( "Task 2" ); }, 1000 ); console . log( "End" ); Output Start End Task 2 Task 1 Both timers run concurrently. Real-Life Example ๐Ÿšš Imagine ordering three products. Order Laptop Order Phone Order Headphones All orders are processed at the same time. Whichever is ready first is delivered first. Concurrency vs Parallelism Concurrency One worker handles multiple tasks by switching between them. Task A โ”‚ Task B โ”‚ Task C Only one task is actively executing JavaScript at a time. Parallelism Multiple workers perform different tasks simultaneously. CPU 1 โ†’ Task A CPU 2 โ†’ Task B CPU 3 โ†’ Task C Requires multiple CPU cores or threads. Comparison Table Feature Concurrency Parallelism Multiple Tasks โœ… Yes โœ… Yes Multiple CPU Cores Required โŒ No โœ… Yes JavaScript Thread Single Multiple Node.js Uses โœ… Yes Worker Threads/Cluster Example with Promise.all() const p1 = Promise . resolve( "User" ); const p2 = Promise . resolve( "Orders" ); const p3 = Promise . resolve( "Payments" ); Promise . all([ p1 , p2 , p3 ]) . then( console . log); Output ["User", "Orders", "Payments"] The promises are started together and awaited together. File Reading Example const fs = require ( "fs" ); fs . readFile( "a.txt" , () => { console . log( "File A" ); }); fs . readFile( "b.txt" , () => { console . log( "File B" ); }); console . log( "Done" ); Output Done File A File B Both file reads are handled concurrently while JavaScript continues executing. Why is Node.js Fast? Node.js is fast because it: Doesn't block while waiting for I/O. Uses the Event Loop to manage asynchronous tasks. Uses libuv and the operating system for background I/O. Can handle thousands of network connections efficiently. Where is Concurrency Used? โœ… Web Servers โœ… API Calls โœ… File Uploads โœ… Database Queries โœ… Chat Applications โœ… Streaming Services Interview Question What is the output? console . log( "A" ); setTimeout (() => { console . log( "B" ); }, 0 ); console . log( "C" ); Output A C B Reason: Even with a 0 ms delay, the callback runs only after the current synchronous code finishes. Best Practices โœ… Use asynchronous APIs for file, network, and database operations. โœ… Use Promise.all() for independent asynchronous tasks that can run together. โœ… Avoid blocking the Event Loop with long-running synchronous code. โŒ Don't confuse concurrency with parallelism. Key Points โœ… Concurrency means managing multiple tasks efficiently. โœ… Node.js uses a single JavaScript thread with the Event Loop. โœ… libuv handles asynchronous I/O in the background. โœ… Concurrency is different from parallelism. โœ… Node.js is ideal for I/O-heavy applications because of its non-blocking design. ๐Ÿง  Easy Formula Need multiple tasks? โ”‚ โ–ผ Concurrency Node.js โ”‚ โ–ผ Event Loop โ”‚ โ–ผ libuv โ”‚ โ–ผ Background I/O Concurrency โ†’ Many Tasks Managed Together Parallelism โ†’ Many Tasks Executed Together Remember: โšก Concurrency = Manage many tasks efficiently. ๐Ÿงต Node.js uses one JavaScript thread with the Event Loop. ๐Ÿš€ Parallelism uses multiple threads or CPU cores, while concurrency in Node.js focuses on non-blocking I/O.