DEV Community

Edward Chen
Edward Chen

Posted on

Weekly Quick Tips: Pub/Sub vs Observer Pattern?

In my attempts to blog more, I am going to do weekly tips on stuff that I think would be helpful or interesting to know for beginners. I will probably link to other articles but the intention of Weekly Quick Tips is for something someone can read in <5 min and walk away with a general sense of "wow that was interesting" or "nod good to know".

So to start it off, let's talk about Pub/Sub vs Observer Pattern. They're similar but just slightly different!

Starting off with the easier one, Observer Pattern. It's simple, there is a Subject that is being watched by many Observers. The Observers are subscribed to a Subject and eagerly wait for new information. There is a direct relationship between the Subject <-> Observer.

Pub/Sub has a middle layer called message broker/event bus that allows for decoupling between the Publisher and Subscriber. So both the Publisher and Subscriber only talk to the message broker and the two are completely oblivious to each other's existence.

You may ask, well what the heck - why would I want that? First off, the decoupling lets you minimize the risk of merge conflicts as people can work separately and since the two are independent of each other, if one happens to go down or encounters an issue it will not cause the other to immediately fail. Scaling can be easily done as well.

Disadvantages? Well that independence is a double edged sword my friend. It also is harder to track logging when something goes wrong and you have to be very sure that the Publisher is sending the message, a way for the subscriber to notify the broker that it received the message and handling the communication between the two. With a traditional client <-> server like in an Observer pattern, an error can just bubble up directly and it is easier to follow.

Thanks for tuning in, please feel free to comment if you have thoughts. At the end of the day, this is about learning so let's work together to help each other learn :D

Sources:
-https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
-https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c

Top comments (0)