In large software applications, different components often need to communicate with each other.
For example, in an e-commerce app, when a user places an order, the inventory system, payment gateway, and notification service all need to know about it.
If these components are highly coupled, making changes to one can affect others, leading to a brittle system that's hard to manage and update.
The traditional path
Usually, pieces of a system would directly communicate with each other, creating a complex web of interactions.
It's like having a group project where everyone talks to everyone else for updates. It gets confusing and chaotic very quickly.
Pub/Sub to the rescue
The Publish/Subscribe (Pub/Sub) pattern introduces a better way of handling this communication.
It's a messaging pattern used in software architecture. It's like a bulletin board in a community center.
People who have messages to share (publishers) put up their notices on the board. Those interested in certain types of notices (subscribers) regularly check the board for updates in their areas of interest.
How it works
Publishers: They send messages without knowing who will receive them.
Subscribers: They listen for messages they're interested in, without knowing who sent them.
Message Broker/Event Bus/Queue: Acts as the bulletin board, managing the messages between publishers and subscribers.
Let's take a look at an e-commerce example where an order has been placed.
When an order has been placed, the Order Service publishes an event to the broker.
The broker is simply a place where all events are stored.
The subscribers are listening for any new order events.
If new order events exist, the subscribers receive them.
In the above example, all events are order events.
But in a real-world system, different kinds of events can be published to the broker.
You can imagine we have different publishers with subscribers listening to their type of events.
Decoupling: Publishers and subscribers don't need to know about each other, making the system more flexible and easier to maintain.
Scalability: Easy to add new publishers or subscribers without disrupting the existing setup.
Focused Communication: Subscribers only receive the information they care about.
Complexity in Managing: As the number of messages and subscribers grows, managing them can become complex.
Potential Delay: There might be a delay in delivering messages, depending on the system's setup.
The Pub/Sub pattern is a good way to scale and decouple a system that has many pieces that need to communicate with each other.