Cluster Sharding

For the Akka Classic documentation of this feature see Classic Cluster Sharding

Module info

To use Akka Cluster Sharding, you must add the following dependency in your project:

sbt
libraryDependencies += "com.typesafe.akka" %% "akka-cluster-sharding-typed" % "2.6.0"
Maven
<dependency>
  <groupId>com.typesafe.akka</groupId>
  <artifactId>akka-cluster-sharding-typed_2.13</artifactId>
  <version>2.6.0</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.typesafe.akka', name: 'akka-cluster-sharding-typed_2.13', version: '2.6.0'
}
Project Info: Akka Cluster Sharding (typed)
Artifact
com.typesafe.akka
akka-cluster-sharding-typed
2.6.0
JDK versions
Adopt OpenJDK 8
Adopt OpenJDK 11
Scala versions2.12.10, 2.13.0
JPMS module nameakka.cluster.sharding.typed
License
Readiness level
Since 2.6.0, 2019-11-06
Home pagehttps://akka.io/
API documentation
Forums
Release notesakka.io blog
IssuesGithub issues
Sourceshttps://github.com/akka/akka

Introduction

Cluster sharding is useful when you need to distribute actors across several nodes in the cluster and 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.

Cluster sharding is typically used when you have many stateful actors that together consume more resources (e.g. memory) than fit on one machine. If you only have a few stateful actors it might be easier to run them on a Cluster Singleton node.

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.

Cluster sharding will not be active on members with status WeaklyUp if that feature is enabled.

Warning

Make sure to not use a Cluster downing strategy that may split the cluster into several separate clusters in case of network problems or system overload (long GC pauses), since that will result in multiple shards and entities being started, one in each separate cluster! See Downing.

Basic example

Sharding is accessed via the ClusterSharding extension

Scala
import akka.cluster.sharding.typed.ShardingEnvelope
import akka.cluster.sharding.typed.scaladsl.ClusterSharding
import akka.cluster.sharding.typed.scaladsl.EntityTypeKey
import akka.cluster.sharding.typed.scaladsl.EntityRef

val sharding = ClusterSharding(system)
Java
import akka.cluster.sharding.typed.ShardingEnvelope;
import akka.cluster.sharding.typed.javadsl.ClusterSharding;
import akka.cluster.sharding.typed.javadsl.EntityTypeKey;
import akka.cluster.sharding.typed.javadsl.EntityRef;
import akka.cluster.sharding.typed.javadsl.Entity;
import akka.persistence.typed.PersistenceId;

ClusterSharding sharding = ClusterSharding.get(system);

It is common for sharding to be used with persistence however any Behavior can be used with sharding e.g. a basic counter:

Scala
object Counter {
  sealed trait Command
  case object Increment extends Command
  final case class GetValue(replyTo: ActorRef[Int]) extends Command

  def apply(entityId: String): Behavior[Command] = {
    def updated(value: Int): Behavior[Command] = {
      Behaviors.receiveMessage[Command] {
        case Increment =>
          updated(value + 1)
        case GetValue(replyTo) =>
          replyTo ! value
          Behaviors.same
      }
    }

    updated(0)

  }
}
Java
public class Counter extends AbstractBehavior<Counter.Command> {

  public interface Command {}

  public enum Increment implements Command {
    INSTANCE
  }

  public static class GetValue implements Command {
    private final ActorRef<Integer> replyTo;

    public GetValue(ActorRef<Integer> replyTo) {
      this.replyTo = replyTo;
    }
  }

  public static Behavior<Command> create(String entityId) {
    return Behaviors.setup(context -> new Counter(context, entityId));
  }

  private final String entityId;
  private int value = 0;

  private Counter(ActorContext<Command> context, String entityId) {
    super(context);
    this.entityId = entityId;
  }

  @Override
  public Receive<Command> createReceive() {
    return newReceiveBuilder()
        .onMessage(Increment.class, msg -> onIncrement())
        .onMessage(GetValue.class, this::onGetValue)
        .build();
  }

  private Behavior<Command> onIncrement() {
    value++;
    return this;
  }

  private Behavior<Command> onGetValue(GetValue msg) {
    msg.replyTo.tell(value);
    return this;
  }
}

Each Entity type has a key that is then used to retrieve an EntityRef for a given entity identifier. Note in the sample’s Counter.applyCounter.create function that the entityId parameter is not called, it is included to demonstrate how one can pass it to an entity. Another way to do this is by sending the entityId as part of the message if needed.

