Search code examples
scalaakkashardingakka-cluster

Akka Cluster Sharding - Entity to Actor communication


I have a problem with rewriting my app to Akka Cluster Sharding. I have a Sharded Entity let's call it A, and a bunch of local actors on each nodes, let's call one of them B. Now I send a message B -> A containing (String, ActorRef[B]) and I want to respond A -> B by using the ref provided in the previous message.

On one hand, documentation suggest it should work https://doc.akka.io/docs/akka/current/typed/cluster-sharding.html#basic-example

But as far as I understand, it should not be possible for A to locate actor B in the cluster because it's not the entityID.

How does it work? Do I have to make B an Entity as well?


Solution

  • An ActorRef is location transparent: it includes the information needed to route the message to an actor in a different ActorSystem (which typically maps 1:1 to a cluster node). If you have an ActorRef for actor B, you can send it a message regardless of where in the cluster you are.

    So then why have cluster sharding, when you can always send messages across the cluster?

    Cluster sharding allows entities to be addressable independently of any actor's lifecycle: an incarnation of an entity runs as an actor and sharding manages spawning an actor to serve as an incarnation on demand, limits an entity to at most one incarnation at a given time, and reserves the right to move an entity to an incarnation on a different node (typically in response to cluster membership changes). If you don't need those aspects for a particular type of actor, there's no need to make it a sharded entity.