A Beginner’s Guide to Node.js Event Loop

June 27, 2024 (2mo ago)

Article cover

Have you ever wondered what happens when you, as a user, request a server? Is it a machine dealing with multiple requests, or is it a machine choosing which requests it wants to handle? Don’t worry! I’ve got you covered. This concise article will explain how Node.js behaves when it receives requests from users and the responses it generates 🚀

Imagine you have a server for your Ecommerce application running on Node.js, and there’s a confused user making multiple requests.

Interaction between user and server

What happens when a Node.js server receives a request?

Assume the parent wrapper as Node.js containing two elements: an event queue and an event loop. When a user requests a server, their request is pushed into the event queue. The event loop captures each queued request based on a FIFO (first in, first out) principle.

Architecture assumption

Now, once the event loop captures the request, it can be categorized into two types: a blocking request and a non-blocking request. A blocking request is synchronous, while a non-blocking request is asynchronous.

Captured request

If it’s an asynchronous operation, the event loop captures and processes it, then returns the desired requested resource to the user.

Non-blocking operations

If it’s a synchronous operation, the event loop captures it and sends it to a thread pool. A thread pool typically consists of 4 workers by default, each responsible for executing its assigned request. Once a worker handles the request, it returns the result and becomes available again in the thread pool. However, if all workers are busy and a new request arrives, it must wait for an available worker. This situation can potentially lead to scalability issues and longer server response times when multiple users make simultaneous requests.

Blocking operations

Connect with me 🍕

If you have any questions, feel free to reach to me on LinkedIn 🚀