Scala
val TypeKey = EntityTypeKey[Counter.Command]("Counter")

val shardRegion: ActorRef[ShardingEnvelope[Counter.Command]] =
  sharding.init(Entity(TypeKey)(createBehavior = entityContext => Counter(entityContext.entityId)))
Java
EntityTypeKey<Counter.Command> typeKey = EntityTypeKey.create(Counter.Command.class, "Counter");

ActorRef<ShardingEnvelope<Counter.Command>> shardRegion =
    sharding.init(Entity.of(typeKey, ctx -> Counter.create(ctx.getEntityId())));

Messages to a specific entity are then sent via an EntityRef. It is also possible to wrap methods in a ShardingEnvelope or define extractor functions and send messages directly to the shard region.

Scala
// With an EntityRef
val counterOne: EntityRef[Counter.Command] = sharding.entityRefFor(TypeKey, "counter-1")
counterOne ! Counter.Increment

// Entity id is specified via an `ShardingEnvelope`
shardRegion ! ShardingEnvelope("counter-1", Counter.Increment)
Java
EntityRef<Counter.Command> counterOne = sharding.entityRefFor(typeKey, "counter-1");
counterOne.tell(Counter.Increment.INSTANCE);

shardRegion.tell(new ShardingEnvelope<>("counter-1", Counter.Increment.INSTANCE));

Cluster sharding init should be called on every node for each entity type. Which nodes entity actors are created on can be controlled with roles. init will create a ShardRegion or a proxy depending on whether the node’s role matches the entity’s role.

Specifying the role:

Scala
sharding.init(
  Entity(TypeKey)(createBehavior = entityContext => Counter(entityContext.entityId)).withRole("backend"))
Java
EntityTypeKey<Counter.Command> typeKey = EntityTypeKey.create(Counter.Command.class, "Counter");

ActorRef<ShardingEnvelope<Counter.Command>> shardRegionOrProxy =
    sharding.init(
        Entity.of(typeKey, ctx -> Counter.create(ctx.getEntityId())).withRole("backend"));

Persistence example

When using sharding, entities can be moved to different nodes in the cluster. Persistence can be used to recover the state of an actor after it has moved.

Akka Persistence is based on the single-writer principle, for a particular PersistenceId only one persistent actor instance should be active. If multiple instances were to persist events at the same time, the events would be interleaved and might not be interpreted correctly on replay. Cluster Sharding is typically used together with persistence to ensure that there is only one active entity for each PersistenceId (entityId).

Here is an example of a persistent actor that is used as a sharded entity:

Scala
import akka.actor.typed.Behavior
import akka.cluster.sharding.typed.scaladsl.EntityTypeKey
import akka.persistence.typed.scaladsl.Effect

object HelloWorld {

  // Command
  trait Command extends CborSerializable
  final case class Greet(whom: String)(val replyTo: ActorRef[Greeting]) extends Command
  // Response
  final case class Greeting(whom: String, numberOfPeople: Int) extends CborSerializable

  // Event
  final case class Greeted(whom: String) extends CborSerializable

  // State
  final case class KnownPeople(names: Set[String]) extends CborSerializable {
    def add(name: String): KnownPeople = copy(names = names + name)

    def numberOfPeople: Int = names.size
  }

  private val commandHandler: (KnownPeople, Command) => Effect[Greeted, KnownPeople] = { (_, cmd) =>
    cmd match {
      case cmd: Greet => greet(cmd)
    }
  }

  private def greet(cmd: Greet): Effect[Greeted, KnownPeople] =
    Effect.persist(Greeted(cmd.whom)).thenRun(state => cmd.replyTo ! Greeting(cmd.whom, state.numberOfPeople))

  private val eventHandler: (KnownPeople, Greeted) => KnownPeople = { (state, evt) =>
    state.add(evt.whom)
  }

  val TypeKey: EntityTypeKey[Command] =
    EntityTypeKey[Command]("HelloWorld")

  def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = {
    Behaviors.setup { context =>
      context.log.info("Starting HelloWorld {}", entityId)
      EventSourcedBehavior(persistenceId, emptyState = KnownPeople(Set.empty), commandHandler, eventHandler)
    }
  }

}
Java
import akka.actor.typed.javadsl.Behaviors;
import akka.cluster.sharding.typed.javadsl.EntityTypeKey;
import akka.persistence.typed.PersistenceId;
import akka.persistence.typed.javadsl.CommandHandler;
import akka.persistence.typed.javadsl.Effect;
import akka.persistence.typed.javadsl.EventHandler;

