trait ClusterSharding extends Extension
This extension provides sharding functionality of actors in a cluster. The typical use case is when you have many stateful actors that together consume more resources (e.g. memory) than fit on one machine. You need to distribute them across several nodes in the cluster and you want to be able to interact with them using their logical identifier, but without having to care about their physical location in the cluster, which might also change over time. It could for example be actors representing Aggregate Roots in Domain-Driven Design terminology. Here we call these actors "entities". These actors typically have persistent (durable) state, but this feature is not limited to actors with persistent state.
In this context sharding means that actors with an identifier, so called entities,
can be automatically distributed across multiple nodes in the cluster. Each entity
actor runs only at one place, and messages can be sent to the entity without requiring
the sender to know the location of the destination actor. This is achieved by sending
the messages via a ShardRegion
actor provided by this extension, which knows how
to route the message with the entity id to the final destination.
This extension is supposed to be used by first, typically at system startup on each node
in the cluster, registering the supported entity types with the ClusterSharding#init
method, which returns the ShardRegion
actor reference for a named entity type.
Messages to the entities are always sent via that ActorRef
, i.e. the local ShardRegion
.
Messages can also be sent via the EntityRef retrieved with ClusterSharding#entityRefFor,
which will also send via the local ShardRegion
.
Some settings can be configured as described in the akka.cluster.sharding
section of the reference.conf
.
The ShardRegion
actor is started on each node in the cluster, or group of nodes
tagged with a specific role. The ShardRegion
is created with a ShardingMessageExtractor
to extract the entity identifier and the shard identifier from incoming messages.
A shard is a group of entities that will be managed together. For the first message in a
specific shard the ShardRegion
requests the location of the shard from a central coordinator,
the akka.cluster.sharding.ShardCoordinator. The ShardCoordinator
decides which ShardRegion
owns the shard. The ShardRegion
receives the decided home of the shard
and if that is the ShardRegion
instance itself it will create a local child
actor representing the entity and direct all messages for that entity to it.
If the shard home is another ShardRegion
instance messages will be forwarded
to that ShardRegion
instance instead. While resolving the location of a
shard incoming messages for that shard are buffered and later delivered when the
shard location is known. Subsequent messages to the resolved shard can be delivered
to the target destination immediately without involving the ShardCoordinator
.
To make sure that at most one instance of a specific entity actor is running somewhere
in the cluster it is important that all nodes have the same view of where the shards
are located. Therefore the shard allocation decisions are taken by the central
ShardCoordinator
, which is running as a cluster singleton, i.e. one instance on
the oldest member among all cluster nodes or a group of nodes tagged with a specific
role. The oldest member can be determined by akka.cluster.Member#isOlderThan.
To be able to use newly added members in the cluster the coordinator facilitates rebalancing
of shards, i.e. migrate entities from one node to another. In the rebalance process the
coordinator first notifies all ShardRegion
actors that a handoff for a shard has started.
That means they will start buffering incoming messages for that shard, in the same way as if the
shard location is unknown. During the rebalance process the coordinator will not answer any
requests for the location of shards that are being rebalanced, i.e. local buffering will
continue until the handoff is completed. The ShardRegion
responsible for the rebalanced shard
will stop all entities in that shard by sending the handOffMessage
to them. When all entities have
been terminated the ShardRegion
owning the entities will acknowledge the handoff as completed
to the coordinator. Thereafter the coordinator will reply to requests for the location of
the shard and thereby allocate a new home for the shard and then buffered messages in the
ShardRegion
actors are delivered to the new location. This means that the state of the entities
are not transferred or migrated. If the state of the entities are of importance it should be
persistent (durable), e.g. with akka-persistence
, so that it can be recovered at the new
location.
The logic that decides which shards to rebalance is defined in a plugable shard
allocation strategy. The default implementation akka.cluster.sharding.ShardCoordinator.LeastShardAllocationStrategy
picks shards for handoff from the ShardRegion
with most number of previously allocated shards.
They will then be allocated to the ShardRegion
with least number of previously allocated shards,
i.e. new members in the cluster. There is a configurable threshold of how large the difference
must be to begin the rebalancing. This strategy can be replaced by an application specific
implementation.
The state of shard locations in the ShardCoordinator
is stored with akka-distributed-data
or
akka-persistence
to survive failures. When a crashed or unreachable coordinator
node has been removed (via down) from the cluster a new ShardCoordinator
singleton
actor will take over and the state is recovered. During such a failure period shards
with known location are still available, while messages for new (unknown) shards
are buffered until the new ShardCoordinator
becomes available.
As long as a sender uses the same ShardRegion
actor to deliver messages to an entity
actor the order of the messages is preserved. As long as the buffer limit is not reached
messages are delivered on a best effort basis, with at-most once delivery semantics,
in the same way as ordinary message sending. Reliable end-to-end messaging, with
at-least-once semantics can be added by using AtLeastOnceDelivery
in akka-persistence
.
Some additional latency is introduced for messages targeted to new or previously unused shards due to the round-trip to the coordinator. Rebalancing of shards may also add latency. This should be considered when designing the application specific shard resolution, e.g. to avoid too fine grained shards.
The ShardRegion
actor can also be started in proxy only mode, i.e. it will not
host any entities itself, but knows how to delegate messages to the right location.
If the state of the entities are persistent you may stop entities that are not used to
reduce memory consumption. This is done by the application specific implementation of
the entity actors for example by defining receive timeout (context.setReceiveTimeout
).
If a message is already enqueued to the entity when it stops itself the enqueued message
in the mailbox will be dropped. To support graceful passivation without losing such
messages the entity actor can send ClusterSharding.Passivate to the ActorRef[ShardCommand]
that was passed in to the factory method when creating the entity..
The specified stopMessage
message will be sent back to the entity, which is
then supposed to stop itself. Incoming messages will be buffered by the ShardRegion
between reception of Passivate
and termination of the entity. Such buffered messages
are thereafter delivered to a new incarnation of the entity.
This class is not intended for user extension other than for test purposes (e.g. stub implementation). More methods may be added in the future and that may break such implementations.
- Self Type
- ClusterSharding with javadsl.ClusterSharding
- Annotations
- @DoNotInherit()
- Source
- ClusterSharding.scala
- Alphabetic
- By Inheritance
- ClusterSharding
- Extension
- AnyRef
- Any
- by any2stringadd
- by StringFormat
- by Ensuring
- by ArrowAssoc
- Hide All
- Show All
- Public
- Protected
Abstract Value Members
- abstract def defaultShardAllocationStrategy(settings: ClusterShardingSettings): ShardAllocationStrategy
The default
ShardAllocationStrategy
is configured byleast-shard-allocation-strategy
properties. - abstract def entityRefFor[M](typeKey: EntityTypeKey[M], entityId: String, dataCenter: DataCenter): EntityRef[M]
Create an
ActorRef
-like reference to a specific sharded entity running in another data center.Create an
ActorRef
-like reference to a specific sharded entity running in another data center.You have to correctly specify the type of messages the target can handle via the
typeKey
.Messages sent through this EntityRef will be wrapped in a ShardingEnvelope including the here provided
entityId
.This can only be used if the default ShardingEnvelope is used, when using custom envelopes or in message entity ids you will need to use the
ActorRef[E]
returned by sharding init for messaging with the sharded actors.For in-depth documentation of its semantics, see EntityRef.
- abstract def entityRefFor[M](typeKey: EntityTypeKey[M], entityId: String): EntityRef[M]
Create an
ActorRef
-like reference to a specific sharded entity.Create an
ActorRef
-like reference to a specific sharded entity.You have to correctly specify the type of messages the target can handle via the
typeKey
.Messages sent through this EntityRef will be wrapped in a ShardingEnvelope including the here provided
entityId
.This can only be used if the default ShardingEnvelope is used, when using custom envelopes or in message entity ids you will need to use the
ActorRef[E]
returned by sharding init for messaging with the sharded actors.For in-depth documentation of its semantics, see EntityRef.
- abstract def init[M, E](entity: Entity[M, E]): ActorRef[E]
Initialize sharding for the given
entity
factory settings.Initialize sharding for the given
entity
factory settings.It will start a shard region or a proxy depending on if the settings require role and if this node has such a role.
- M
The type of message the entity accepts
- E
A possible envelope around the message the entity accepts
- abstract def shard(typeKey: EntityTypeKey[_]): ActorRef[ShardCommand]
Access to the
ActorRef
to sendShardCommand
for a given entity type.Access to the
ActorRef
to sendShardCommand
for a given entity type. For example ClusterSharding.Passivate can be sent to thisActorRef
. Note that thisActorRef
is also available in the EntityContext. The entity type must first be initialized with the ClusterSharding.init method. - abstract def shardState: ActorRef[ClusterShardingQuery]
Actor for querying Cluster Sharding state
Concrete Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def ##: Int
- Definition Classes
- AnyRef → Any
- def +(other: String): String
- Implicit
- This member is added by an implicit conversion from ClusterSharding toany2stringadd[ClusterSharding] performed by method any2stringadd in scala.Predef.
- Definition Classes
- any2stringadd
- def ->[B](y: B): (ClusterSharding, B)
- Implicit
- This member is added by an implicit conversion from ClusterSharding toArrowAssoc[ClusterSharding] performed by method ArrowAssoc in scala.Predef.
- Definition Classes
- ArrowAssoc
- Annotations
- @inline()
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @HotSpotIntrinsicCandidate() @native()
- def ensuring(cond: (ClusterSharding) => Boolean, msg: => Any): ClusterSharding
- Implicit
- This member is added by an implicit conversion from ClusterSharding toEnsuring[ClusterSharding] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: (ClusterSharding) => Boolean): ClusterSharding
- Implicit
- This member is added by an implicit conversion from ClusterSharding toEnsuring[ClusterSharding] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: Boolean, msg: => Any): ClusterSharding
- Implicit
- This member is added by an implicit conversion from ClusterSharding toEnsuring[ClusterSharding] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- def ensuring(cond: Boolean): ClusterSharding
- Implicit
- This member is added by an implicit conversion from ClusterSharding toEnsuring[ClusterSharding] performed by method Ensuring in scala.Predef.
- Definition Classes
- Ensuring
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @HotSpotIntrinsicCandidate() @native()
- def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @HotSpotIntrinsicCandidate() @native()
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @HotSpotIntrinsicCandidate() @native()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @HotSpotIntrinsicCandidate() @native()
- final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def toString(): String
- Definition Classes
- AnyRef → Any
- final def wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException]) @native()
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
Deprecated Value Members
- def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable]) @Deprecated
- Deprecated
(Since version 9)
- def formatted(fmtstr: String): String
- Implicit
- This member is added by an implicit conversion from ClusterSharding toStringFormat[ClusterSharding] performed by method StringFormat in scala.Predef.
- Definition Classes
- StringFormat
- Annotations
- @deprecated @inline()
- Deprecated
(Since version 2.12.16) Use
formatString.format(value)
instead ofvalue.formatted(formatString)
, or use thef""
string interpolator. In Java 15 and later,formatted
resolves to the new method in String which has reversed parameters.
- def →[B](y: B): (ClusterSharding, B)
- Implicit
- This member is added by an implicit conversion from ClusterSharding toArrowAssoc[ClusterSharding] performed by method ArrowAssoc in scala.Predef.
- Definition Classes
- ArrowAssoc
- Annotations
- @deprecated
- Deprecated
(Since version 2.13.0) Use
->
instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code.