...

/

Publish/Subscribe Pattern

Publish/Subscribe Pattern

Learn how to implement the Publish/Subscribe pattern in Node.js applications.

Publish/Subscribe (often abbreviated to Pub/Sub) pattern is probably the best-known one-way messaging pattern. We should already be familiar with it because it’s nothing more than a distributed Observer pattern. Similar to the Observer pattern, we have a set of subscribers registering their interest in receiving a specific category of messages. On the other side, the publisher produces messages that are distributed across all the relevant subscribers. The illustration below shows the two main variants of the Pub/Sub pattern; the first is based on a peer-to-peer architecture, and the second uses a broker to mediate the communication.

Press + to interact
Publish/Subscribe messaging pattern
Publish/Subscribe messaging pattern

What makes Pub/Sub so special is the fact that the publisher doesn’t know in advance who the recipients of the messages are. As we said, it’s the subscriber that has to register its interest to receive a particular message, allowing the publisher to work with an unspecified number of receivers. In other words, the two sides of the Pub/Sub pattern are loosely coupled, which makes this an ideal pattern to integrate the nodes of an evolving distributed system.

The presence of a broker further improves the decoupling between the nodes of the system because the subscribers interact ...