Telerik blogs
How ToT2 Dark_1200x303

Publish/Subscribe (PubSub) is an asynchronous communication system that allows real-time data streaming, making PubSub essential to many applications.

Every developer knows how important performance is in modern applications. Performance plays an important role in the success of any company. We can tell how a company cares about its users by looking at its applications. Users don’t want to feel any delay or latency. They usually expect things to happen fast and without any errors.

Creating modern applications, along with all the other features nowadays, is a tough challenge. The people who are using modern applications daily don’t notice how much time and work goes in under the hood. Imagine having to create a modern real-time application, like Zoom. People use it daily and the application has become one of the most important tools for communication throughout the last couple years.

We have many examples of real-time applications that most people use daily. Video-chat apps, messaging apps, online games, etc. The examples are many and the importance of real-time applications is huge.

There’s one messaging system very important for building real-time applications. We’re going to cover and learn more about how this messaging system works. We will look at some libraries that use this messaging system and see examples of how we can create real-time applications using it.

PubSub

PubSub is a shorthand for publish/subscribe. It is an asynchronous communication system where applications can exchange messages in real time. It provides a way of communication between publishers and receivers on topics they subscribe to.

Three publisher nodes push messages to a central hub Topic. Then three subscriber nodes receive messages from Topic.

A publisher pushes a message to the channel. Subscribers receive the message as it becomes available. Subscribers can sign up to channels they are interested in.

The publisher does not send a message to all subscribers. Publishers do not know who the subscribers are and which topics they are interested in. The decoupling of publishers and subscribers provides better scalability and improvement of dynamic network topology compared to other communication systems.

The publish/subscribe system allows for a secure and modern way of communication between applications. It can be used in serverless architectures and microservices.

There are four concepts very important in the PubSub system that you need to know:

  • Publishers – A publisher can be an application or service that sends a message to a specific channel.
  • Subscribers – A subscriber can be any application or service that wants to receive messages from a specific channel.
  • Channels – A channel maintains a list of subscribers. It sends to all subscribers of that channel any message sent from the publishers.
  • Messages – A message is some sort of data sent by the publishers to any subscribers of a specific channel.

Imagine a classroom. We have many students inside a classroom who are interested in a specific topic. We have a teacher in there to handle the content and teach the students. The publish/subscribe system works like this.

We have our discipline (channel). Each student (subscriber) can subscribe to a discipline (channel) they are interested in. The teacher (publisher) handles the content (sends messages) to their students. A student can ask questions to the teacher (message).

One of the biggest advantages of using the publish/subscribe system is loose decoupling. Publishers don’t know about the subscribers, which means that the applications can operate independently.

A single traditional data center has many problems, and one of the most important for not using them is scalability. PubSub provides a way for scaling the system to a huge volume. Increasing the number of messages and publishers throughout your message system might slow it down a little bit though. Sometimes to overshadow these problems, applications put in place features such as time-limit-period for publishers.

Redis

Many developers might think that Redis is a publish/subscribe system library. This is one of the most confusing parts of the PubSub system.

Redis is an in-memory data structure, most of the time used as a caching system. It is a non-relational kind of database that can be used as a message broker.

Besides being all that, Redis can be a good alternative for implementing a publish/subscribe system. It provides a PubSub system that can be used for building real-time applications.

For JavaScript applications, one of the best wrappers for using Redis and a PubSub system is a library called node-redis-pubsub. The usage is very simple and you can share data with other applications easily.

nrp.on('say hello', (data) => {
  console.log('Hello ' + data.name);
});


nrp.emit('say hello', { name: 'Louis' });


nrp.on('city:*', (data, channel) => {
  console.log(data.city + ' is great');
});


nrp.emit('city:hello' , { city: 'Paris' });
nrp.emit('city:yeah'  , { city: 'San Francisco' });

PubSub in JavaScript

We have many different libraries for implementing the PubSub system in JavaScript applications.

One of the best ones for it is the PubSubJS library. It a publish/subscribe library that can be used in a single process, has synchronization decoupling for publishing asynchronously and is dependency-free.

The first thing you need to do is install the PubSubJS library:

yarn add pubsub-js

Then import the module:

import PubSub from 'pubsub-js'

You now need to create your subscriber function. This function handles subscribing to channels:

const mySubscriber = (message, data) => {
  console.log(`Here is the message ${message}`);
};

After that, we need to create a token. We are going to use the subscribe function to subscribe to our channel and use that token in case we want to unsubscribe to that topic later:

const mySubscriber = (message, data) => {
  console.log(`Here is the message ${message}`);
};

const token = PubSub.subscribe('topic', mySubscriber);

We can now publish our topic asynchronously:

const mySubscriber = (message, data) => {
  console.log(`Here is the message ${message}`);
};

const token = PubSub.subscribe('topic', mySubscriber);

PubSub.publish('topic', 'first pubsub system using JavaScript');

Conclusion

Modern applications are decoupled into small pieces of code. They are very easy to compose and work along with other applications. Using a good communication system between your applications will get your application to the next level.

Real-time applications are applications that the user senses immediately without delay. Real-time data in modern applications can become a problem when done in the wrong way. There are other alternatives, but the PubSub system at the end of the day is the best choice for many applications.

It provides a powerful, secure and easy way of streaming real-time data between applications. Using the PubSub system will make things easier. It provides a performant and reliable way of consuming real-time data.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a full-stack developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Related Posts

Comments

Comments are disabled in preview mode.