public static class HelloWorld
    extends EventSourcedBehavior<HelloWorld.Command, HelloWorld.Greeted, HelloWorld.KnownPeople> {

  // Command
  public interface Command extends CborSerializable {}

  public static final class Greet implements Command {
    public final String whom;
    public final ActorRef<Greeting> replyTo;

    public Greet(String whom, ActorRef<Greeting> replyTo) {
      this.whom = whom;
      this.replyTo = replyTo;
    }
  }

  // Response
  public static final class Greeting implements CborSerializable {
    public final String whom;
    public final int numberOfPeople;

    public Greeting(String whom, int numberOfPeople) {
      this.whom = whom;
      this.numberOfPeople = numberOfPeople;
    }
  }

  // Event
  public static final class Greeted implements CborSerializable {
    public final String whom;

    @JsonCreator
    public Greeted(String whom) {
      this.whom = whom;
    }
  }

  // State
  static final class KnownPeople implements CborSerializable {
    private Set<String> names = Collections.emptySet();

    KnownPeople() {}

    private KnownPeople(Set<String> names) {
      this.names = names;
    }

    KnownPeople add(String name) {
      Set<String> newNames = new HashSet<>(names);
      newNames.add(name);
      return new KnownPeople(newNames);
    }

    int numberOfPeople() {
      return names.size();
    }
  }

  public static final EntityTypeKey<Command> ENTITY_TYPE_KEY =
      EntityTypeKey.create(Command.class, "HelloWorld");

  public static Behavior<Command> create(String entityId, PersistenceId persistenceId) {
    return Behaviors.setup(context -> new HelloWorld(context, entityId, persistenceId));
  }

  private HelloWorld(
      ActorContext<Command> context, String entityId, PersistenceId persistenceId) {
    super(persistenceId);
    context.getLog().info("Starting HelloWorld {}", entityId);
  }

  @Override
  public KnownPeople emptyState() {
    return new KnownPeople();
  }

  @Override
  public CommandHandler<Command, Greeted, KnownPeople> commandHandler() {
    return newCommandHandlerBuilder().forAnyState().onCommand(Greet.class, this::greet).build();
  }

  private Effect<Greeted, KnownPeople> greet(KnownPeople state, Greet cmd) {
    return Effect()
        .persist(new Greeted(cmd.whom))
        .thenRun(newState -> cmd.replyTo.tell(new Greeting(cmd.whom, newState.numberOfPeople())));
  }

  @Override
  public EventHandler<KnownPeople, Greeted> eventHandler() {
    return (state, evt) -> state.add(evt.whom);
  }
}

To initialize and use the entity:

Scala
import akka.cluster.sharding.typed.scaladsl.ClusterSharding
import akka.cluster.sharding.typed.scaladsl.Entity
import akka.util.Timeout

class HelloWorldService(system: ActorSystem[_]) {
  import system.executionContext

  private val sharding = ClusterSharding(system)

  // registration at startup
  sharding.init(Entity(typeKey = HelloWorld.TypeKey) { entityContext =>
    HelloWorld(entityContext.entityId, PersistenceId(entityContext.entityTypeKey.name, entityContext.entityId))
  })

  private implicit val askTimeout: Timeout = Timeout(5.seconds)

  def greet(worldId: String, whom: String): Future[Int] = {
    val entityRef = sharding.entityRefFor(HelloWorld.TypeKey, worldId)
    val greeting = entityRef ? HelloWorld.Greet(whom)
    greeting.map(_.numberOfPeople)
  }

}
Java
import akka.cluster.sharding.typed.javadsl.ClusterSharding;
import akka.cluster.sharding.typed.javadsl.EntityRef;
import akka.cluster.sharding.typed.javadsl.Entity;
import akka.persistence.typed.javadsl.EventSourcedBehavior;
import akka.serialization.jackson.CborSerializable;
import akka.util.Timeout;
import com.fasterxml.jackson.annotation.JsonCreator;

public static class HelloWorldService {
  private final ActorSystem<?> system;
  private final ClusterSharding sharding;
  private final Duration askTimeout = Duration.ofSeconds(5);

