ELIXIR · 3 MIN READ · Mar 26, 2020

Elixir Pubsub In Less Than 50 Lines

Alex de Sousa

Alex de Sousa

BEAM engineer since 2012, Elixir alchemist since 2015, and open source author. Writing about Elixir, OTP, and software engineering.

:pg2 is a mostly unknown, but powerful Erlang module. It provides an API for creating process groups.

Process Group

So, what’s a process group? Well… it’s a group of Erlang/Elixir processes.

Perhaps, the correct question would be, why do we care about process groups? Well, process groups are the foundation for publisher-subscribers (pubsubs for short).

PG2

Understanding :pg2 API and how it relates to a pubsub API will make it easier to understand:

And that’s it! That’s the API. And you know what’s the best thing about it? It can work between connected nodes. Keep reading and you’ll see :)

Message in cereal

Implementing a PubSub

A PubSub has three main functions:

For a full implementation of PubSub you can check this gist.

I usually create a .iex.exs file in my $HOME folder and then run iex. You could do the same with the previous gist by doing the following:

~ $ PUBSUB="https://gist.githubusercontent.com/alexdesousa/4d592fe206cca17393affaefa4c8fd33/raw/4d84894f016bd9eef84bba647c77c62b9c9a6094/pub_sub.ex"
~ $ curl "$PUBSUB" -o .iex.exs
~ $ iex

It's that easy

Distributed PubSub

For our distributed experiment we’ll need two nodes. My machine is called matrix and both nodes will be neo and trinity respectively:

Now :neo@matrix can subscribe to :mainframe channel:

iex(neo@matrix)1> PubSub.subscribe(:mainframe)
:ok

And :trinity@matrix can send a message:

iex(trinity@matrix)2> PubSub.publish(:mainframe, "Wake up, Neo...")
:ok 

Note: Sometimes it takes a bit of time for nodes to synchronize their process groups, so you might need to publish/2 your message twice.

Finally, :neo@matrix should receive the message:

iex(neo@matrix)2> flush()
"Wake up, Neo..."
:ok

And that’s it. A powerful pubsub in a few lines of code thanks to :pg2.

Follow the white rabbit

Conclusion

Erlang has several built-in hidden gems like :pg2 that make our lives easier.

gem

Happy coding!

ABOUT THE AUTHOR
Alex de Sousa

Alex de Sousa

BEAM engineer since 2012, Elixir alchemist since 2015, and open source author. Writing about Elixir, OTP, and software engineering.

MORE POSTS