PubSub:
PubSub (Publish-Subscribe) is a messaging pattern that is used for asyncronous communication. It is part of event-driven architecture and is often used to decouple services that send messages from services that receive messages. In a PubSub system, senders (publishers) generate messages, and receivers (subscribers) express interest in certain types of messages. A broker in the middle is responsible for dispatching the messages from the publishers to the appropriate subscribers. PubSub has two main types of systems: topic-based and content-based. In a topic-based system, messages are published to "topics". Subscribers express interest in one or more topics and only receive messages that are of interest. In a content-based system, messages are only delivered to a subscriber if the attributes of those messages match constraints defined by the subscriber. In this article we will look at the topic-based approach.Topic-based system: 1. Publisher: The publisher creates a message (a message could be of any data structure), tags it with a topic name, and sends it to the broker. 2. Broker: The broker receives messages from publishers and distributes them to subscribers. To do this, it maintains a list of subscribers along with the topics they're interested in. When the broker receives a message, it looks at the topic name and sends the message to all subscribers who have expressed interest in that topic. 3. The subscriber tells the broker which topics it's interested in. Whenever the broker receives a message with a matching topic, it sends the message to the subscriber. The subscriber will then process the message in whatever way it chooses. Consider a real-time stock market: 1. The publishers are the financial markets, which are constantly generating new data for different stocks. 2. The topics are the individual stocks. 3. The subscribers are traders or financial applications that are interested in specific stocks. 4. The broker is the stock market update system that delivers the updates to the right subscribers. The financial markets (publisher) generate updates and send them to the stock market update system (broker). The broker keeps track of who (subscribers) is interested in updates about which stocks (topics). When an update about a particular stock arrives, the broker sends it to all the people who have expressed interest in that stock (subscribed to that topic). PubSub systems offer the benefits of decoupling, as publishers and subscribers are not required to have knowledge of each other's existence. This makes it easy to add, remove, or modify components without affecting others. This flexibility and ease of adaptability make PubSub systems a great choice for efficient and scalable communication architectures.