  // registration at startup
  public HelloWorldService(ActorSystem<?> system) {
    this.system = system;
    sharding = ClusterSharding.get(system);

    // registration at startup
    sharding.init(
        Entity.of(
            HelloWorld.ENTITY_TYPE_KEY,
            entityContext ->
                HelloWorld.create(
                    entityContext.getEntityId(),
                    PersistenceId.of(
                        entityContext.getEntityTypeKey().name(), entityContext.getEntityId()))));
  }

  // usage example
  public CompletionStage<Integer> sayHello(String worldId, String whom) {
    EntityRef<HelloWorld.Command> entityRef =
        sharding.entityRefFor(HelloWorld.ENTITY_TYPE_KEY, worldId);
    CompletionStage<HelloWorld.Greeting> result =
        entityRef.ask(replyTo -> new HelloWorld.Greet(whom, replyTo), askTimeout);
    return result.thenApply(greeting -> greeting.numberOfPeople);
  }
}

Note how an unique PersistenceIdPersistenceId can be constructed from the EntityTypeKey and the entityId provided by the EntityContextEntityContext in the factory function for the Behavior. This is a typical way of defining the PersistenceId but other formats are possible, as described in the PersistenceId section.

Sending messages to persistent entities is the same as if the entity wasn’t persistent. The only difference is when an entity is moved the state will be restored. In the above example ask is used but tell or any of the other Interaction Patterns can be used.

See persistence for more details.

Shard allocation

A shard is a group of entities that will be managed together. The grouping is typically defined by a hashing function of the entityId. For a specific entity identifier the shard identifier must always be the same. Otherwise the entity actor might accidentally be started in several places at the same time.

By default the shard identifier is the absolute value of the hashCode of the entity identifier modulo the total number of shards. The number of shards is configured by:

akka.cluster.sharding {
  # Number of shards used by the default HashCodeMessageExtractor
  # when no other message extractor is defined. This value must be
  # the same for all nodes in the cluster and that is verified by
  # configuration check when joining. Changing the value requires
  # stopping all nodes in the cluster.
  number-of-shards = 1000
}

As a rule of thumb, the number of shards should be a factor ten greater than the planned maximum number of cluster nodes. It doesn’t have to be exact. Fewer shards than number of nodes will result in that some nodes will not host any shards. Too many shards will result in less efficient management of the shards, e.g. rebalancing overhead, and increased latency because the coordinator is involved in the routing of the first message for each shard.

The number-of-shards configuration value must be the same for all nodes in the cluster and that is verified by configuration check when joining. Changing the value requires stopping all nodes in the cluster.

The shards are allocated to the nodes in the cluster. The decision of where to allocate a shard is done by a shard allocation strategy. The default implementation akka.cluster.sharding.ShardCoordinator.LeastShardAllocationStrategy allocates new shards to the ShardRegion (node) with least number of previously allocated shards. This strategy can be replaced by an application specific implementation.

An optional custom shard allocation strategy can be passed into the optional parameter when initializing an entity type or explicitly using the withAllocationStrategy function. See the API documentation of akka.cluster.sharding.ShardAllocationStrategyakka.cluster.sharding.AbstractShardAllocationStrategy for details of how to implement a custom ShardAllocationStrategy.

How it works

See Cluster Sharding concepts.

Sharding State Store Mode

There are two cluster sharding states managed:

  1. ShardCoordinator State - the Shard locations
  2. Remembering Entities - the entities in each Shard, which is optional, and disabled by default

For these, there are currently two modes which define how these states are stored:

Warning

Persistence for state store mode is deprecated.

Changing the mode requires a full cluster restart.

Distributed Data Mode

This mode is enabled with configuration (enabled by default):

akka.cluster.sharding.state-store-mode = ddata

The state of the ShardCoordinator is replicated across the cluster but is not durable, not stored to disk. The ShardCoordinator state replication is handled by Distributed Data with WriteMajority/ReadMajority consistency. When all nodes in the cluster have been stopped, the state is no longer needed and dropped.

The state of Remembering Entities is durable and stored to disk. This means remembered entities are restarted even after a complete (non-rolling) cluster restart when the disk is still available.

Cluster Sharding uses its own Distributed Data Replicator per node. If using roles with sharding there is one Replicator per role, which enables a subset of all nodes for some entity types and another subset for other entity types. Each such replicator has a name that contains the node role and therefore the role configuration must be the same on all nodes in the cluster, for example you can’t change the roles when performing a rolling upgrade. Changing roles requires a full cluster restart.

The settings for Distributed Data are configured in the section akka.cluster.sharding.distributed-data. It’s not possible to have different distributed-data settings for different sharding entity types.

