Distributed Publish Subscribe in Cluster
How do I send a message to an actor without knowing which node it is running on?
How do I send messages to all actors in the cluster that have registered interest in a named topic?
This pattern provides a mediator actor, akka.cluster.pubsub.DistributedPubSubMediator, that manages a registry of actor references and replicates the entries to peer actors among all cluster nodes or a group of nodes tagged with a specific role.
The DistributedPubSubMediator
actor is supposed to be started on all nodes, or all nodes with specified role, in the cluster. The mediator can be started with the DistributedPubSub
extension or as an ordinary actor.
The registry is eventually consistent, i.e. changes are not immediately visible at other nodes, but typically they will be fully replicated to all other nodes after a few seconds. Changes are only performed in the own part of the registry and those changes are versioned. Deltas are disseminated in a scalable way to other nodes with a gossip protocol.
You can send messages via the mediator on any node to registered actors on any other node.
There a two different modes of message delivery, explained in the sections Publish
and Send
below.
Publish
This is the true pub/sub mode. A typical usage of this mode is a chat room in an instant messaging application.
Actors are registered to a named topic. This enables many subscribers on each node. The message will be delivered to all subscribers of the topic.
For efficiency the message is sent over the wire only once per node (that has a matching topic), and then delivered to all subscribers of the local topic representation.
You register actors to the local mediator with DistributedPubSubMediator.Subscribe
. Successful Subscribe and Unsubscribe is acknowledged with DistributedPubSubMediator.SubscribeAck
and DistributedPubSubMediator.UnsubscribeAck
replies. The acknowledgment means that the subscription is registered, but it can still take some time until it is replicated to other nodes.
You publish messages by sending DistributedPubSubMediator.Publish
message to the local mediator.
Topic actors are automatically removed from the registry when they are terminated. Termination occurs when there are no subscribers for the duration configured by akka.cluster.pub-sub.removed-time-to-live
, which defaults to 2 minutes. You can change the deadline by setting removed-time-to-live
to a custom duration.
You can Unsubscribe
from a topic with DistributedPubSubMediator.Unsubscribe
.
An example of a subscriber actor:
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
namespace SampleSubscriber
{
public sealed class Subscriber: ReceiveActor
{
private readonly IActorRef _mediator;
private readonly ILoggingAdapter _log;
public Subscriber()
{
_log = Context.GetLogger();
_mediator = DistributedPubSub.Get(Context.System).Mediator;
_mediator.Tell(new Subscribe("content", Self));
Receive<SubscribeAck>(ack =>
{
if (ack != null && ack.Subscribe.Topic == "content" && ack.Subscribe.Ref.Equals(Self))
{
Become(Ready);
}
});
}
private void Ready()
{
Receive<string>(message => _log.Info("Got {0}", message));
}
}
}
Subscriber actors can be started on several nodes in the cluster, and all will receive messages published to the "content" topic.
// See https://aka.ms/new-console-template for more information
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using SampleSubscriber;
var config = ConfigurationFactory.ParseString(@"
akka {
actor.provider = cluster
extensions = [""Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools""]
remote {
dot-netty.tcp {
port = 0
hostname = localhost
}
}
cluster {
seed-nodes = [""akka.tcp://cluster@localhost:5800""]
}
}");
var actorSystem = ActorSystem.Create("cluster", config);
DistributedPubSub.Get(actorSystem);
actorSystem.ActorOf(Props.Create(() => new Subscriber()), "subscriber");
actorSystem.WhenTerminated.Wait();
A simple actor that publishes to this "content" topic:
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
namespace SamplePublisher
{
public sealed class Publisher: ReceiveActor
{
public Publisher()
{
var mediator = DistributedPubSub.Get(Context.System).Mediator;
Receive<string>(input => mediator.Tell(new Publish("content", input.ToUpperInvariant())));
}
}
}
It can publish messages to the topic from anywhere in the cluster:
// See https://aka.ms/new-console-template for more information
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using SamplePublisher;
var config = ConfigurationFactory.ParseString(@"
akka {
actor.provider = cluster
extensions = [""Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools""]
remote {
dot-netty.tcp {
port = 5800
hostname = localhost
}
}
cluster {
seed-nodes = [""akka.tcp://cluster@localhost:5800""]
}
}");
var actorSystem = ActorSystem.Create("cluster", config);
DistributedPubSub.Get(actorSystem);
var publisher = actorSystem.ActorOf(Props.Create<Publisher>(), "publisher");
publisher.Tell("Hello from Akka-Verse");
actorSystem.WhenTerminated.Wait();
Topic Groups
Actors may also be subscribed to a named topic with a group id. If subscribing with a group id, each message published to a topic with the SendOneMessageToEachGroup
flag set to true is delivered via the supplied RoutingLogic
(default random) to one actor within each subscribing group.
If all the subscribed actors have the same group id, then this works just like Send
and each message is only delivered to one subscriber.
If all the subscribed actors have different group names, then this works like normal Publish
and each message is broadcasted to all subscribers.
Note
Note that if the group id is used it is part of the topic identifier. Messages published with SendOneMessageToEachGroup=false
will not be delivered to subscribers that subscribed with a group id. Messages published with SendOneMessageToEachGroup=true
will not be delivered to subscribers that subscribed without a group id.
Send
This is a point-to-point mode where each message is delivered to one destination, but you still do not have to know where the destination is located. A typical usage of this mode is private chat to one other user in an instant messaging application. It can also be used for distributing tasks to registered workers, like a cluster aware router where the routees dynamically can register themselves.
The message will be delivered to one recipient with a matching path, if any such exists in the registry. If several entries match the path because it has been registered on several nodes the message will be sent via the supplied RoutingLogic
(default random) to one destination. The sender() of the message can specify that local affinity is preferred, i.e. the message is sent to an actor in the same local actor system as the used mediator actor, if any such exists, otherwise route to any other matching entry.
You register actors to the local mediator with DistributedPubSubMediator.Put
. The IActorRef
in Put must belong to the same local actor system as the mediator. The path without address information is the key to which you send messages. On each node there can only be one actor for a given path, since the path is unique within one local actor system.
You send messages by sending DistributedPubSubMediator.Send
message to the local mediator with the path (without address information) of the destination actors.
Actors are automatically removed from the registry when they are terminated, or you can explicitly remove entries with DistributedPubSubMediator.Remove
.
An example of a destination actor:
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
namespace SampleDestination
{
public sealed class Destination : ReceiveActor
{
private readonly ILoggingAdapter log = Context.GetLogger();
public Destination()
{
// activate the extension
var mediator = DistributedPubSub.Get(Context.System).Mediator;
// register to the path
mediator.Tell(new Put(Self));
Receive<string>(s =>
{
log.Info($"Got {s}");
});
}
}
Destination actors can be started on several nodes in the cluster, and all will receive messages sent to the path (without address information).
// See https://aka.ms/new-console-template for more information
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using SampleDestination;
var config = ConfigurationFactory.ParseString(@"
akka {
actor.provider = cluster
extensions = [""Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools""]
remote {
dot-netty.tcp {
port = 0
hostname = localhost
}
}
cluster {
seed-nodes = [""akka.tcp://cluster@localhost:5800""]
}
}");
var actorSystem = ActorSystem.Create("cluster", config);
DistributedPubSub.Get(actorSystem);
actorSystem.ActorOf(Props.Create<Destination>(), "destination");
actorSystem.WhenTerminated.Wait();
A simple actor that sends to the path:
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
namespace SampleSender
{
public sealed class Sender: ReceiveActor
{
public Sender()
{
// activate the extension
var mediator = DistributedPubSub.Get(Context.System).Mediator;
Receive<string>(str =>
{
var upperCase = str.ToUpper();
mediator.Tell(new Send(path: "/user/destination", message: upperCase, localAffinity: true));
});
}
}
}
It can send messages to the path from anywhere in the cluster:
// See https://aka.ms/new-console-template for more information
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using SampleSender;
var config = ConfigurationFactory.ParseString(@"
akka {
actor.provider = cluster
extensions = [""Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools""]
remote {
dot-netty.tcp {
port = 0
hostname = localhost
}
}
cluster {
seed-nodes = [""akka.tcp://cluster@localhost:5800""]
}
}");
var actorSystem = ActorSystem.Create("cluster", config);
DistributedPubSub.Get(actorSystem);
var sender = actorSystem.ActorOf(Props.Create<Sender>(), "sender");
sender.Tell("Hello from Akka-Verse");
actorSystem.WhenTerminated.Wait();
It is also possible to broadcast messages to the actors that have been registered with Put
. Send DistributedPubSubMediator.SendToAll
message to the local mediator and the wrapped message will then be delivered to all recipients with a matching path. Actors with the same path, without address information, can be registered on different nodes. On each node there can only be one such actor, since the path is unique within one local actor system.
Typical usage of this mode is to broadcast messages to all replicas with the same path, e.g. 3 actors on different nodes that all perform the same actions, for redundancy. You can also optionally specify a property (AllButSelf
) deciding if the message should be sent to a matching path on the self node or not.
DeadLetters From DistributedPubSub
There are three factors that determine when or if a message is published to /system/deadletters
, namely: send-to-dead-letters-when-no-subscribers
, zero existing subscribers, or if the topic does not exist / has been terminated.
akka.cluster.pub-sub.send-to-dead-letters-when-no-subscribers
: this is aDistributedPubSub
setting that, if turned off or set tofalse
(it ison
/true
by default), will not produceDeadletter
s when there are no subscribers or the topic does not exist.Zero Existing Subscribers: A message is sent to the DeadLetter if
Send-to-dead-letters-when-no-subscribers
is on/true and there are no existing subscriber(s) to receive it.Akka.Cluster.DistributedPubSub
does not support queueing up messages while there are no existing subscribers!Terminated Topic Actor: When there are no existing subscribers and no new subscription for a duration of, say 2 minutes (the default for
removed-time-to-live
), the Topic Actor is terminated and ifSend-to-dead-letters-when-no-subscribers
is on/true, messages are sent to DeadLetter.
DistributedPubSub Extension
In the example above the mediator is started and accessed with the Akka.Cluster.Tools.PublishSubscribe.DistributedPubSub
extension. That is convenient and perfectly fine in most cases, but it can be good to know that it is possible to start the mediator actor as an ordinary actor and you can have several different mediators at the same time to be able to divide a large number of actors/topics to different mediators. For example you might want to use different cluster roles for different mediators.
The DistributedPubSub
extension can be configured with the following properties:
############################################
# Akka Cluster Tools Reference Config File #
############################################
# This is the reference config file that contains all the default settings.
# Make your edits/overrides in your application.conf.
# //#pub-sub-ext-config
# Settings for the DistributedPubSub extension
akka.cluster.pub-sub {
# Actor name of the mediator actor, /system/distributedPubSubMediator
name = distributedPubSubMediator
# Start the mediator on members tagged with this role.
# All members are used if undefined or empty.
role = ""
# The routing logic to use for 'Send'
# Possible values: random, round-robin, broadcast
routing-logic = random
# How often the DistributedPubSubMediator should send out gossip information
gossip-interval = 1s
# Removed entries are pruned after this duration
removed-time-to-live = 120s
# Maximum number of elements to transfer in one message when synchronizing the registries.
# Next chunk will be transferred in next round of gossip.
max-delta-elements = 3000
# When a message is published to a topic with no subscribers send it to the dead letters.
send-to-dead-letters-when-no-subscribers = on
# The id of the dispatcher to use for DistributedPubSubMediator actors.
# If not specified, the internal dispatcher is used.
# If specified you need to define the settings of the actual dispatcher.
use-dispatcher = ""
}
# //#pub-sub-ext-config
# Protobuf serializer for cluster DistributedPubSubMediator messages
akka.actor {
serializers {
akka-pubsub = "Akka.Cluster.Tools.PublishSubscribe.Serialization.DistributedPubSubMessageSerializer, Akka.Cluster.Tools"
}
serialization-bindings {
"Akka.Cluster.Tools.PublishSubscribe.IDistributedPubSubMessage, Akka.Cluster.Tools" = akka-pubsub
"Akka.Cluster.Tools.PublishSubscribe.Internal.SendToOneSubscriber, Akka.Cluster.Tools" = akka-pubsub
}
serialization-identifiers {
"Akka.Cluster.Tools.PublishSubscribe.Serialization.DistributedPubSubMessageSerializer, Akka.Cluster.Tools" = 9
}
}
It is recommended to load the extension when the actor system is started by defining it in akka.extensions configuration property. Otherwise it will be activated when first used and then it takes a while for it to be populated.
akka.extensions = ["Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools"]