How to use Pub/Sub in Golang

If you’ve ever used Golang before, the concepts of Publish/Subscribe should be fairly familiar to you. It is much like how goroutines communicate over channels between each other, the idea boils down to allowing for such a channel to have multiple ‘subscribers’ receive messages sent on the channel.

This paradigm can be powerful when used right, allowing for a cut down of complexity from both the publisher and subscriber sides and fast asynchronous communication. This is similar to Go’s goroutine usage, making the two a powerful combination.

What is Pub/Sub?

The Publish/Subscribe (Pub/Sub) pattern allows for real-time messages to be sent from one device (a ‘Publisher’) to other devices (‘Subscribers’). This is done through a message broker, which receives messages from Publishers and then sends them to the relevant Subscribers.

The premise of topics (also known as channels, but we will refer to them as topics to avoid confusion with Go’s channels) is used to identify to who each message should be sent to. This is an ID that represents a collection of communication to which a publisher can publish to, and subscribers can subscribe to. An example would be to have a topic called ‘sport,’ to which a publisher will be publishing sports updates to, and subscribers would subscribe for said sports updates.

There is no inherent need for a publisher to be only a publisher nor a subscriber to be just a subscriber. Many use cases, such as Chat Applications, require clients to publish and subscribe to messages. The main concept is that all communication is sent to the broker, identified by a topic ID, and then sent to any client who has subscribed to said topic.

Although Pub/Sub is based on earlier design patterns like message queuing, it is more flexible and scalable. The key to this is that Pub/Sub enables the movement of messages between different system components without the components being aware of each other’s identity.

When you should use Pub/Sub

Pub/Sub has a few areas in which it particularly excels over other more traditional methods such as polling:

  • A publisher doesn’t need to know who they’re publishing to, just which topic they’re publishing to. This allows for dynamic message distribution without any actions on the publisher’s end
  • Subscribers don’t need to repeatedly poll a publisher for updates or communicate directly with the publisher. Once a connection has been established with the broker and a topic subscribed to, they’re ready to receive messages