Persistence Mode

This mode is enabled with configuration:

akka.cluster.sharding.state-store-mode = persistence

Since it is running in a cluster Persistence must be configured with a distributed journal.

Note

Persistence mode for Remembering Entities will be replaced by a pluggable data access API with storage implementations, see #27763. New sharding applications should no longer choose persistence mode. Existing users of persistence mode can eventually migrate to the replacement options.

Passivation

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]ActorRef<ShardCommand> that was passed in to the factory method when creating the entity. The optional stopMessage message will be sent back to the entity, which is then supposed to stop itself, otherwise it will be stopped automatically. Incoming messages will be buffered by the Shard between reception of Passivate and termination of the entity. Such buffered messages are thereafter delivered to a new incarnation of the entity.

Scala
object Counter {
  sealed trait Command
  case object Increment extends Command
  final case class GetValue(replyTo: ActorRef[Int]) extends Command
  private case object Idle extends Command
  case object GoodByeCounter extends Command

  def apply(shard: ActorRef[ClusterSharding.ShardCommand], entityId: String): Behavior[Command] = {
    Behaviors.setup { ctx =>
      def updated(value: Int): Behavior[Command] =
        Behaviors.receiveMessage[Command] {
          case Increment =>
            updated(value + 1)
          case GetValue(replyTo) =>
            replyTo ! value
            Behaviors.same
          case Idle =>
            // after receive timeout
            shard ! ClusterSharding.Passivate(ctx.self)
            Behaviors.same
          case GoodByeCounter =>
            // the stopMessage, used for rebalance and passivate
            Behaviors.stopped
        }

      ctx.setReceiveTimeout(30.seconds, Idle)
      updated(0)
    }
  }
}
Java
public class Counter2 extends AbstractBehavior<Counter2.Command> {

  public interface Command {}

  private enum Idle implements Command {
    INSTANCE
  }

  public enum GoodByeCounter implements Command {
    INSTANCE
  }

  public enum Increment implements Command {
    INSTANCE
  }

  public static class GetValue implements Command {
    private final ActorRef<Integer> replyTo;

    public GetValue(ActorRef<Integer> replyTo) {
      this.replyTo = replyTo;
    }
  }

  public static Behavior<Command> create(
      ActorRef<ClusterSharding.ShardCommand> shard, String entityId) {
    return Behaviors.setup(
        ctx -> {
          ctx.setReceiveTimeout(Duration.ofSeconds(30), Idle.INSTANCE);
          return new Counter2(ctx, shard, entityId);
        });
  }

  private final ActorRef<ClusterSharding.ShardCommand> shard;
  private final String entityId;
  private int value = 0;

  private Counter2(
      ActorContext<Command> context,
      ActorRef<ClusterSharding.ShardCommand> shard,
      String entityId) {
    super(context);
    this.shard = shard;
    this.entityId = entityId;
  }

  @Override
  public Receive<Command> createReceive() {
    return newReceiveBuilder()
        .onMessage(Increment.class, msg -> onIncrement())
        .onMessage(GetValue.class, this::onGetValue)
        .onMessage(Idle.class, msg -> onIdle())
        .onMessage(GoodByeCounter.class, msg -> onGoodByeCounter())
        .build();
  }

  private Behavior<Command> onIncrement() {
    value++;
    return this;
  }

  private Behavior<Command> onGetValue(GetValue msg) {
    msg.replyTo.tell(value);
    return this;
  }

  private Behavior<Command> onIdle() {
    // after receive timeout
    shard.tell(new ClusterSharding.Passivate<>(getContext().getSelf()));
    return this;
  }

  private Behavior<Command> onGoodByeCounter() {
    // the stopMessage, used for rebalance and passivate
    return Behaviors.stopped();
  }
}

and then initialized with:

Scala
val TypeKey = EntityTypeKey[Counter.Command]("Counter")

ClusterSharding(system).init(Entity(TypeKey)(createBehavior = entityContext =>
  Counter(entityContext.shard, entityContext.entityId)).withStopMessage(Counter.GoodByeCounter))
Java

EntityTypeKey<Counter2.Command> typeKey = EntityTypeKey.create(Counter2.Command.class, "Counter"); sharding.init( Entity.of(typeKey, ctx -> Counter2.create(ctx.getShard(), ctx.getEntityId())) .withStopMessage(Counter2.GoodByeCounter.INSTANCE));

