Open In App

What is Reactor Pattern in Node.js ?

Last Updated : 22 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Reactor Pattern is used to avoid the blocking of the Input/Output operations. It provides us with a handler that is associated with I/O operations. When the I/O requests are to be generated, they get submitted to a demultiplexer, which handles concurrency in avoiding the blocking of the I/O mode and collects the requests in form of an event and queues those events.

There are two ways in which I/O operations are performed:

  1. Blocking I/O: Application will make a function call and pause its execution at a point until the data is received. It is called as ‘Synchronous’.
  2. Non-Blocking I/O: Application will make a function call, and, without waiting for the results it continues its execution. It is called as ‘Asynchronous’.

Note: Node.js is Asynchronous in nature.

Reactor Pattern comprises of:

  1. Resources: They are shared by multiple applications for I/O operations, generally slower in executions.
  2. Synchronous Event De-multiplexer/Event Notifier: This uses Event Loop for blocking on all resources. When a set of I/O operations completes, the Event De-multiplexer pushes the new events into the Event Queue.
  3. Event Loop and Event Queue: Event Queue queues up the new events that occurred along with its event-handler, pair.
  4. Request Handler/Application: This is, generally, the application that provides the handler to be executed for registered events on resources.

How Reactor Pattern works?

  1. Everything starts with the application. It makes a request and the event demultiplexer gathers those requests and then it forms queues know as Event Queues.
  2. Event demultiplexer is run by libuv which is a library that allows JavaScript code (via V8) to perform I/O, in-network, file, etc. It is an asynchronous IO library that allows Node.js to perform I/O.
  3. In the diagram above, there is only one event queue and there are 7 basics queues. Those queues have ascending priorities, the queue that has the highest priority is checked first by the event loop.
  4. The Timers queue has the highest priority. setTimeout and setInterval functions are queued here. Once the events are done in this queue, or time is up, the event loop passes those functions to call stack, named as executing handler.
  5. When one of the event queues is complete, instead of jumping to the next queue, the event loop firstly will check the other two queues which queue other micro tasks and process called nextTick functions. Then it will jump to the upcoming queue.

Callback queue is an event queue and call stack is execute handler.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads