The Node.js Event Loop: Concurrency on a Single Thread
The Node.js event loop lets a single thread handle high concurrency by offloading I/O. It's ideal for web servers and APIs, but the footgun is that any long-running synchronous code will block the entire application, freezing all other requests.
WHY IT EXISTS Traditional web servers often used a thread-per-request model, which consumes significant memory and struggles under high concurrency. Node.js was designed to solve this with an event-driven, non-blocking I/O model, allowing a single process to handle thousands of concurrent connections efficiently.
THE MENTAL MODEL Imagine a restaurant with only one, very fast waiter. The waiter takes an order (initiates an I/O operation like a database query), gives it to the kitchen (the underlying OS/libuv), and immediately moves to the next table without waiting for the food to be cooked. When a dish is ready (the I/O completes), the kitchen signals the waiter, who then delivers it. The waiter is the event loop; your code is the waiter, and the kitchen is the background worker pool.
HOW IT WORKS The event loop is a process that continuously checks for tasks to execute. When your JavaScript code initiates an asynchronous operation (like reading a file with fs.readFile), Node.js hands that operation off to a worker thread in its underlying C++ library, libuv. The main JavaScript thread is not blocked and can continue executing other code. When the I/O operation finishes, its associated callback function is placed into a queue. The event loop picks up this callback from the queue and executes it on the main thread.
WHEN TO USE IT Node.js and its event loop excel in I/O-bound applications. This includes web servers, APIs, real-time applications like chat servers, and microservices that spend most of their time waiting for network or database responses. It's built for high concurrency with low resource usage.
WHEN NOT TO USE IT Avoid Node.js for CPU-intensive tasks. A long-running, synchronous computation (like complex math or data processing) will monopolize the single main thread, blocking the event loop entirely. This makes the application unresponsive to all other requests. For CPU-bound work, consider using Node.js Worker Threads or a different language better suited for multi-threaded computation.
ONE CANONICAL EXAMPLE A simple Express.js web server handling API requests. When a request comes in to fetch user data, the server makes a non-blocking call to a database. While waiting for the database response, the event loop is free to handle hundreds or thousands of other incoming requests. Once the database returns the data, the corresponding callback is executed to send the HTTP response.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.