Note that in the above example the stopMessage is specified as GoodByeCounter. That message will be sent to the entity when it’s supposed to stop itself due to rebalance or passivation. If the stopMessage is not defined it will be stopped automatically without receiving a specific message. It can be useful to define a custom stop message if the entity needs to perform some asynchronous cleanup or interactions before stopping.

Automatic Passivation

The entities are automatically passivated if they haven’t received a message within the duration configured in akka.cluster.sharding.passivate-idle-entity-after or by explicitly setting the passivateIdleEntityAfter flag on ClusterShardingSettings to a suitable time to keep the actor alive. Note that only messages sent through sharding are counted, so direct messages to the ActorRef or messages that the actor sends to itself are not counted in this activity. Passivation can be disabled by setting akka.cluster.sharding.passivate-idle-entity-after = off. It is disabled automatically if Remembering Entities is enabled.

Remembering Entities

Remembering entities pertains to restarting entities after a rebalance or recovering from a crash. Enabling or disabling (the default) this feature drives the behavior of the restarts:

  • enabled: entities are restarted, even though no new messages are sent to them. This will also disable Automtic Passivation.
  • disabled: entities are restarted, on demand when a new message arrives.

Note that the state of the entities themselves will not be restored unless they have been made persistent, for example with Event Sourcing.

To make the list of entities in each Shard persistent (durable) set the rememberEntities flag to true in ClusterShardingSettings when starting a shard region (or its proxy) for a given entity type or configure akka.cluster.sharding.remember-entities = on.

The performance cost of rememberEntities is rather high when starting/stopping entities and when shards are rebalanced. This cost increases with number of entities per shard, thus it is not recommended with more than 10000 active entities per shard.

Behavior When Enabled

When rememberEntities is enabled, whenever a Shard is rebalanced onto another node or recovers after a crash it will recreate all the entities which were previously running in that Shard. To permanently stop entities, a Passivate message must be sent to the parent of the entity actor, otherwise the entity will be automatically restarted after the entity restart backoff specified in the configuration.

When Distributed Data mode is used the identifiers of the entities are stored in Durable Storage of Distributed Data. You may want to change the configuration of the akka.cluster.sharding.distributed-data.durable.lmdb.dir, since the default directory contains the remote port of the actor system. If using a dynamically assigned port (0) it will be different each time and the previously stored data will not be loaded.

The reason for storing the identifiers of the active entities in durable storage, i.e. stored to disk, is that the same entities should be started also after a complete cluster restart. If this is not needed you can disable durable storage and benefit from better performance by using the following configuration:

akka.cluster.sharding.distributed-data.durable.keys = []

Behavior When Not Enabled

When rememberEntities is disabled (the default), a Shard will not automatically restart any entities after a rebalance or recovering from a crash. Instead, entities are started once the first message for that entity has been received in the Shard.

Startup after minimum number of members

It’s recommended to use Cluster Sharding with the Cluster setting akka.cluster.min-nr-of-members or akka.cluster.role.<role-name>.min-nr-of-members. min-nr-of-members will defer the allocation of the shards until at least that number of regions have been started and registered to the coordinator. This avoids that many shards are allocated to the first region that registers and only later are rebalanced to other nodes.

See How To Startup when Cluster Size Reached for more information about min-nr-of-members.

Lease

A lease can be used as an additional safety measure to ensure a shard does not run on two nodes.

Reasons for how this can happen:

  • Network partitions without an appropriate downing provider
  • Mistakes in the deployment process leading to two separate Akka Clusters
  • Timing issues between removing members from the Cluster on one side of a network partition and shutting them down on the other side

A lease can be a final backup that means that each shard won’t create child entity actors unless it has the lease.

To use a lease for sharding set akka.cluster.sharding.use-lease to the configuration location of the lease to use. Each shard will try and acquire a lease with with the name <actor system name>-shard-<type name>-<shard id> and the owner is set to the Cluster(system).selfAddress.hostPort.

If a shard can’t acquire a lease it will remain uninitialized so messages for entities it owns will be buffered in the ShardRegion. If the lease is lost after initialization the Shard will be terminated.

Removal of internal Cluster Sharding data

Removal of internal Cluster Sharding data is only relevant for “Persistent Mode”. The Cluster Sharding ShardCoordinator stores locations of the shards. This data is safely be removed when restarting the whole Akka Cluster. Note that this does not include application data.

There is a utility program akka.cluster.sharding.RemoveInternalClusterShardingData that removes this data.

Warning

