Kotlin + Akka Part 5: Pub / Sub

Blockchain.com Engineering
Blockchain.com Engineering
2 min readJun 4, 2018

The Akka Event Stream provides a pub/sub style API for actors. Actors subscribe to ‘channels’ on the Event Stream; the event is placed in the Actor’s mailbox if the subscription type matches the message.

The subscription channels are simple message types; any message published to the event bus which is the type, or the subtype, of the channel is forwarded to the actor ref.

Below is a simple example of how to use the event stream:

loggerRef1 will receive both messages since the Actor ref is subscribed to the parent type Event. loggerRef2 & loggerRef3 will receive Event1 and Event2 respectively. This ‘type’ subscription mechanism becomes very useful if there is a granular message hierarchy and it is known upfront which message types an Actor is interested in.

An Actor can access the event stream directly by:

context.system.eventStream()

Note: A distributed event stream is not supported natively by Akka. In other words, If you need to have your event stream replicated across multiple akka systems, on different JVM’s, you will need to build this yourself.

Another mechanism for publishing and consuming messages is using a BroadcastGroup. A broadcast group is made up from a set of actor paths and any message sent to the group will be received by all Actors. For example:

There is no message channel system like the Event Stream, so all Actors in the broadcast group will receive the messages. BroadcastGroup is itself an actor, and you can add a Routee by sending it a message:

broadcastRef.tell(AddRoutee(routeePath), ActorRef.noSender())

Note that the new Routee will not receive any messages that were published previously. To remove a Routee, simply use:

broadcastRef.tell(RemoveRoutee(routeePath), ActorRef.noSender())

There are a few other ways to manage pub/sub in Akka (such as the BroadcastRoutingLogic or event the distributed PubSubMediator), but the approach discussed previously in this post are being used in the platform which ingests thousands of messages a second, 24/7.

All the source code you find from this blog is available from here.

--

--

Blockchain.com Engineering
Blockchain.com Engineering

The Blockchain.com engineering team is building an open, accessible, and fair financial future, one piece of software at a time. Learn more at blockchain.com