Never use this program while there are running Akka Cluster nodes that are using Cluster Sharding. Stop all Cluster nodes before using this program.

It can be needed to remove the data if the Cluster Sharding coordinator cannot startup because of corrupt data, which may happen if accidentally two clusters were running at the same time, e.g. caused by an invalid downing provider when there was a network partition.

Use this program as a standalone Java main program:

java -classpath <jar files, including akka-cluster-sharding>
  akka.cluster.sharding.RemoveInternalClusterShardingData
    -2.3 entityType1 entityType2 entityType3

The program is included in the akka-cluster-sharding jar file. It is easiest to run it with same classpath and configuration as your ordinary application. It can be run from sbt or Maven in similar way.

Specify the entity type names (same as you use in the init method of ClusterSharding) as program arguments.

If you specify -2.3 as the first program argument it will also try to remove data that was stored by Cluster Sharding in Akka 2.3.x using different persistenceId.

Configuration

The ClusterSharding extension can be configured with the following properties. These configuration properties are read by the ClusterShardingSettings when created with an ActorSystem parameter. It is also possible to amend the ClusterShardingSettings or create it from another config section with the same layout as below.

One important configuration property is number-of-shards as described in Shard allocation

# Settings for the ClusterShardingExtension
akka.cluster.sharding {

  # The extension creates a top level actor with this name in top level system scope,
  # e.g. '/system/sharding'
  guardian-name = sharding

  # Specifies that entities runs on cluster nodes with a specific role.
  # If the role is not specified (or empty) all nodes in the cluster are used.
  role = ""

  # When this is set to 'on' the active entity actors will automatically be restarted
  # upon Shard restart. i.e. if the Shard is started on a different ShardRegion
  # due to rebalance or crash.
  remember-entities = off

  # Set this to a time duration to have sharding passivate entities when they have not
  # received any message in this length of time. Set to 'off' to disable.
  # It is always disabled if `remember-entities` is enabled.
  passivate-idle-entity-after = 120s

  # If the coordinator can't store state changes it will be stopped
  # and started again after this duration, with an exponential back-off
  # of up to 5 times this duration.
  coordinator-failure-backoff = 5 s

  # The ShardRegion retries registration and shard location requests to the
  # ShardCoordinator with this interval if it does not reply.
  retry-interval = 2 s

  # Maximum number of messages that are buffered by a ShardRegion actor.
  buffer-size = 100000

  # Timeout of the shard rebalancing process.
  # Additionally, if an entity doesn't handle the stopMessage
  # after (handoff-timeout - 5.seconds).max(1.second) it will be stopped forcefully
  handoff-timeout = 60 s

  # Time given to a region to acknowledge it's hosting a shard.
  shard-start-timeout = 10 s

  # If the shard is remembering entities and can't store state changes
  # will be stopped and then started again after this duration. Any messages
  # sent to an affected entity may be lost in this process.
  shard-failure-backoff = 10 s

  # If the shard is remembering entities and an entity stops itself without
  # using passivate. The entity will be restarted after this duration or when
  # the next message for it is received, which ever occurs first.
  entity-restart-backoff = 10 s

  # Rebalance check is performed periodically with this interval.
  rebalance-interval = 10 s

  # Absolute path to the journal plugin configuration entity that is to be
  # used for the internal persistence of ClusterSharding. If not defined
  # the default journal plugin is used. Note that this is not related to
  # persistence used by the entity actors.
  # Only used when state-store-mode=persistence
  journal-plugin-id = ""

  # Absolute path to the snapshot plugin configuration entity that is to be
  # used for the internal persistence of ClusterSharding. If not defined
  # the default snapshot plugin is used. Note that this is not related to
  # persistence used by the entity actors.
  # Only used when state-store-mode=persistence
  snapshot-plugin-id = ""

  # Defines how the coordinator stores its state. Same is also used by the
  # shards for rememberEntities.
  # Valid values are "ddata" or "persistence". 
  state-store-mode = "ddata"

  # The shard saves persistent snapshots after this number of persistent
  # events. Snapshots are used to reduce recovery times.
  # Only used when state-store-mode=persistence
  snapshot-after = 1000

  # The shard deletes persistent events (messages and snapshots) after doing snapshot
  # keeping this number of old persistent batches.
  # Batch is of size `snapshot-after`.
  # When set to 0 after snapshot is successfully done all events with equal or lower sequence number will be deleted.
  # Default value of 2 leaves last maximum 2*`snapshot-after` events and 3 snapshots (2 old ones + latest snapshot)
  keep-nr-of-batches = 2

  # Setting for the default shard allocation strategy
  least-shard-allocation-strategy {
    # Threshold of how large the difference between most and least number of
    # allocated shards must be to begin the rebalancing.
    # The difference between number of shards in the region with most shards and
    # the region with least shards must be greater than (>) the `rebalanceThreshold`
    # for the rebalance to occur.
    # It is also the maximum number of shards that will start rebalancing per rebalance-interval
    # 1 gives the best distribution and therefore typically the best choice.
    # Increasing the threshold can result in quicker rebalance but has the
    # drawback of increased difference between number of shards (and therefore load)
    # on different nodes before rebalance will occur.
    rebalance-threshold = 1

    # The number of ongoing rebalancing processes is limited to this number.
    max-simultaneous-rebalance = 3
  }

  # Timeout of waiting the initial distributed state for the shard coordinator (an initial state will be queried again if the timeout happened)
  # and for a shard to get its state when remembered entities is enabled
  # The read from ddata is a ReadMajority, for small clusters (< majority-min-cap) every node needs to respond
  # so is more likely to time out if there are nodes restarting e.g. when there is a rolling re-deploy happening
  # Only used when state-store-mode=ddata
  waiting-for-state-timeout = 2 s

  # Timeout of waiting for update the distributed state (update will be retried if the timeout happened)
  # Only used when state-store-mode=ddata
  updating-state-timeout = 5 s

  # Timeout to wait for querying all shards for a given `ShardRegion`.
  shard-region-query-timeout = 3 s

  # The shard uses this strategy to determines how to recover the underlying entity actors. The strategy is only used
  # by the persistent shard when rebalancing or restarting. The value can either be "all" or "constant". The "all"
  # strategy start all the underlying entity actors at the same time. The constant strategy will start the underlying
  # entity actors at a fix rate. The default strategy "all".
  entity-recovery-strategy = "all"

  # Default settings for the constant rate entity recovery strategy
  entity-recovery-constant-rate-strategy {
    # Sets the frequency at which a batch of entity actors is started.
    frequency = 100 ms
    # Sets the number of entity actors to be restart at a particular interval
    number-of-entities = 5
  }

  # Settings for the coordinator singleton. Same layout as akka.cluster.singleton.
  # The "role" of the singleton configuration is not used. The singleton role will
  # be the same as "akka.cluster.sharding.role".
  # A lease can be configured in these settings for the coordinator singleton
  coordinator-singleton = ${akka.cluster.singleton}
  
  # Settings for the Distributed Data replicator. 
  # Same layout as akka.cluster.distributed-data.
  # The "role" of the distributed-data configuration is not used. The distributed-data
  # role will be the same as "akka.cluster.sharding.role".
  # Note that there is one Replicator per role and it's not possible
  # to have different distributed-data settings for different sharding entity types.
  # Only used when state-store-mode=ddata
  distributed-data = ${akka.cluster.distributed-data}
  distributed-data {
    # minCap parameter to MajorityWrite and MajorityRead consistency level.
    majority-min-cap = 5
    durable.keys = ["shard-*"]
    
    # When using many entities with "remember entities" the Gossip message
    # can become to large if including to many in same message. Limit to
    # the same number as the number of ORSet per shard.
    max-delta-elements = 5
    
  }

  # The id of the dispatcher to use for ClusterSharding actors.
  # If specified you need to define the settings of the actual dispatcher.
  # This dispatcher for the entity actors is defined by the user provided
  # Props, i.e. this dispatcher is not used for the entity actors.
  use-dispatcher = "akka.actor.internal-dispatcher"

  # Config path of the lease that each shard must acquire before starting entity actors
  # default is no lease
  # A lease can also be used for the singleton coordinator by settings it in the coordinator-singleton properties
  use-lease = ""

  # The interval between retries for acquiring the lease
  lease-retry-interval = 5s
}
akka.cluster.sharding {
  # Number of shards used by the default HashCodeMessageExtractor
  # when no other message extractor is defined. This value must be
  # the same for all nodes in the cluster and that is verified by
  # configuration check when joining. Changing the value requires
  # stopping all nodes in the cluster.
  number-of-shards = 1000
}

Example project

Sharding example project Sharding example project is an example project that can be downloaded, and with instructions of how to run.

This project contains a KillrWeather sample illustrating how to use Cluster Sharding.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.