# Getting Started This page takes you from an empty Spring Boot application to an actor that answers HTTP requests. ## Prerequisites - Java 21 or higher - Spring Boot 3.5 or higher Spring Boot 2 users stay on the 0.x line (`spring-boot-starter-actor`). ## 1. Add the dependency === "Gradle" ```groovy implementation 'io.github.seonwkim:actor-spring-boot-starter:1.1.0' ``` === "Maven" ```xml io.github.seonwkim actor-spring-boot-starter 1.1.0 ``` The latest version is on [Maven Central](https://central.sonatype.com/artifact/io.github.seonwkim/actor-spring-boot-starter). For cluster features (sharding, singletons, replicated data), use `actor-spring-boot-starter-cluster` instead. Other modules are listed on the [home page](index.md#modules). Writing Kotlin? Add `io.github.seonwkim:actor-kotlin:1.1.0` too, for `suspend` functions and reified helpers (see the [Kotlin guide](guides/kotlin.md)). Every code sample in these docs has a Java and a Kotlin tab; your choice applies to the whole site. ### Several modules: import the BOM From 1.1.0, `io.github.seonwkim:actor-bom` lists every module at one version. Import it and leave the version off each module. It manages only this project's modules; Spring Boot keeps managing Pekko's dependencies such as Jackson. === "Gradle" ```groovy implementation platform('io.github.seonwkim:actor-bom:1.1.0') implementation 'io.github.seonwkim:actor-spring-boot-starter' implementation 'io.github.seonwkim:actor-metrics' testImplementation 'io.github.seonwkim:actor-test' ``` === "Maven" ```xml io.github.seonwkim actor-bom 1.1.0 pom import io.github.seonwkim actor-spring-boot-starter io.github.seonwkim actor-metrics io.github.seonwkim actor-test test ``` !!! note Spring Boot 3.5 manages Jackson 2.18+, which satisfies Pekko. No `jackson-bom` override is needed. ## 2. Start the application The starter is a Spring Boot auto-configuration: with the dependency on the classpath, a `@SpringBootApplication` starts one actor system for the Spring context and stops it when the context closes. `spring.actor.enabled=false` keeps the starter on the classpath without starting one. === "Java" ```java @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` === "Kotlin" ```kotlin @SpringBootApplication class MyApplication fun main(args: Array) { runApplication(*args) } ``` !!! note "`@EnableActorSupport` is optional" Applications written for 1.0.0 have `@EnableActorSupport` on the application class. It still works and adds nothing in a Spring Boot application, so you can remove it. Keep it only where auto-configuration is off, such as a context built without `@EnableAutoConfiguration`. ## 3. Write an actor An actor is a Spring bean that implements `SpringActor`. `Command` is the type of message it accepts. A message that expects an answer extends `AskCommand` and answers with `reply(...)`. === "Java" ```java @Component public class GreeterActor implements SpringActor { public interface Command {} public static class Greet extends AskCommand implements Command { public final String name; public Greet(String name) { this.name = name; } } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(Greet.class, (ctx, msg) -> { msg.reply("Hello, " + msg.name + "!"); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin @Component class GreeterActor : SpringActor { sealed interface Command class Greet(val name: String) : AskCommand(), Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { msg -> msg.reply("Hello, ${msg.name}!") same() } } } ``` The actor handles one message at a time, so state inside it needs no locks. Because it's a bean, its constructor can take any other bean (a repository, a client). ## 4. Talk to it Inject `SpringActorSystem`. `getOrSpawn` returns the running actor with that id, or starts it. `ask` sends a message and waits for the reply, up to the timeout. === "Java" ```java @RestController public class GreeterController { private final SpringActorSystem actorSystem; public GreeterController(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } @GetMapping("/greet") public CompletionStage greet(@RequestParam String name) { return actorSystem.getOrSpawn(GreeterActor.class, "greeter") .thenCompose(greeter -> greeter.ask(new GreeterActor.Greet(name)) .withTimeout(Duration.ofSeconds(5)) .execute()); } } ``` === "Kotlin" ```kotlin @RestController class GreeterController(private val actorSystem: SpringActorSystem) { @GetMapping("/greet") suspend fun greet(@RequestParam name: String): String = actorSystem.awaitGetOrSpawn("greeter") .awaitAsk(GreeterActor.Greet(name), timeout = 5.seconds) } ``` In Kotlin, `awaitGetOrSpawn` and `awaitAsk` suspend instead of returning a `CompletionStage`. A `suspend` controller method needs Spring WebFlux, or Spring MVC with `kotlinx-coroutines-reactor` on the classpath. Run the application and call it: ```bash curl 'http://localhost:8080/greet?name=Ada' # Hello, Ada! ``` ## 5. Configure (optional) Nothing is required. Every key lives under `spring.actor`: ```yaml spring: actor: name: orders # actor system name, shown in logs and node addresses provider: local # local (default) or cluster ``` The [configuration reference](guides/operations/configuration.md) lists every key. ## Using an AI assistant If an AI assistant helps you write code with the starter, point it to [llms.txt](llms.txt). It is a short index of these docs, following the [llms.txt](https://llmstxt.org/) convention, with one line per page. For the full text of every page in one file, use [llms-full.txt](https://seonwkim.github.io/actor-spring-boot-starter/llms-full.txt). ## Next steps - [Actors](guides/core/actors.md) and [messaging](guides/core/messaging.md): spawning, ids, tell and ask in depth - [Supervision](guides/core/supervision.md): what happens when an actor fails - [Sharded actors](guides/cluster/sharded-actors.md): spread actors over a cluster - [Testing](guides/testing.md): test actors with `@ActorTest` - [Examples](examples/index.md): runnable applications, from a single node to Kubernetes --- # Actors An actor is an object that owns some state and handles messages one at a time. Code outside the actor never touches that state: it sends a message, and the actor changes its state while it handles the message. Because only one message runs at a time, the actor needs no locks. Use an actor when something has state that many requests change at once (a counter, a chat room, an order, a session, an AI agent's conversation), when work should run in the background without blocking the caller, or when you want a failure to restart one small part of the system instead of the request. This page covers defining actors, Spring dependency injection, actor ids, spawning and finding actors, stopping them, and child actors. Sending messages is in [Messaging](messaging.md), failures in [Supervision](supervision.md), and the tools inside an actor (state, timers, watching) in [Behaviors](behaviors.md). ## Setup Add `actor-spring-boot-starter` to your Spring Boot application, as shown in [Getting Started](../../getting-started.md). That starts one actor system for the Spring context and gives you a `SpringActorSystem` bean to inject. Nothing else is needed for the features on this page. ## Defining an actor An actor is a Spring bean that implements `SpringActor`, where `C` is the type of the messages it accepts (its *commands*). It has one method, `create`, which returns the actor's behavior: which handler runs for which message. === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import org.springframework.stereotype.Component; @Component public class GreeterActor implements SpringActor { // Every message this actor accepts implements Command. public interface Command {} // A message that expects no answer. public record LogVisit(String name) implements Command {} // A message that expects a String answer: it extends AskCommand. public static class Greet extends AskCommand implements Command { public final String name; public Greet(String name) { this.name = name; } } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(LogVisit.class, (ctx, msg) -> { ctx.getLog().info("{} visited", msg.name()); return SpringActorBehavior.same(); }) .onMessage(Greet.class, (ctx, msg) -> { msg.reply("Hello, " + msg.name + "!"); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.kotlin.behavior import org.springframework.stereotype.Component @Component class GreeterActor : SpringActor { // Every message this actor accepts implements Command. sealed interface Command // A message that expects no answer. data class LogVisit(val name: String) : Command // A message that expects a String answer: it extends AskCommand. class Greet(val name: String) : AskCommand(), Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { msg -> log.info("{} visited", msg.name) same() } onMessage { msg -> msg.reply("Hello, ${msg.name}!") same() } } } ``` What each part does: - **`@Component`** makes the class a Spring bean. The starter finds every bean that implements `SpringActor` (or `SpringActorWithContext`) and registers it as an actor type. A `@Bean` method works too. - **`Command`** is the actor's message type. Each message is a class that implements it. Make messages immutable: records or classes with `final` fields (`data class` / `val` in Kotlin). - **`AskCommand`** marks a message that expects an answer of type `R`. The handler answers with `msg.reply(value)`. See [Messaging](messaging.md#ask-request-and-reply). - **`create`** runs once each time an actor of this class is spawned. It gets the actor's context (`actorContext.actorId()` is the id it was spawned with) and returns the behavior. - **`onMessage(Type, handler)`** registers a handler. The handler gets the behavior context (`ctx`: logger, self reference, timers, children) and the message, and returns the next behavior. `same()` means "keep handling messages this way". See [Behaviors](behaviors.md) for the other return values and for keeping state in the actor. In Kotlin, `behavior(actorContext) { ... }` comes from the `actor-kotlin` module and builds the same behavior with `SpringActorBehavior.builder`: `onMessage { msg -> ... }` is `.onMessage(Greet.class, (ctx, msg) -> ...)`, and the handler runs with the behavior context as `this`, so `log` is `ctx.getLog()`. See the [Kotlin guide](../kotlin.md#defining-an-actor). ## Spring dependency injection Actors are ordinary Spring beans, so they get their dependencies through the constructor (or any other injection style): === "Java" ```java @Component public class OrderActor implements SpringActor { private final OrderRepository orderRepository; public OrderActor(OrderRepository orderRepository) { this.orderRepository = orderRepository; } public interface Command {} public record MarkPaid(long orderId) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(MarkPaid.class, (ctx, msg) -> { orderRepository.markPaid(msg.orderId()); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin @Component class OrderActor(private val orderRepository: OrderRepository) : SpringActor { sealed interface Command data class MarkPaid(val orderId: Long) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { msg -> orderRepository.markPaid(msg.orderId) same() } } } ``` Spring creates one `OrderActor` bean, and every actor spawned from that class calls `create` on that same bean. Keep injected services in `final` fields, and per-actor state in the behavior, as the next section shows. ## What not to do in an actor bean !!! danger "Don't" - **Don't keep state in bean fields.** A field of the bean is shared by every actor of the class and changed from many threads at once, which breaks the "one message at a time, no locks" guarantee. Keep per-actor state in the behavior: the state object of [`withState`](behaviors.md#state-with-withstate). - **Don't block the default dispatcher.** A JPA repository or a blocking HTTP client holds the thread while it waits, and the default dispatcher's few threads run out. Spawn such actors with `withBlockingDispatcher()` (see [Dispatchers](dispatchers.md)), or call a non-blocking client and turn its `CompletionStage` into a message with [`pipeToSelf`](behaviors.md#futures-pipetoself). - **Don't put proxy annotations on an actor bean.** `@Transactional`, `@Async` or `@Cacheable` make Spring wrap the bean in a proxy, but the handlers run in the behavior that `create` returns, not through the proxy, so the advice never applies to them, and a transaction can't span messages anyway. Put `@Transactional` on a separate service the handler calls. === "Java" ```java @Service public class PaymentService { @Transactional // on the service, not on the actor public void markPaid(long orderId) { // update the order and the ledger in one transaction } } @Component public class OrderActor implements SpringActor { private final PaymentService payments; // wiring: injected and final // private int paidCount; // don't: shared by every OrderActor public OrderActor(PaymentService payments) { this.payments = payments; } public interface Command {} public record MarkPaid(long orderId) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> new Paid()) // one per actor .onMessage(MarkPaid.class, (paid, msg) -> { payments.markPaid(msg.orderId()); // blocks: see the spawn below paid.count++; return SpringActorBehavior.same(); }) .build(); } private static class Paid { int count; // only this actor's thread touches it } } // The handler waits on the database, so the actor runs on the blocking dispatcher. actorSystem.actor(OrderActor.class).withId("order-42").withBlockingDispatcher().getOrSpawn(); ``` === "Kotlin" ```kotlin @Service class PaymentService { @Transactional // on the service, not on the actor fun markPaid(orderId: Long) { // update the order and the ledger in one transaction } } @Component class OrderActor(private val payments: PaymentService) : SpringActor { // private var paidCount = 0 // don't: shared by every OrderActor sealed interface Command data class MarkPaid(val orderId: Long) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext, state = { Paid() }) { // one per actor onMessage { msg -> payments.markPaid(msg.orderId) // blocks: see the spawn below count++ same() } } private class Paid { var count = 0 // only this actor's thread touches it } } // The handler waits on the database, so the actor runs on the blocking dispatcher. actorSystem.actor().withId("order-42").withBlockingDispatcher().getOrSpawn() ``` The starter checks the first and the last rule when it starts. For each actor bean (`SpringActor`, `SpringShardedActor`) it logs a warning for every instance field that is neither `static` nor `final`, superclasses included, and for a bean that is a Spring AOP proxy. Fields Spring injects are wiring, not state, and don't count: those annotated with `@Autowired`, `@Value`, `@Inject` or `@Resource`, those set through a setter with one of these annotations, and properties set on the bean definition. A `final` field that holds a mutable object (a `HashMap`, an `AtomicInteger`) is shared just the same, but the check can't tell it apart from a service, so it doesn't report it. | `spring.actor.validation.actor-beans` | Effect | |---|---| | `warn` (default) | Logs one warning per problem, naming the bean, its class and the field | | `fail` | Stops startup with an error that lists the problems | | `off` | Doesn't check | ## Actor ids Every actor has an id: the string you pass to `withId(...)` or `getOrSpawn(..., id)`. The starter names the actor `:`, so: - An id is unique per actor class. `OrderActor` "42" and `InvoiceActor` "42" are two different actors. - An id is unique within its parent. Top-level actors (spawned from `SpringActorSystem`) share one parent on each node; a child's id only has to be unique among its parent's children. - A plain actor lives on the node that spawned it. In cluster mode, `get` and `exists` on another node don't see it. For one actor per id across the whole cluster, use [sharded actors](../cluster/sharded-actors.md); for one actor per cluster, use [cluster singletons](../cluster/singletons.md). Use ids that come from your domain, such as an order id or a user id, so any request can find its actor again. ## Spawning and finding actors Inject `SpringActorSystem` wherever you need an actor. Every call returns a `CompletionStage` (the Kotlin module adds `suspend` versions). | Method | What it does | Default timeout | When it does not work out | |---|---|---|---| | `getOrSpawn(Class, id)` | Returns the running actor, or spawns it with default settings | 3 s | Fails if the spawn fails | | `find(Class, id)` | Returns the running actor | 3 s | Completes with an empty `Optional` when there is none; fails on timeout | | `exists(Class, id)` | Says whether the actor runs | 3 s | Completes with `false` when there is none; fails on timeout | | `actor(Class)` | Starts a spawn builder for custom settings (see below) | 3 s | | Each method has an overload with a `Duration timeout` as the last argument. ### getOrSpawn: the usual way `getOrSpawn` is the simplest way to use an actor. Call it on every request with the id from the request; the first call spawns the actor, later calls return it. === "Java" ```java @Service public class GreeterService { private final SpringActorSystem actorSystem; public GreeterService(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } public CompletionStage greet(String name) { return actorSystem.getOrSpawn(GreeterActor.class, "greeter") .thenCompose(greeter -> greeter .ask(new GreeterActor.Greet(name)) .withTimeout(Duration.ofSeconds(3)) .execute()); } } ``` === "Kotlin" ```kotlin @Service class GreeterService(private val actorSystem: SpringActorSystem) { // A suspend function: call it from a coroutine or a suspend controller method. suspend fun greet(name: String): String = actorSystem.awaitGetOrSpawn("greeter") .awaitAsk(GreeterActor.Greet(name), timeout = 3.seconds) } ``` In a WebFlux application, wrap the stage with `Mono.fromCompletionStage(...)` (Java) or use a `suspend` controller method (Kotlin). `getOrSpawn` checks for the running actor and spawns it in one step, so callers that ask for the same **new** id at the same moment all get the same actor. ### The spawn builder: custom settings `actorSystem.actor(Class)` returns a builder. Set the id and any options, then end with `spawn()`, `getOrSpawn()` or `spawnAndWait()`: === "Java" ```java CompletionStage> order = actorSystem .actor(OrderActor.class) .withId("order-42") .withBlockingDispatcher() // it calls a JPA repository .withMailbox(MailboxConfig.bounded(1_000)) .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, Duration.ofMinutes(1))) .withTimeout(Duration.ofSeconds(5)) .getOrSpawn(); ``` === "Kotlin" ```kotlin // In a suspend function val order: SpringActorHandle = actorSystem .actor() .withId("order-42") .withBlockingDispatcher() // it calls a JPA repository .withMailbox(MailboxConfig.bounded(1_000)) .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, 1.minutes)) .withTimeout(5.seconds) .awaitGetOrSpawn() ``` | Builder method | What it sets | Default | |---|---|---| | `withId(String)` | The actor id. Required unless you pass a context. | none | | `withContext(SpringActorContext)` | A custom context (see [Custom actor context](#custom-actor-context)). Its `actorId()` is the id. | a context holding the id | | `withTimeout(Duration)` | How long to wait for the spawn | 3 s | | `withSupervisionStrategy(...)` | What happens when a handler throws. See [Supervision](supervision.md). | stop | | `withDefaultDispatcher()`, `withBlockingDispatcher()`, `withDispatcherFromConfig(name)`, `withDispatcherSameAsParent()` | The thread pool. See [Dispatchers](dispatchers.md). | default dispatcher | | `withMailbox(MailboxConfig)` | The mailbox: `MailboxConfig.bounded(n)` or `MailboxConfig.fromConfig(name)`. See [Mailboxes](dispatchers.md#mailboxes). | unbounded | | `withTags(TagsConfig)` | Tags in the `pekkoTags` log field. See [Logging](logging.md). | none | | `withMdc(MdcConfig)` | Fixed MDC values on every log line of the actor. See [Logging](logging.md). | none | | `asClusterSingleton()` | One instance in the cluster. Cluster mode only. See [Singletons](../cluster/singletons.md). | off | | Ending | Returns | Notes | |---|---|---| | `spawn()` | `CompletionStage>` | Fails if an actor with this class and id already runs | | `getOrSpawn()` | `CompletionStage>` | Returns the running actor if there is one; the options apply only when it spawns | | `spawnAndWait()` | `SpringActorHandle` | Blocks the calling thread until the actor runs | `actorSystem.getOrSpawn(Class, id)` is `actor(Class).withId(id).getOrSpawn()` with every option at its default. !!! warning "Don't block where threads are shared" `spawnAndWait()` (and `.toCompletableFuture().join()` on any stage) blocks the calling thread. That is fine in a test or at startup, but not inside an actor's handler or a WebFlux pipeline: compose the stage instead, or use the `suspend` functions in Kotlin. ### find and exists `find` returns a handle to a running actor and `exists` says whether one runs. Neither spawns anything. Use them when an absent actor means something to your code, for example "this order was never opened": === "Java" ```java actorSystem.find(OrderActor.class, "order-42").thenAccept(order -> order.ifPresentOrElse( o -> o.tell(new OrderActor.MarkPaid(42)), () -> log.info("order-42 is not running"))); ``` === "Kotlin" ```kotlin // In a suspend function val order = actorSystem.awaitGet("order-42") if (order == null) { log.info("order-42 is not running") } else { order.tell(OrderActor.MarkPaid(42)) } ``` Both look at the top-level actors of this node and at the [cluster singletons](../cluster/singletons.md) this node spawned. When the actor system doesn't answer within the timeout (3 s by default), the stage fails with a `TimeoutException`; it never reports a running actor as missing. `get(Class, id)`, which completes with `null` when no actor runs, is deprecated: use `find`. Spawning a top-level actor, `find` and `exists` are each a request to one actor on the node, which keeps the top-level actors as its children and answers in turn. That suits up to hundreds of long-lived actors, looked up once and kept (see below). For an actor per user, order or session that is created and stopped often, use [sharded actors](../cluster/sharded-actors.md): you send to an id, the shard region routes the message without asking that one actor, and the entity starts on its first message and stops when idle. They also run on one node, as a one-node cluster (`spring.actor.cluster.join-self`). ### Keeping a handle A `SpringActorHandle` stays valid for as long as the actor runs, and sending through it costs nothing extra. If a service talks to the same actor on every request, look it up once and keep the stage: === "Java" ```java @Service public class CounterService { private final SpringActorSystem actorSystem; private final AtomicReference>> counter = new AtomicReference<>(); public CounterService(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } private CompletionStage> counter() { return counter.updateAndGet(existing -> existing != null ? existing : actorSystem.getOrSpawn(CounterActor.class, "counter")); } public CompletionStage increment() { return counter().thenCompose(c -> c.ask(new CounterActor.Increment()).execute()); } } ``` === "Kotlin" ```kotlin @Service class CounterService(private val actorSystem: SpringActorSystem) { // Spawned on first use; later calls reuse the same handle. private val counter = AtomicReference>>() private fun counter(): CompletionStage> = counter.updateAndGet { existing -> existing ?: actorSystem.getOrSpawn(CounterActor::class.java, "counter") } suspend fun increment(): Long = counter().await().awaitAsk(CounterActor.Increment()) } ``` A kept handle points at one actor. If that actor stops, messages sent through the handle are lost (they go to dead letters). Keep handles only to actors that live as long as the service, or look the actor up again after it stops. ### Spawning at startup A bean may spawn its actors in its constructor or in a `@PostConstruct` method, as the logging example's `OrderService` does. Spring may not have created the actor's bean yet at that point (beans are created in an order you don't control); the spawn then asks Spring for the actor bean first, so it gets created on the spot. Blocking with `spawnAndWait()` is fine there, since startup runs on Spring's own thread. === "Java" ```java @Service public class OrderService { private final SpringActorHandle orders; public OrderService(SpringActorSystem actorSystem) { this.orders = actorSystem.actor(OrderActor.class).withId("orders").spawnAndWait(); } } ``` === "Kotlin" ```kotlin @Service class OrderService(actorSystem: SpringActorSystem) { private val orders: SpringActorHandle = actorSystem.actor(OrderActor::class.java).withId("orders").spawnAndWait() } ``` The actor class must be a bean of the same application context (for example annotated with `@Component`). If it isn't, the spawn fails with "No factory registered for class ...". ## Custom actor context `SpringActor` receives a plain `SpringActorContext`, which holds the actor id. To give an actor more than its id when it starts, define your own context class and implement `SpringActorWithContext` instead: === "Java" ```java @Component public class ReportActor implements SpringActorWithContext { public static class ReportContext extends SpringActorContext { private final String reportId; final String ownerEmail; public ReportContext(String reportId, String ownerEmail) { this.reportId = reportId; this.ownerEmail = ownerEmail; } @Override public String actorId() { return reportId; } } public interface Command {} public record Build() implements Command {} @Override public SpringActorBehavior create(ReportContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(Build.class, (ctx, msg) -> { ctx.getLog().info("Building {} for {}", actorContext.actorId(), actorContext.ownerEmail); return SpringActorBehavior.same(); }) .build(); } } // Spawning it actorSystem.actor(ReportActor.class) .withContext(new ReportActor.ReportContext("report-7", "kim@example.com")) .getOrSpawn(); ``` === "Kotlin" ```kotlin @Component class ReportActor : SpringActorWithContext { class ReportContext(private val reportId: String, val ownerEmail: String) : SpringActorContext() { override fun actorId(): String = reportId } sealed interface Command class Build : Command override fun create(actorContext: ReportContext): SpringActorBehavior = behavior(actorContext) { onMessage { log.info("Building {} for {}", actorContext.actorId(), actorContext.ownerEmail) same() } } } // Spawning it, in a suspend function actorSystem.actor() .withContext(ReportActor.ReportContext("report-7", "kim@example.com")) .awaitGetOrSpawn() ``` Always spawn such an actor through the builder with `withContext(...)`. A spawn by id alone (`actorSystem.getOrSpawn(ReportActor.class, id)`, or `withId(...)` without `withContext`) can't build a `ReportContext`, so its stage fails with an `IllegalArgumentException` that names the context type and says to use `withContext(...)`. `find` and `exists` work as usual: they only need the id. ## Stopping actors An actor runs until it is stopped. There are three ways to stop one: | From | How | Notes | |---|---|---| | Outside the actor | `handle.stop()` | The stop request goes into the mailbox, so messages sent before it are handled first. | | Inside the actor | return `SpringActorBehavior.stopped()` from a handler | Stops after the current message. | | A parent | `ctx.stop(childRef)` in the parent's handler | Only for the parent's own children. | When an actor stops, its `PostStop` signal handler runs (see [Behaviors](behaviors.md#lifecycle-signals)), its children stop, and messages still in its mailbox are dropped. Stopping is final: to use the id again, spawn a new actor. Stopping takes a moment, so a spawn with the same id right after `stop()` can still find the name taken; `getOrSpawn` after the old actor is gone, or [watch](behaviors.md#watching-other-actors) it and spawn on `ActorTerminated`. An idle actor is not stopped for you. If you create one actor per user or per order, stop it when its work is done (for example with a [timer](behaviors.md#timers) that fires after some idle time), or use [sharded actors](../cluster/sharded-actors.md), which can passivate idle entities. ## Child actors An actor can spawn its own actors, called children. Use children to split work under one owner: a `ParentSupervisor` with a worker per task, a chat room with an actor per connection. Children are tied to their parent: - A child stops when its parent stops. - The parent decides how each child is supervised (see [Supervision](supervision.md#supervising-children)). - A child's id only has to be unique among its parent's children. ### Enable child operations on the parent Spawning, finding and checking children works through messages that the parent handles for you. They are turned on when the parent's command type extends `FrameworkCommand`: === "Java" ```java public interface Command extends FrameworkCommand {} ``` === "Kotlin" ```kotlin sealed interface Command : FrameworkCommand ``` Without it, the parent ignores these requests, and every child operation fails with a timeout. ### Spawning children from inside the parent Inside a handler, `ctx.getSelf()` is a handle to the parent. Call `child(ChildClass)` on it to get a child builder. The spawn is a message to the parent itself, and the parent handles it after the current message. So **never wait for it inside the handler** (`spawnAndWait()` or `join()`): the parent would wait for a message it can't handle until it finishes waiting, and the spawn times out. Use `pipeToSelf` to get the result back as a message instead: === "Java" ```java @Component public class DispatcherActor implements SpringActor { public interface Command extends FrameworkCommand {} public record Assign(String workerId, String task) implements Command {} // The result of a child spawn, delivered back to this actor as a message. record WorkerReady(Assign assign, SpringActorHandle worker, Throwable error) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(Assign.class, (ctx, msg) -> { ctx.pipeToSelf( ctx.getSelf() .child(WorkerActor.class) .withId(msg.workerId()) .withSupervisionStrategy(SupervisionStrategy.restart()) .getOrSpawn(), (worker, error) -> new WorkerReady(msg, worker, error)); return SpringActorBehavior.same(); }) .onMessage(WorkerReady.class, (ctx, msg) -> { if (msg.error() != null) { ctx.getLog().error("Could not start worker {}", msg.assign().workerId(), msg.error()); } else { msg.worker().tell(new WorkerActor.DoTask(msg.assign().task())); } return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin @Component class DispatcherActor : SpringActor { sealed interface Command : FrameworkCommand data class Assign(val workerId: String, val task: String) : Command // The result of a child spawn, delivered back to this actor as a message. data class WorkerReady( val assign: Assign, val worker: SpringActorHandle?, val error: Throwable?, ) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { msg -> pipeToSelf( self.child() .withId(msg.workerId) .withSupervisionStrategy(SupervisionStrategy.restart()) .getOrSpawn(), ) { worker, error -> WorkerReady(msg, worker, error) } same() } onMessage { msg -> val worker = msg.worker if (msg.error != null || worker == null) { log.error("Could not start worker {}", msg.assign.workerId, msg.error) } else { worker.tell(WorkerActor.DoTask(msg.assign.task)) } same() } } } ``` `WorkerActor` is an ordinary actor (`@Component`, `SpringActor`). Children get Spring dependency injection like any other actor. You can also start children when the parent starts, in the [`withState`](behaviors.md#state-with-withstate) factory: call `spawn()` there and don't wait for the result. ### Child operations The child builder (`handle.child(ChildClass)`) has the same shape as the spawn builder: | Method | Notes | |---|---| | `withId(id)` or `withContext(ctx)` | Required | | `withSupervisionStrategy(strategy)` | How the parent handles the child's failures. Default: stop. | | `withTimeout(duration)` | Default 3 s | | `withDispatcher(DispatcherConfig)` | `DispatcherConfig.blocking()`, `.sameAsParent()`, `.fromConfig(name)`, `.defaultDispatcher()` | | `withMailbox(MailboxConfig)`, `withTags(TagsConfig)`, `withMdc(MdcConfig)` | As for top-level actors | | `spawn()` | Spawns the child. If a child with that class and id already runs, returns it and logs a deprecation warning: use `getOrSpawn()` for that. In 2.0 it fails, like a top-level `spawn()`. | | `getOrSpawn()` | Returns the running child, or spawns it (in one step, so concurrent calls get the same child) | | `spawnAndWait()` | Blocks until the child runs. Never call it inside the parent. | | `get()` | Deprecated: use `handle.child(ChildClass, id).get()`, which returns an `Optional` | | `exists()` | Whether the child runs | For lookups only, `handle.child(ChildClass, id)` returns a child reference whose `get()` completes with an `Optional`: === "Java" ```java CompletionStage>> worker = dispatcher.child(WorkerActor.class, "worker-1").get(); CompletionStage running = dispatcher.child(WorkerActor.class, "worker-1").withTimeout(Duration.ofSeconds(1)).exists(); ``` === "Kotlin" ```kotlin // In a suspend function val worker: SpringActorHandle? = dispatcher.child("worker-1").awaitGet() // null when it doesn't run val running: Boolean = dispatcher.child("worker-1").withTimeout(1.seconds).awaitExists() ``` These calls work from outside the parent too: any code with the parent's handle (here `dispatcher`) can spawn, find or check its children. Differences from top-level actors: - One rule for a taken id: `spawn()` is for a new actor and `getOrSpawn()` reuses a running one. A top-level `spawn()` fails when the id is taken. A child `spawn()` still returns the running child, with a deprecation warning, until 2.0. - A child can't be a cluster singleton. - Dispatchers are set with `withDispatcher(DispatcherConfig...)` instead of the `with...Dispatcher()` shortcuts. Inside the parent's handlers, `ctx.getChildren()` lists the running children and `ctx.stop(child)` stops one (see [Behaviors](behaviors.md#the-behavior-context)). ## Pitfalls - **State in bean fields.** All actors of a class share the bean. Keep per-actor state in `withState`. See [What not to do in an actor bean](#what-not-to-do-in-an-actor-bean). - **Blocking inside an actor.** Waiting on a future, `spawnAndWait()`, `Thread.sleep` or blocking I/O on the default dispatcher holds a shared thread. Use `pipeToSelf`, or the blocking dispatcher for blocking I/O. - **Child operations time out.** The parent's command type doesn't extend `FrameworkCommand`, or the parent is waiting inside a handler. - **Second `spawn()` with the same id fails.** Use `getOrSpawn()`, or check `exists` first. - **Actors that are never stopped.** One actor per request or per user, never stopped, grows memory without bound. ## Related - [Messaging](messaging.md): tell, ask, replies and message adapters - [Supervision](supervision.md): what happens when a handler throws - [Behaviors](behaviors.md): state, timers, watching, lifecycle signals - [Dispatchers](dispatchers.md): thread pools and mailboxes - [Sharded actors](../cluster/sharded-actors.md): one actor per id across a cluster - [Kotlin](../kotlin.md): the `actor-kotlin` helpers used in the Kotlin tabs --- # Messaging Actors talk only through messages. There are two ways to send one: - **tell**: send and move on. Nothing comes back. Use it for commands and events. - **ask**: send and get a `CompletionStage` that completes with the actor's reply. Use it when the caller needs an answer, for example to build an HTTP response. This page covers both, how replies work, what happens on timeouts and errors, how actors reply to each other without ask, and how to design messages. Defining and spawning actors is in [Actors](actors.md). ## Message rules - **One message at a time.** An actor handles its messages one after another, in the order they arrive in its mailbox. Messages from one sender to one actor arrive in the order they were sent. - **At most once.** A message is delivered once or not at all. Messages to an actor that has stopped are dropped (they go to "dead letters"). If a message must not be lost, send it with [reliable delivery](reliable-delivery.md), or store it first (see [Event sourcing](../data/event-sourcing.md)). - **Immutable messages.** The sender and the actor may run on different threads. Use records, `final` fields or Kotlin `val`s, and immutable collections (`List.copyOf`). - **Serializable in a cluster.** A message that can cross nodes must implement `JsonSerializable` or `CborSerializable` (package `io.github.seonwkim.actor.serialization`). In local mode messages are passed as objects and need neither. See [Cluster formation](../cluster/cluster-formation.md). The starter writes them with its own Jackson mapper, not the application's `ObjectMapper` (*new in the next release; 1.1.0 uses the application's*), so settings made for the REST API do not change what nodes exchange. To use the application's, set `spring.actor.serialization.application-object-mapper: true`, and treat its settings as part of the message format. ## Tell `tell` puts the message in the actor's mailbox and returns at once: === "Java" ```java actorSystem.getOrSpawn(GreeterActor.class, "greeter") .thenAccept(greeter -> greeter.tell(new GreeterActor.LogVisit("Kim"))); ``` === "Kotlin" ```kotlin // In a suspend function actorSystem.awaitGetOrSpawn("greeter") .tell(GreeterActor.LogVisit("Kim")) ``` `tell` never fails and never waits. The caller doesn't learn whether the message was handled. If it needs to know, use ask. ## Ask: request and reply A message that expects an answer extends `AskCommand`, where `R` is the answer's type. The handler answers with `msg.reply(value)`: === "Java" ```java public static class GetBalance extends AskCommand implements Command { public final String accountId; public GetBalance(String accountId) { this.accountId = accountId; } } // In create(): .onMessage(GetBalance.class, (state, msg) -> { msg.reply(state.balance()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin class GetBalance(val accountId: String) : AskCommand(), Command // In the behavior { } block, whose state object has balance(): onMessage { msg -> msg.reply(balance()) same() } ``` The caller sends it with `ask`, sets a timeout, and calls `execute()`: === "Java" ```java CompletionStage balance = account .ask(new AccountActor.GetBalance("acc-1")) .withTimeout(Duration.ofSeconds(2)) .execute(); ``` === "Kotlin" ```kotlin // In a suspend function: suspends until the reply arrives val balance: Long = account.awaitAsk(AccountActor.GetBalance("acc-1"), timeout = 2.seconds) ``` In a WebFlux controller, return `Mono.fromCompletionStage(balance)` (Java) or make the handler a `suspend fun` (Kotlin). How ask works: the starter creates a short-lived reply address and sends a shallow copy of the command that carries it (`getReplyTo()` on the copy the actor receives). The command you passed is not changed. `reply(value)` sends the value to that address, and the `CompletionStage` completes. ### Timeouts Every ask has a timeout. When no reply arrives in time, the stage fails with `java.util.concurrent.TimeoutException`. | Where the handle came from | Default ask timeout | |---|---| | `spawn`, `getOrSpawn`, `find`, `exists`, a child builder, `ctx.getSelf()` | 3 s | Set your own with `withTimeout(Duration)`. Pick a timeout that fits the caller (an HTTP request's budget), not the actor. To return a fallback value instead of failing, add `onTimeout`: === "Java" ```java CompletionStage balance = account .ask(new AccountActor.GetBalance("acc-1")) .withTimeout(Duration.ofSeconds(2)) .onTimeout(() -> -1L) .execute(); ``` === "Kotlin" ```kotlin // In a suspend function val balance: Long = account .ask(AccountActor.GetBalance("acc-1")) .withTimeout(2.seconds) .onTimeout { -1L } .await() ``` `onTimeout` only handles timeouts. Any other failure still fails the stage. When you block on the stage (`.toCompletableFuture().get()`), the `TimeoutException` arrives wrapped in an `ExecutionException`; inside `thenCompose`/`exceptionally` chains it can arrive wrapped in a `CompletionException`. Check `getCause()`. In Kotlin, `awaitAsk` and `await()` throw the `TimeoutException` itself. ### Errors in the handler If the handler throws, no reply is sent, and the actor is handled by its [supervision strategy](supervision.md) (stopped, by default). By default the asker only sees a timeout. Add `failFastOnError()` to fail the ask at once with the handler's exception instead: === "Java" ```java CompletionStage balance = account .ask(new AccountActor.GetBalance("acc-1")) .withTimeout(Duration.ofSeconds(2)) .failFastOnError() .execute(); // fails with the handler's exception as soon as it throws ``` === "Kotlin" ```kotlin // In a suspend function: throws the handler's exception as soon as it throws val balance: Long = account.awaitAsk(AccountActor.GetBalance("acc-1"), timeout = 2.seconds, failFast = true) ``` It works for `SpringActorBehavior` handlers and for the command handlers of [event-sourced actors](../data/event-sourcing.md), on a local actor or a sharded entity. When the actor runs on another node, the exception's class is not sent: the ask fails with an exception whose message names the original class and message. The supervision strategy still applies. `failFastOnError()` reports bugs and unexpected failures quickly. For an error the caller is expected to handle, make it part of the reply: === "Java" ```java public sealed interface WithdrawResult { record Done(long balance) implements WithdrawResult {} record Rejected(String reason) implements WithdrawResult {} } public static class Withdraw extends AskCommand implements Command { public final long amount; public Withdraw(long amount) { this.amount = amount; } } // In create(): .onMessage(Withdraw.class, (state, msg) -> { if (msg.amount > state.balance()) { msg.reply(new WithdrawResult.Rejected("insufficient funds")); } else { msg.reply(new WithdrawResult.Done(state.withdraw(msg.amount))); } return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin sealed interface WithdrawResult { data class Done(val balance: Long) : WithdrawResult data class Rejected(val reason: String) : WithdrawResult } class Withdraw(val amount: Long) : AskCommand(), Command // In the behavior { } block: onMessage { msg -> if (msg.amount > balance()) { msg.reply(WithdrawResult.Rejected("insufficient funds")) } else { msg.reply(WithdrawResult.Done(withdraw(msg.amount))) } same() } ``` ### Replying later `reply` is an ordinary send, so the actor doesn't have to answer inside the handler. It can keep the command and answer when it knows the answer, for example when a human approves something or another actor answers. The `ApprovalActor` of the [agent example](../../examples/agent.md) keeps pending requests in a map and replies when a decision arrives (simplified): === "Java" ```java SpringActorBehavior onRequest(RequestApproval request) { pending.put(request.id(), request); // keep the command return SpringActorBehavior.same(); } SpringActorBehavior onDecide(Decide decide) { RequestApproval request = pending.remove(decide.requestId()); if (request != null) { request.reply(new ApprovalDecision(decide.approved())); // answer the original asker } return SpringActorBehavior.same(); } ``` === "Kotlin" ```kotlin fun onRequest(request: RequestApproval): SpringActorBehavior { pending[request.id] = request // keep the command return SpringActorBehavior.same() } fun onDecide(decide: Decide): SpringActorBehavior { pending.remove(decide.requestId) ?.reply(ApprovalDecision(decide.approved)) // answer the original asker return SpringActorBehavior.same() } ``` The asker's timeout still applies: a reply after the timeout is dropped. ### Ask rules - **A command object can be asked again.** `ask` sends a copy and leaves your object unchanged, so one instance can be asked twice or from several threads at once. (Before 1.1.0, `ask` stored the reply address in the object itself.) - **`reply` needs an ask.** Calling `reply` on a command that was sent with `tell` throws `IllegalStateException`. If a command can arrive both ways, check `msg.hasReplyTo()` first. - **Reply once.** Only the first reply reaches the asker. ## Asking from inside an actor Inside a handler, never wait for a reply (`join()`, `get()`): the actor would hold its thread and handle nothing else until the reply comes. Send the ask and turn the result into a message to yourself with `ctx.pipeToSelf`. The `AgentBrain` of the [agent example](../../examples/agent.md) asks the approval actor this way (simplified): === "Java" ```java // A message this actor sends itself when the ask completes. record ApprovalResolved(boolean approved, String note) implements Command {} private SpringActorBehavior askForApproval(PendingApproval request) { ctx.pipeToSelf( approvals.ask(new ApprovalActor.RequestApproval(request)) .withTimeout(Duration.ofMinutes(5)) .execute(), (decision, error) -> error != null ? new ApprovalResolved(false, "no answer: " + error.getMessage()) : new ApprovalResolved(decision.approved(), "answered")); return SpringActorBehavior.same(); } ``` === "Kotlin" ```kotlin // A message this actor sends itself when the ask completes. data class ApprovalResolved(val approved: Boolean, val note: String) : Command private fun askForApproval(request: PendingApproval): SpringActorBehavior { ctx.pipeToSelf( approvals.ask(ApprovalActor.RequestApproval(request)) .withTimeout(5.minutes) .execute(), ) { decision, error -> if (error != null || decision == null) ApprovalResolved(false, "no answer: ${error?.message}") else ApprovalResolved(decision.approved, "answered") } return SpringActorBehavior.same() } ``` For the common case, asking an actor and turning the reply or the timeout into a message, `ctx.askToSelf` (*new in the next release*) does the same in one call, with the same timeout and error behavior as `ask(...).withTimeout(...)`: ```java ctx.askToSelf(approvals, new ApprovalActor.RequestApproval(request), Duration.ofMinutes(5), (decision, error) -> error != null ? new ApprovalResolved(false, "no answer: " + error.getMessage()) : new ApprovalResolved(decision.approved(), "answered")); ``` When no reply comes in time, `error` is a `TimeoutException`. The target can also be a sharded entity's handle (`actorSystem.sharded(RoomActor.class).withId(roomId).get()`), wherever the entity runs. The function you pass to `pipeToSelf` gets the value (or `null`) and the error (or `null`). It runs when the stage completes, so it must not touch the actor's state; it only builds the message. The actor changes its state when it handles that message. The same pattern works for any `CompletionStage`: an HTTP client call, a repository call on another thread, an LLM call. ## Replying to an actor without ask Ask creates a temporary reply address. Between actors, you can pass a real address instead: put a `SpringActorRef` in the message, and the receiver tells its answer to that ref. `ctx.getSelf()` is the current actor's ref. When the receiver answers with a type that is not one of your commands, use a **message adapter**: `ctx.messageAdapter(Type.class, fn)` returns a `SpringActorRef` that turns each value it receives into one of your commands. The agent example asks a rate limiter for permits this way: === "Java" ```java // The rate limiter answers with a RateLimiterActor.Permit. // PermitGranted is one of this actor's commands: record PermitGranted(Permit permit) implements Command {} private final SpringActorRef permits; AgentBrain(SpringBehaviorContext ctx) { this.permits = ctx.messageAdapter(RateLimiterActor.Permit.class, PermitGranted::new); } private void requestPermit() { rateLimiter.tell(RateLimiterActor.Acquire.replyingTo(permits)); } ``` === "Kotlin" ```kotlin // The rate limiter answers with a RateLimiterActor.Permit. // PermitGranted is one of this actor's commands: data class PermitGranted(val permit: Permit) : Command private val permits: SpringActorRef = ctx.messageAdapter(RateLimiterActor.Permit::class.java) { PermitGranted(it) } private fun requestPermit() { rateLimiter.tell(RateLimiterActor.Acquire.replyingTo(permits)) } ``` Create adapters once, when the actor starts (in the `withState` factory), not per message. Refs in messages work across nodes: a `SpringActorRef` field in a `JsonSerializable` message is serialized by the starter. ## Calling actors from Spring code Typical shapes, from a service or controller: === "Java" ```java // Fire and forget public void visit(String name) { actorSystem.getOrSpawn(GreeterActor.class, "greeter") .thenAccept(greeter -> greeter.tell(new GreeterActor.LogVisit(name))); } // Request and reply, as a Mono for WebFlux public Mono greet(String name) { return Mono.fromCompletionStage(actorSystem.getOrSpawn(GreeterActor.class, "greeter") .thenCompose(greeter -> greeter.ask(new GreeterActor.Greet(name)) .withTimeout(Duration.ofSeconds(3)) .execute())); } ``` === "Kotlin" ```kotlin // Fire and forget suspend fun visit(name: String) { actorSystem.awaitGetOrSpawn("greeter").tell(GreeterActor.LogVisit(name)) } // Request and reply: a suspend function, usable from a suspend WebFlux handler suspend fun greet(name: String): String = actorSystem.awaitGetOrSpawn("greeter") .awaitAsk(GreeterActor.Greet(name), timeout = 3.seconds) ``` For a stream of values instead of one reply, see [Reactor streams](../streaming/reactor-streams.md). For one message to many actors, see [Pub/sub topics](pub-sub-topics.md) and [Routers](routers.md). ## Pitfalls - **Ask timeouts that hide errors.** A handler that throws sends no reply. Put expected errors in the reply type, and use `failFastOnError()` to see unexpected ones without waiting for the timeout. - **Blocking on ask inside an actor.** Use `pipeToSelf`. - **Mutable messages.** A message changed after sending can be seen half-changed by the actor. - **Forgetting serialization in cluster mode.** A message without `JsonSerializable` or `CborSerializable` fails when it crosses nodes. ## Related - [Actors](actors.md): defining, spawning and finding actors - [Behaviors](behaviors.md): `pipeToSelf`, message adapters and the rest of the behavior context - [Supervision](supervision.md): what happens when a handler throws - [Pub/sub topics](pub-sub-topics.md) and [Receptionist](receptionist.md): reaching actors without their id - [Testing](../testing.md): testing asks and replies --- # Reliable Delivery `tell` is **at most once**: a message that is lost, or that reaches an actor whose handler fails, is gone. Reliable delivery makes a send **at least once, handled once per key**: the sender retries the message until the receiving actor acknowledges it, and the receiver remembers the idempotency keys it handled, so a retry doesn't run the handler again. It works for local actors and sharded entities. Use it for commands that must not be dropped while the application runs: an order to an order actor, a payment step to a sharded entity. Don't use it when: - a lost message is fine (a UI refresh, a cache warm-up): plain `tell` is cheaper; - the caller needs an answer: use [`ask`](messaging.md); - the message must survive a restart of the **sending** node, or the receiver's deduplication must survive a restart of the **receiving** actor: see [Limits](#limits). Store the work first, for example with [event sourcing](../data/event-sourcing.md). ## Receiving: wrap the behavior The receiving actor wraps the behavior its `create` returns with `ReliableDelivery.consumer(...)`. Its handlers and its supervision stay as they are. === "Java" ```java import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.SupervisionStrategy; import io.github.seonwkim.actor.delivery.ReliableDelivery; import org.springframework.stereotype.Component; @Component public class OrderActor implements SpringActor { public interface Command {} public record PlaceOrder(String orderId) implements Command {} private final OrderRepository orders; public OrderActor(OrderRepository orders) { this.orders = orders; } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return ReliableDelivery.consumer(SpringActorBehavior.builder(Command.class, actorContext) .withSupervisionStrategy(SupervisionStrategy.restart()) .onMessage(PlaceOrder.class, (ctx, msg) -> { orders.save(msg.orderId()); // throws: no ack, the sender retries return SpringActorBehavior.same(); }) .build()); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.SupervisionStrategy import io.github.seonwkim.actor.delivery.ReliableDelivery import io.github.seonwkim.actor.kotlin.actorBehavior import org.springframework.stereotype.Component @Component class OrderActor(private val orders: OrderRepository) : SpringActor { sealed interface Command data class PlaceOrder(val orderId: String) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = ReliableDelivery.consumer( actorBehavior(actorContext) .withSupervisionStrategy(SupervisionStrategy.restart()) .onMessage(PlaceOrder::class.java) { _, msg -> orders.save(msg.orderId) // throws: no ack, the sender retries SpringActorBehavior.same() } .build(), ) } ``` - **Ack:** a reliable message is acknowledged when one of the actor's handlers returned. If the handler threw, or no handler matched the message, there is no ack and the sender retries. - **Deduplication:** the actor remembers the key of every message it handled, with a fingerprint of its payload (its `hashCode`). A message whose key it remembers is acknowledged again without calling the handler. - **Payload conflict:** the same key with a different payload is not a duplicate. The handler doesn't run, and the send fails at once with `PAYLOAD_CONFLICT` (see [Outcomes](#outcomes)). Give reliable messages value equality (records, data classes): a class that keeps `Object`'s `hashCode` has no fingerprint, so its payloads aren't compared. - **How long:** keys are remembered for `spring.actor.delivery.idempotency-ttl` (default 10 minutes). One actor can override it: `ReliableDelivery.consumer(behavior, Duration.ofHours(1))`. - **How many:** at most `spring.actor.delivery.max-remembered-keys` keys per actor (default 10,000). Past that, the oldest keys are forgotten first, so a burst can't grow the memory without limit. - **Plain messages:** `tell` and `ask` to the same actor keep working, without deduplication. The behavior must come from `SpringActorBehavior.builder(...)`. Sharded entities wrap their behavior the same way, in their `create(SpringShardedActorContext)`. ### Stale generation: not the owner yet, or anymore During a deployment a message can reach an actor that doesn't own its state: a new instance still loading it, or an old one that a newer generation replaced. The handler says so by throwing `StaleGenerationException`. The message is not acknowledged and its key is not remembered, the actor is not restarted, and the sender retries the same key and payload, which reaches the active owner once it is ready. === "Java" ```java .onMessage(PlaceOrder.class, (ctx, msg) -> { if (!ownership.isActive(msg.orderId())) { throw new StaleGenerationException("order " + msg.orderId() + " is not active here"); } orders.save(msg.orderId()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin .onMessage(PlaceOrder::class.java) { _, msg -> if (!ownership.isActive(msg.orderId)) { throw StaleGenerationException("order ${msg.orderId} is not active here") } orders.save(msg.orderId) SpringActorBehavior.same() } ``` `ownership` stands for your own check, such as a lease or an epoch in your database. For blue-green deployments, `DeploymentGeneration.check(epoch)` is that check: it throws `StaleGenerationException` for work stamped by a generation that is no longer active ([The active generation](../operations/deployments.md#the-active-generation)). For a plain `tell`, the exception is an ordinary failure for the actor's supervision. ## Sending to an actor Inject the `SpringReliableDelivery` bean and build a sender for an actor handle. `send` returns a `CompletionStage` that completes when the actor acknowledged the message. === "Java" ```java @Service public class OrderService { private final ReliableSender orders; public OrderService(SpringActorSystem actorSystem, SpringReliableDelivery reliableDelivery) { SpringActorHandle orderActor = actorSystem.actor(OrderActor.class).withId("orders").spawnAndWait(); this.orders = reliableDelivery.to(orderActor).build(); } public CompletionStage placeOrder(String orderId) { // The order id is the key: placing the same order twice runs the handler once. return orders.send(new OrderActor.PlaceOrder(orderId), orderId); } } ``` === "Kotlin" ```kotlin @Service class OrderService(actorSystem: SpringActorSystem, reliableDelivery: SpringReliableDelivery) { private val orders: ReliableSender = reliableDelivery .to(actorSystem.actor(OrderActor::class.java).withId("orders").spawnAndWait()) .build() // Suspends until the actor acknowledged the order (kotlinx.coroutines.future.await). // The order id is the key: placing the same order twice runs the handler once. suspend fun placeOrder(orderId: String) { orders.send(OrderActor.PlaceOrder(orderId), orderId).await() } } ``` **Idempotency keys:** - `send(message)`: the starter makes a new key for this send. Its retries run the handler once, but sending the same message again is a new message. - `send(message, key)`: you pass a business id, such as an order id or a payment id. Any send with that key runs the handler once while the receiver remembers it: re-sends from another sender, from another node, or after the sender's node restarted. A sender holds no resources: build one per receiver and keep it, or build one per call. ## Retries A send is retried with exponential backoff and full jitter until it is acknowledged. Every attempt carries the same idempotency key and the same payload. The backoff doubles from `initialBackoff` up to `maxBackoff`, and the pause before the next attempt is random, from zero to the backoff, so senders that failed together don't retry together. | `RetryPolicy` | Property | Default | | |---|---|---|---| | `maxAttempts` | `spring.actor.delivery.retry.max-attempts` | 5 | attempts in total, including the first | | `timeout` | `spring.actor.delivery.retry.timeout` | 30s | from the first attempt; no attempt starts after it | | `attemptTimeout` | `spring.actor.delivery.retry.attempt-timeout` | 3s | how long one attempt waits for the ack | | `initialBackoff` / `maxBackoff` | `spring.actor.delivery.retry.initial-backoff` / `.max-backoff` | 200ms / 5s | the backoff doubles up to the maximum | The properties set the policy of every sender. One sender can set its own: === "Java" ```java ReliableSender orders = reliableDelivery.to(orderActor) .withRetry(RetryPolicy.defaults() .withMaxAttempts(10) .withTimeout(Duration.ofMinutes(1)) .withBackoff(Duration.ofMillis(100), Duration.ofSeconds(10))) .build(); ``` === "Kotlin" ```kotlin val orders: ReliableSender = reliableDelivery.to(orderActor) .withRetry( RetryPolicy.defaults() .withMaxAttempts(10) .withTimeout(Duration.ofMinutes(1)) .withBackoff(Duration.ofMillis(100), Duration.ofSeconds(10)), ) .build() ``` ## Outcomes A send that fails completes its stage with `ReliableDeliveryException`. Its `reason()` says why, and `reason().isRetryable()` whether sending again can succeed: | Reason | Retryable | When | Suggested HTTP response | |---|---|---|---| | `STALE_GENERATION` | yes | the handler threw `StaleGenerationException` on every attempt | 409 Conflict with `Retry-After` | | `TIMEOUT` | yes | the last attempt waited its `attemptTimeout` without an ack | 504 Gateway Timeout | | `UNAVAILABLE` | yes | the last attempt failed at once, for example because the actor is stopped | 503 Service Unavailable | | `PAYLOAD_CONFLICT` | no | the receiver handled the key with a different payload; not retried | 409 Conflict or 422 Unprocessable Entity | A retryable failure means the retry policy ran out. The message may still have been handled (only the acks may have been lost), so a client can send it again with the same key and payload: within the receiver's TTL it runs once. A payload conflict fails the same way every time: the client must not retry it, and should use a new key for a new payload. An application that sends from an HTTP handler can map the reasons once: === "Java" ```java @RestControllerAdvice public class ReliableDeliveryErrors { @ExceptionHandler(ReliableDeliveryException.class) public ResponseEntity deliveryFailed(ReliableDeliveryException e) { return switch (e.reason()) { case STALE_GENERATION -> ResponseEntity.status(HttpStatus.CONFLICT) .header(HttpHeaders.RETRY_AFTER, "1") .body("Not ready yet, retry with the same key"); case TIMEOUT -> ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body("Timed out, retry"); case UNAVAILABLE -> ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("Unavailable, retry"); case PAYLOAD_CONFLICT -> ResponseEntity.status(HttpStatus.CONFLICT) .body("Key " + e.idempotencyKey() + " was used for a different request"); }; } } ``` === "Kotlin" ```kotlin @RestControllerAdvice class ReliableDeliveryErrors { @ExceptionHandler(ReliableDeliveryException::class) fun deliveryFailed(e: ReliableDeliveryException): ResponseEntity = when (e.reason()) { ReliableDeliveryException.Reason.STALE_GENERATION -> ResponseEntity.status(HttpStatus.CONFLICT) .header(HttpHeaders.RETRY_AFTER, "1") .body("Not ready yet, retry with the same key") ReliableDeliveryException.Reason.TIMEOUT -> ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT).body("Timed out, retry") ReliableDeliveryException.Reason.UNAVAILABLE -> ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("Unavailable, retry") ReliableDeliveryException.Reason.PAYLOAD_CONFLICT -> ResponseEntity.status(HttpStatus.CONFLICT) .body("Key ${e.idempotencyKey()} was used for a different request") } } ``` The exception reaches the handler when the controller returns the send's stage or waits for it, as `await()` does in Kotlin. ## Sending to sharded entities In cluster mode, `toSharded(...)` builds one sender for all entities of a sharded actor class. `send` takes the entity id. === "Java" ```java ShardedReliableSender payments = reliableDelivery.toSharded(OrderEntity.class).build(); payments.send("order-42", new OrderEntity.Pay(1_000), "payment-77") .thenRun(() -> log.info("order-42 acknowledged payment-77")); ``` === "Kotlin" ```kotlin val payments: ShardedReliableSender = reliableDelivery.toSharded(OrderEntity::class.java).build() // In a suspend function payments.send("order-42", OrderEntity.Pay(1_000), "payment-77").await() ``` A retry reaches the entity wherever it runs; if the entity stopped or moved, the retry starts it again. Messages must implement `JsonSerializable` or `CborSerializable`, as for any message that crosses nodes. ## What it costs - **Per message:** one ask and one ack, and one more of each per retry. No extra actors stay alive. - **On the receiver:** a key and an expiry for each handled message, up to the TTL and the key limit (10,000 keys of about 100 bytes each is about 1 MB per actor). - **While a receiver is down:** each pending send retries until it gives up; with the defaults, at most 5 asks over about 30 seconds. ## Limits - **Dedupe memory is in the actor.** So is the payload fingerprint: a conflict is found only while the key is remembered. The memory is lost when the receiving actor restarts by its spawn supervision, stops, or (sharded) is passivated or moves to another node. After that, a retry or a re-send with the same key runs the handler again. Make handlers safe to run twice when that matters. A durable key store is a planned follow-up. - **Stopped local actors don't come back.** Retries to a local actor that stopped fail when the retry policy runs out. A sharded entity starts again on the next retry. - **No ordering.** Retries can overtake later messages: send one at a time (wait for the stage) when the order matters. - **Not durable on the sender.** A send in progress is lost when the sending node stops; the caller sees no result. Re-send with the same key when it restarts. --- # Supervision Supervision decides what happens to an actor when one of its handlers throws an exception. Instead of try/catch around every handler, you choose a strategy once: restart the actor with fresh state, keep it running and skip the message, or stop it. A failure then stays inside that one actor, and the rest of the application keeps working. Use supervision for failures you can't handle where they happen: a bug, a corrupted in-memory state, a dependency that throws. For expected outcomes (a rejected payment, an invalid input), reply with a result instead (see [Errors in the handler](messaging.md#errors-in-the-handler)). ## Strategies `SupervisionStrategy` has three strategies: | Strategy | What happens after a failure | Use it when | |---|---|---| | `SupervisionStrategy.stop()` | The actor stops. **This is the default** when no strategy is set. | A failed actor should not keep going; a caller or parent will create a new one if needed | | `SupervisionStrategy.restart()` | The actor starts again with fresh state, under the same id and ref. No limit. | The state can be rebuilt (from a database, a snapshot, or from nothing) | | `SupervisionStrategy.restart().withLimit(n, window)` | Restarts, but stops the actor once it has restarted `n` times within `window` | Most restarts in production: it stops an actor that fails on every message | | `SupervisionStrategy.resume()` | The actor keeps its state and goes on with the next message. The failed message is dropped. | The failure doesn't damage the state, and losing one message is fine | !!! note "Default: stop" With no strategy, a failing actor stops. Earlier versions of these docs said the default was restart; it is stop. The message that failed is never retried, whatever the strategy. If the sender asked, it gets no reply and sees a timeout. ## Where to set the strategy There are four places. Set it in one of them per actor. === "Java" ```java // 1. When spawning a top-level actor actorSystem.actor(OrderActor.class) .withId("order-42") .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, Duration.ofMinutes(1))) .spawn(); // 2. In the actor's own behavior: applies however the actor is spawned @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, Duration.ofMinutes(1))) .withState(ctx -> new OrderState(ctx)) .onMessage(Pay.class, OrderState::onPay) .build(); } // 3. When a parent spawns a child ctx.getSelf().child(WorkerActor.class) .withId("worker-1") .withSupervisionStrategy(SupervisionStrategy.resume()) .spawn(); // 4. For the workers of a router SpringRouterBehavior.builder(Command.class, actorContext) .withRoutingStrategy(RoutingStrategy.roundRobin()) .withWorkerActors(WorkerActor.class) .withSupervisionStrategy(SupervisionStrategy.restart()) .build(); ``` === "Kotlin" ```kotlin // 1. When spawning a top-level actor (in a suspend function) actorSystem.actor() .withId("order-42") .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, 1.minutes)) .awaitSpawn() // 2. In the actor's own behavior: applies however the actor is spawned override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext, state = { ctx -> OrderState(ctx) }) { withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes)) onMessage { msg -> onPay(msg) } } // 3. When a parent spawns a child ctx.self.child() .withId("worker-1") .withSupervisionStrategy(SupervisionStrategy.resume()) .spawn() // 4. For the workers of a router SpringRouterBehavior.builder(Command::class.java, actorContext) .withRoutingStrategy(RoutingStrategy.roundRobin()) .withWorkerActors(WorkerActor::class.java) .withSupervisionStrategy(SupervisionStrategy.restart()) .build() ``` Which one to pick: - Put it **in the behavior** (2) when the strategy belongs to the actor itself, for example "this actor reloads its state on restart, so restarting is always safe". Every spawn then gets it. - Put it **at the spawn site** (1, 3) when the caller decides, for example a parent that treats some children as disposable. - Sharded actors set it in their behavior (2); see [Sharded actors](../cluster/sharded-actors.md). ## What a restart keeps and what it loses A restart builds the actor's behavior again from its `withState` factory. `create` is not called again. | Kept | Lost | |---|---| | The actor's id, path and ref: handles held by others keep working | The state object: the `withState` factory runs again and builds a new one | | Messages already waiting in the mailbox | The message that failed | | The actor's dispatcher, mailbox settings, tags and MDC | Timers: they are cancelled. Timers started in the `withState` factory start again because it runs again. | | The Spring bean and its injected dependencies | Child actors: Pekko stops them when the parent restarts | So anything an actor must not lose on restart has to live outside the state object: in a database, a snapshot, or an [event-sourced journal](../data/event-sourcing.md). The `AgentBrain` of the [agent example](../../examples/agent.md) restarts up to 10 times a minute and reloads its conversation from the last snapshot in its constructor, which the `withState` factory calls on every start: === "Java" ```java return builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, Duration.ofMinutes(1))) .withState(ctx -> new AgentBrain(ctx, agentId, dependencies)) // reloads the snapshot .onMessage(AgentActor.Chat.class, AgentBrain::onChat) .build(); ``` === "Kotlin" ```kotlin builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes)) .withState { ctx -> AgentBrain(ctx, agentId, dependencies) } // reloads the snapshot .onMessage(AgentActor.Chat::class.java) { brain, chat -> brain.onChat(chat) } .build() ``` ## Reacting to restarts and stops Two signals tell an actor about its own lifecycle. Register them with `onSignal`: - `PreRestart` arrives just before a restart. Release what the old state holds (open files, subscriptions) or log what is lost. - `PostStop` arrives after the actor stopped, whether a handler returned `stopped()`, someone called `stop()`, or supervision stopped it. === "Java" ```java return SpringActorBehavior.builder(Command.class, actorContext) .withSupervisionStrategy(SupervisionStrategy.restart()) .withState(ctx -> new WorkerState(ctx)) .onMessage(DoTask.class, WorkerState::onDoTask) .onSignal(PreRestart.class, (state, signal) -> { state.ctx().getLog().warn("Restarting; {} completed tasks are lost", state.completed()); return SpringActorBehavior.same(); }) .onSignal(PostStop.class, (state, signal) -> { state.ctx().getLog().info("Stopped after {} tasks", state.completed()); return SpringActorBehavior.same(); }) .build(); ``` === "Kotlin" ```kotlin behavior(actorContext, state = { ctx -> WorkerState(ctx) }) { withSupervisionStrategy(SupervisionStrategy.restart()) onMessage { msg -> onDoTask(msg) } onSignal { ctx.log.warn("Restarting; {} completed tasks are lost", completed) same() } onSignal { ctx.log.info("Stopped after {} tasks", completed) same() } } ``` Keep signal handlers short and don't throw from them. More on signals in [Behaviors](behaviors.md#lifecycle-signals). ## Supervising children A parent chooses a strategy for each child when it spawns it (place 3 above). A child's failure does not fail the parent: with `stop`, the child just stops. To find out, the parent [watches](behaviors.md#watching-other-actors) the child and handles the `ActorTerminated` signal, for example to spawn a replacement or to tell a caller: === "Java" ```java .onMessage(WorkerReady.class, (ctx, msg) -> { ctx.watch(msg.worker()); // ActorTerminated arrives when the worker stops return SpringActorBehavior.same(); }) .onSignal(ActorTerminated.class, (ctx, signal) -> { ctx.getLog().warn("Worker {} stopped", signal.ref().path()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin onMessage { msg -> watch(msg.worker) // ActorTerminated arrives when the worker stops same() } onSignal { signal -> log.warn("Worker {} stopped", signal.ref.path()) same() } ``` Common choices by role: | Child role | Strategy | |---|---| | Stateless worker | `restart()` | | Worker in production that might fail on every message | `restart().withLimit(3, Duration.ofMinutes(1))` | | Validator or one-shot task that should fail fast | `stop()` | | Logger or metrics forwarder where one lost message is fine | `resume()` | ## Pitfalls - **Relying on the default.** With no strategy, the first exception stops the actor, and later messages to it are lost. Set a strategy on every long-lived actor. - **Unlimited restarts.** `restart()` without a limit restarts an actor that fails on every message forever. Prefer `withLimit`. - **State that must survive.** A restart throws the state object away. Persist what matters. - **`resume` on damaged state.** If the exception left the state half-updated, `resume` keeps the half-updated state. - **Errors meant for the caller.** The asker of a failed message only sees a timeout. Reply with an error result for expected failures. ## Related - [Actors](actors.md): spawning actors and children - [Behaviors](behaviors.md): `withState`, signals and watching - [Messaging](messaging.md): replies, timeouts and errors - [Event sourcing](../data/event-sourcing.md): state that survives restarts and node failures --- # Behaviors An actor's behavior says how it handles each message. You build it in `create` with `SpringActorBehavior.builder(...)` (or `behavior(...) { }` in Kotlin, see the [Kotlin guide](../kotlin.md#defining-an-actor)). This page covers what you can do inside a behavior: keep state, choose the next behavior, react to lifecycle signals, schedule messages with timers, watch other actors, and turn futures into messages. For defining and spawning actors see [Actors](actors.md); for sending messages see [Messaging](messaging.md). ## The builder | Builder method | What it does | |---|---| | `withState(ctx -> state)` | Creates the actor's state object when the actor starts (and again on each restart). Handlers then receive the state instead of the context. | | `onMessage(Type.class, (state, msg) -> next)` | Handles messages of `Type`. Handlers are tried in the order they were added; the first whose type matches runs. | | `onSignal(Signal.class, (state, signal) -> next)` | Handles a lifecycle signal: `PreRestart`, `PostStop` or `ActorTerminated`. | | `withSupervisionStrategy(strategy)` | What happens when a handler throws. See [Supervision](supervision.md). | | `withMdc(msg -> map)` | Log context computed per message. See [Logging](logging.md). | | `build()` | Returns the behavior. | A message with no matching handler is *unhandled*: it is dropped (and published as unhandled), and the actor keeps going. ## State with withState Without `withState`, every handler receives the behavior context (`ctx`). With it, the handlers receive your own state object, which you usually give a reference to the context. Put the actor's fields and its handler methods in that object: === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.SpringBehaviorContext; import org.springframework.stereotype.Component; @Component public class CounterActor implements SpringActor { public interface Command {} public record Add(long amount) implements Command {} public static class Get extends AskCommand implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> new Counter(ctx, actorContext.actorId())) .onMessage(Add.class, Counter::onAdd) .onMessage(Get.class, Counter::onGet) .build(); } private static class Counter { private final SpringBehaviorContext ctx; private final String id; private long value; // only this actor's thread touches it Counter(SpringBehaviorContext ctx, String id) { this.ctx = ctx; this.id = id; ctx.getLog().info("Counter {} started", id); } SpringActorBehavior onAdd(Add msg) { value += msg.amount(); return SpringActorBehavior.same(); } SpringActorBehavior onGet(Get msg) { msg.reply(value); return SpringActorBehavior.same(); } } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.SpringBehaviorContext import io.github.seonwkim.actor.kotlin.behavior import org.springframework.stereotype.Component @Component class CounterActor : SpringActor { sealed interface Command data class Add(val amount: Long) : Command class Get : AskCommand(), Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext, state = { ctx -> Counter(ctx, actorContext.actorId()) }) { // The handlers run with the Counter as `this`. onMessage { msg -> onAdd(msg) } onMessage { msg -> onGet(msg) } } private class Counter(private val ctx: SpringBehaviorContext, private val id: String) { private var value = 0L // only this actor's thread touches it init { ctx.log.info("Counter {} started", id) } fun onAdd(msg: Add): SpringActorBehavior { value += msg.amount return SpringActorBehavior.same() } fun onGet(msg: Get): SpringActorBehavior { msg.reply(value) return SpringActorBehavior.same() } } } ``` The state object belongs to one actor and is only touched while that actor handles a message, so plain fields need no `volatile` or locks. Don't hand the object (or its mutable collections) to other threads. The `withState` factory runs inside the actor when it starts, before the first message. It is the place to load initial data, start timers, register with the [receptionist](receptionist.md) or spawn children. On a [restart](supervision.md#what-a-restart-keeps-and-what-it-loses) it runs again and builds a fresh object. ## What a handler returns Each handler returns the behavior for the next message: | Return | Meaning | |---|---| | `SpringActorBehavior.same()` | Keep handling messages the same way. The usual return. | | `SpringActorBehavior.stopped()` | Stop the actor after this message. Its `PostStop` handler runs. | | `SpringActorBehavior.unhandled()` | This handler didn't handle the message after all. The message is published as unhandled; the behavior stays. | | A new behavior from `SpringActorBehavior.builder(...).build()` | Handle the next messages with this behavior instead. | Returning a new behavior lets an actor change how it reacts, for example a door that ignores `Open` while locked. Each built behavior has its own handlers and its own state: === "Java" ```java @Component public class DoorActor implements SpringActor { public interface Command {} public record Lock() implements Command {} public record Unlock() implements Command {} public static class IsLocked extends AskCommand implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return unlocked(actorContext); } private static SpringActorBehavior unlocked(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(Lock.class, (ctx, msg) -> locked(actorContext)) .onMessage(IsLocked.class, (ctx, msg) -> { msg.reply(false); return SpringActorBehavior.same(); }) .build(); } private static SpringActorBehavior locked(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(Unlock.class, (ctx, msg) -> unlocked(actorContext)) .onMessage(IsLocked.class, (ctx, msg) -> { msg.reply(true); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin @Component class DoorActor : SpringActor { sealed interface Command class Lock : Command class Unlock : Command class IsLocked : AskCommand(), Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = unlocked(actorContext) private fun unlocked(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { locked(actorContext) } onMessage { msg -> msg.reply(false) same() } } private fun locked(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { unlocked(actorContext) } onMessage { msg -> msg.reply(true) same() } } } ``` In the locked behavior, `Lock` has no handler, so a second `Lock` is unhandled and dropped. For many actors a status field in one state object is simpler; switch behaviors when the states really accept different messages. ## Lifecycle signals Signals are events about the actor's life, not messages from others. Handle them with `onSignal`: | Signal | When it arrives | Typical use | |---|---|---| | `PreRestart` | Just before a supervised restart | Release resources the old state holds; log what is lost | | `PostStop` | After the actor stopped (for any reason) | Close resources, deregister, log final state | | `ActorTerminated` | An actor this one [watches](#watching-other-actors) has stopped; `signal.ref()` is that actor | Replace a worker, clean up a session | An example with `PreRestart` and `PostStop` is in [Supervision](supervision.md#reacting-to-restarts-and-stops). A signal handler returns the next behavior like a message handler; return `same()`. ## Timers A timer sends a message to the actor itself, once or repeatedly. Use timers for timeouts, retries, polling and periodic work. Each timer has a key (any object); starting a timer with a key that is already active replaces it. | Method on the context | What it does | |---|---| | `startSingleTimer(key, message, delay)` | Sends `message` once after `delay` | | `startTimerAtFixedRate(key, message, interval)` | Sends `message` every `interval` until cancelled | | `cancelTimer(key)` | Cancels the timer; a message it already sent is not delivered | === "Java" ```java @Component public class SessionActor implements SpringActor { public interface Command {} public record Touch() implements Command {} private enum IdleTimeout implements Command { INSTANCE } private enum Flush implements Command { INSTANCE } private static final Duration IDLE = Duration.ofMinutes(30); @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> { ctx.startTimerAtFixedRate("flush", Flush.INSTANCE, Duration.ofSeconds(10)); ctx.startSingleTimer("idle", IdleTimeout.INSTANCE, IDLE); return ctx; }) .onMessage(Touch.class, (ctx, msg) -> { ctx.startSingleTimer("idle", IdleTimeout.INSTANCE, IDLE); // restart the idle clock return SpringActorBehavior.same(); }) .onMessage(Flush.class, (ctx, msg) -> { ctx.getLog().debug("Flushing"); return SpringActorBehavior.same(); }) .onMessage(IdleTimeout.class, (ctx, msg) -> SpringActorBehavior.stopped()) .build(); } } ``` === "Kotlin" ```kotlin @Component class SessionActor : SpringActor { sealed interface Command class Touch : Command private data object IdleTimeout : Command private data object Flush : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext, state = { ctx -> ctx.startTimerAtFixedRate("flush", Flush, 10.seconds) ctx.startSingleTimer("idle", IdleTimeout, IDLE) ctx }) { onMessage { startSingleTimer("idle", IdleTimeout, IDLE) // restart the idle clock same() } onMessage { log.debug("Flushing") same() } onMessage { stopped() } } private companion object { val IDLE = 30.minutes } } ``` Timers belong to the actor: they stop when it stops and are cancelled when it restarts. Timer messages go through the mailbox like any other message, so they run one at a time with the rest. ## Watching other actors `ctx.watch(ref)` asks to be told when another actor stops. When it does, this actor receives the `ActorTerminated` signal with the stopped actor's ref: === "Java" ```java .onMessage(Track.class, (ctx, msg) -> { ctx.watch(msg.worker()); return SpringActorBehavior.same(); }) .onSignal(ActorTerminated.class, (ctx, signal) -> { ctx.getLog().info("{} stopped", signal.ref().path()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin onMessage { msg -> watch(msg.worker) same() } onSignal { signal -> log.info("{} stopped", signal.ref.path()) same() } ``` !!! warning "Always handle ActorTerminated when you watch" An actor that watches another and has no `onSignal(ActorTerminated.class, ...)` handler **fails** when the watched actor stops, and its supervision strategy applies (stop, by default). The watched actor can be anywhere: a child, an unrelated actor, or (in cluster mode) an actor on another node; it then also counts as stopped when its node leaves the cluster. The chat example's `UserActor` watches the actor that represents the WebSocket client so it can clean up when the client goes away. ## Futures: pipeToSelf Handlers must not block, and callbacks on a `CompletionStage` run on another thread, where they must not touch the actor's state. `ctx.pipeToSelf(stage, (value, error) -> message)` solves both: when the stage completes, the function builds a message, and the actor handles it like any other. === "Java" ```java .onMessage(Load.class, (state, msg) -> { state.ctx().pipeToSelf( profileClient.fetch(msg.userId()), // CompletionStage (profile, error) -> new Loaded(profile, error)); return SpringActorBehavior.same(); }) .onMessage(Loaded.class, (state, msg) -> state.onLoaded(msg)) // update state here ``` === "Kotlin" ```kotlin onMessage { msg -> ctx.pipeToSelf(profileClient.fetch(msg.userId)) { profile, error -> // CompletionStage Loaded(profile, error) } same() } onMessage { msg -> onLoaded(msg) } // update state here ``` Exactly one of `value` and `error` is non-null. More examples, including asking another actor, are in [Messaging](messaging.md#asking-from-inside-an-actor). ## The behavior context The context (`SpringBehaviorContext`) is what an actor can do from its handlers. You get it in the `withState` factory, and as the first handler argument when there is no `withState` (in the Kotlin `behavior { }` DSL, as the handler's `this`). | Method | What it does | |---|---| | `getSelf()` | A handle to this actor: pass it as a reply address, or use it for [child operations](actors.md#child-actors) | | `getLog()` | The actor's logger; its lines carry the actor's path and MDC (see [Logging](logging.md)) | | `actorId()` | The id the actor was spawned with, so handlers don't have to capture it in `create` | | `path()`, `nodeAddress()` | The actor's path and the address of the node it runs on | | `getChild(ChildClass.class, id)`, `getChildren()` | The running child with that class and id (an `Optional`), and all running children. `getChild(name)`, which took the internal name `:`, is deprecated | | `stop(child)` | Stops one of this actor's children | | `startSingleTimer`, `startTimerAtFixedRate`, `cancelTimer` | [Timers](#timers) | | `watch(ref)` | [Watching](#watching-other-actors) | | `pipeToSelf(stage, fn)` | [Futures](#futures-pipetoself) | | `askToSelf(target, command, timeout, fn)` (*new in the next release*) | Asks `target` and sends this actor the message `fn` builds from the reply or the error. See [Messaging](messaging.md#asking-from-inside-an-actor). | | `messageAdapter(Type.class, fn)` | A ref that accepts another actor's reply type and delivers it as one of this actor's commands. See [Messaging](messaging.md#replying-to-an-actor-without-ask). | | `registerWithReceptionist(name)` | Registers this actor under a service name. See [Receptionist](receptionist.md). | | `unwrap(Class)` | The underlying Pekko `ActorContext`, for features the starter doesn't wrap | Use the context only on the actor's own thread: inside handlers and the `withState` factory, never in a future callback. ## Stashing and other Pekko features The starter has no stash (holding messages back until the actor is ready). The usual replacement is a queue in the state object, as the `AgentBrain` of the [agent example](../../examples/agent.md) does: while it is busy it adds new `Chat` messages to a `Deque` and takes the next one when the turn ends. For a Pekko feature the starter doesn't wrap, there are two escape hatches. Code that uses them depends on Pekko directly and gets no compatibility promise from the starter. - `ctx.unwrap(org.apache.pekko.actor.typed.javadsl.ActorContext.class)` returns Pekko's context. - `SpringActorBehavior.wrap(pekkoBehavior)` runs a behavior written against Pekko's API. Such a behavior gets none of the starter's features (child operations, MDC, metrics hooks). ## Pitfalls - **Blocking in a handler.** Use `pipeToSelf` for futures, and the blocking dispatcher for blocking I/O. - **Touching state from a callback.** `thenAccept` on a future runs on another thread. Send a message with `pipeToSelf` instead. - **Watching without handling `ActorTerminated`.** The watcher fails when the watched actor stops. - **Heavy work in `withState`.** The actor handles no message until the factory returns. Load large data asynchronously with `pipeToSelf`. - **Handler order.** The first handler whose type matches wins. Register specific types before their supertypes. ## Related - [Actors](actors.md): defining, spawning and stopping actors - [Messaging](messaging.md): tell, ask and message adapters - [Supervision](supervision.md): restarts and what they reset - [Logging](logging.md): per-message MDC with `withMdc` - [Testing](../testing.md): testing behaviors --- # Routers A router is an actor that owns a pool of identical worker actors and passes each message it receives to one of them (or to all of them). You send to the router as if it were one actor; the work runs on several workers at once. Use a router when one actor can't keep up and the work doesn't depend on shared state: sending emails, resizing images, calling a slow API. If the work belongs to an entity (an order, a user), use one actor per entity instead (see [Actors](actors.md) or [Sharded actors](../cluster/sharded-actors.md)); a router with [consistent hashing](#consistent-hashing) sits in between. A router lives on one node, and its workers are its children. Routers come with the core starter; no extra dependency or configuration is needed. ## Creating a router A router has two parts: the worker actor that does the work, and the router actor that holds the pool. They share one command type. === "Java" ```java import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.SupervisionStrategy; import io.github.seonwkim.actor.router.RoutingStrategy; import io.github.seonwkim.actor.router.SpringRouterBehavior; import org.springframework.stereotype.Component; // The worker: an ordinary actor bean @Component public class ResizeWorker implements SpringActor { private final ImageService imageService; public ResizeWorker(ImageService imageService) { this.imageService = imageService; } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(ImageRouter.Command.class, actorContext) .onMessage(ImageRouter.Resize.class, (ctx, msg) -> { imageService.resize(msg.imageId(), msg.width()); return SpringActorBehavior.same(); }) .build(); } } // The router: its behavior is a pool of ResizeWorkers @Component public class ImageRouter implements SpringActor { public interface Command {} public record Resize(String imageId, int width) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringRouterBehavior.builder(Command.class, actorContext) .withRoutingStrategy(RoutingStrategy.roundRobin()) .withPoolSize(8) .withWorkerActors(ResizeWorker.class) .withSupervisionStrategy(SupervisionStrategy.restart()) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.SupervisionStrategy import io.github.seonwkim.actor.kotlin.actorBehavior import io.github.seonwkim.actor.router.RoutingStrategy import io.github.seonwkim.actor.router.SpringRouterBehavior import org.springframework.stereotype.Component // The worker: an ordinary actor bean @Component class ResizeWorker(private val imageService: ImageService) : SpringActor { override fun create(actorContext: SpringActorContext): SpringActorBehavior = actorBehavior(actorContext) .onMessage(ImageRouter.Resize::class.java) { _, msg -> imageService.resize(msg.imageId, msg.width) SpringActorBehavior.same() } .build() } // The router: its behavior is a pool of ResizeWorkers @Component class ImageRouter : SpringActor { sealed interface Command data class Resize(val imageId: String, val width: Int) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = SpringRouterBehavior.builder(Command::class.java, actorContext) .withRoutingStrategy(RoutingStrategy.roundRobin()) .withPoolSize(8) .withWorkerActors(ResizeWorker::class.java) .withSupervisionStrategy(SupervisionStrategy.restart()) .build() } ``` Spawn and use the router like any other actor: === "Java" ```java @Service public class ImageResizer { private final SpringActorSystem actorSystem; public ImageResizer(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } public void resizeLater(String imageId) { actorSystem.getOrSpawn(ImageRouter.class, "image-router") .thenAccept(router -> router.tell(new ImageRouter.Resize(imageId, 640))); } } ``` === "Kotlin" ```kotlin @Service class ImageResizer(private val actorSystem: SpringActorSystem) { suspend fun resizeLater(imageId: String) { actorSystem.awaitGetOrSpawn("image-router") .tell(ImageRouter.Resize(imageId, 640)) } } ``` ## Builder options | Method | Required | Default | Notes | |---|---|---|---| | `withRoutingStrategy(strategy)` | yes | none | `build()` throws `IllegalStateException` without it | | `withWorkerActors(Class)` | yes | none | A `SpringActor` bean whose command type is the router's | | `withPoolSize(n)` | no | 5 | Must be positive | | `withSupervisionStrategy(strategy)` | no | stop | Applies to each worker. See [Worker failures](#worker-failures). | Each worker's `create(actorContext)` gets its own id, `worker-` (`actorContext.actorId()`), which it keeps across restarts. Use it to tell workers apart in logs. ## Routing strategies | Strategy | Who gets a message | Use it for | |---|---|---| | `RoutingStrategy.roundRobin()` | Each worker in turn | Tasks that take about the same time | | `RoutingStrategy.random()` | A random worker | Simple spreading with no bookkeeping | | `RoutingStrategy.broadcast()` | Every worker | Telling all workers something, such as "clear your cache" | | `RoutingStrategy.consistentHashing()` | The worker chosen by the message's key | Keeping all messages for one key on one worker | ### Broadcast With `broadcast()`, every message is handled once per worker: 10 messages to a pool of 5 means 50 handler calls. Use it for rare control messages, not for regular work. A broadcast ask gets the first worker's reply; the other replies are dropped. ### Consistent hashing `consistentHashing()` sends messages with the same key to the same worker, as long as the pool doesn't change. A worker can then keep a cache per key, or handle one customer's messages in order. Give a message its key by implementing `ConsistentHashable`: === "Java" ```java public record ProcessOrder(String customerId, String orderId) implements Command, ConsistentHashable { @Override public String getConsistentHashKey() { return customerId; // one customer's orders always go to the same worker } } // In the router's create(): return SpringRouterBehavior.builder(Command.class, actorContext) .withRoutingStrategy(RoutingStrategy.consistentHashing()) .withPoolSize(10) .withWorkerActors(OrderWorker.class) .build(); ``` === "Kotlin" ```kotlin data class ProcessOrder(val customerId: String, val orderId: String) : Command, ConsistentHashable { // one customer's orders always go to the same worker override fun getConsistentHashKey(): String = customerId } // In the router's create(): SpringRouterBehavior.builder(Command::class.java, actorContext) .withRoutingStrategy(RoutingStrategy.consistentHashing()) .withPoolSize(10) .withWorkerActors(OrderWorker::class.java) .build() ``` - The key must not be `null`; a `null` key fails the routing with `IllegalStateException`. - A message that doesn't implement `ConsistentHashable` is hashed by its `toString()`. Records and data classes have a stable `toString()`; most other classes don't, so implement `ConsistentHashable`. - `consistentHashing(virtualNodesFactor)` sets how many points each worker gets on the hash ring (default 10, minimum 1). More points spread keys more evenly. - This is not a replacement for sharding: the mapping changes when a worker is replaced, and it stays on one node. For one actor per key across a cluster, use [sharded actors](../cluster/sharded-actors.md). ## Ask through a router A router forwards `AskCommand`s like any message, and the worker that handles it replies to the asker: === "Java" ```java public static class Validate extends AskCommand implements Command { public final String data; public Validate(String data) { this.data = data; } } // In the worker: .onMessage(Validate.class, (ctx, msg) -> { msg.reply(!msg.data.isBlank()); return SpringActorBehavior.same(); }) // The caller: CompletionStage valid = router.ask(new ValidationRouter.Validate("payload")) .withTimeout(Duration.ofSeconds(2)) .execute(); ``` === "Kotlin" ```kotlin class Validate(val data: String) : AskCommand(), Command // In the worker: .onMessage(Validate::class.java) { _, msg -> msg.reply(msg.data.isNotBlank()) SpringActorBehavior.same() } // The caller, in a suspend function: val valid: Boolean = router.awaitAsk(ValidationRouter.Validate("payload"), timeout = 2.seconds) ``` ## Worker failures The router's `withSupervisionStrategy` applies to each worker. Without it, a worker whose handler throws **stops** and leaves the pool, so the pool shrinks with every failure. For a pool that should keep its size, set `SupervisionStrategy.restart()` (or `restart().withLimit(...)`). With restart, the failed message is dropped and the other messages are still handled, as the router tests check. See [Supervision](supervision.md) for what each strategy does. ## Workers and Spring beans Every worker in a pool is created from the same worker bean, so: - Injected services are shared by all workers (and by every pool that uses the bean). That is what you want for repositories, clients and connection pools. - Per-worker state belongs in the worker's [`withState`](behaviors.md#state-with-withstate) object, not in a field of the bean. - Workers don't have ids of their own. All workers of a pool get the same generated `actorContext.actorId()` (`worker-`), so don't use it to tell workers apart. A worker that blocks (JDBC, blocking HTTP) holds a thread of the router's dispatcher. Spawn the router with `withBlockingDispatcher()` or a [custom dispatcher](dispatchers.md) in that case. ## Pitfalls - **No routing strategy.** `build()` fails; there is no default strategy. - **Pool that shrinks.** Without a restart strategy, failing workers stop for good. - **Shared state in the worker bean.** All workers of all pools share it. - **Ordering.** Round robin and random spread consecutive messages over different workers, so they can be handled out of order. Use consistent hashing (or one actor per key) when order per key matters. ## Related - [Actors](actors.md): spawning the router - [Supervision](supervision.md): worker strategies - [Dispatchers](dispatchers.md): thread pools for blocking workers - [Sharded actors](../cluster/sharded-actors.md): one actor per key across a cluster - [Pekko routers](https://pekko.apache.org/docs/pekko/current/typed/routers.html): the pool router the starter uses --- # Pub/Sub Topics A topic delivers each published message to every actor subscribed to it. The publisher doesn't know who the subscribers are or how many there are. In cluster mode, a message published on one node reaches the subscribers on every node. Use a topic for one-to-many messages: chat rooms, live notifications, "this data changed" events that several actors care about. Don't use it for: - one-to-one messages: send to the actor directly ([Messaging](messaging.md)); - request and reply: use ask; - messages that must not be lost: topics deliver at most once; - spreading work so that only one worker handles each message: use a [router](routers.md). Topics come with the core starter. The `SpringTopicManager` bean is created for you. ## Names and message types A topic is identified by a `TopicName`: a message type plus a name. Publishers and subscribers that use the same type and name share the topic, on every node. Two topics with the same name but different types are different topics. The type matters because **subscribers receive the messages as commands**. A topic's type must be the subscribers' command type (or a supertype of it): an actor of `SpringActor` can subscribe to a topic of `UserActor.Command`, and every message published there must be a `UserActor.Command`. === "Java" ```java // In UserActor: the events users receive are some of its commands public interface Command extends JsonSerializable {} public record ChatPosted(String roomId, String userId, String text) implements Command {} // The topic for one room TopicName room = TopicName.of(UserActor.Command.class, "chat-room-" + roomId); ``` === "Kotlin" ```kotlin // In UserActor: the events users receive are some of its commands sealed interface Command : JsonSerializable data class ChatPosted(val roomId: String, val userId: String, val text: String) : Command // The topic for one room val room: TopicName = TopicName.of(UserActor.Command::class.java, "chat-room-$roomId") ``` In cluster mode, messages cross nodes, so the message type must implement `JsonSerializable` or `CborSerializable`. In local mode they don't have to. ## Getting a topic Inject `SpringTopicManager` and call `topic(name)`, then one of: | Method | What it does | |---|---| | `getOrCreate()` | Returns the topic, creating it on this node if it doesn't exist yet. Safe to call any number of times. | | `create()` | Creates the topic; throws `TopicAlreadyExistsException` if it already exists on this node | | `getOrCreateAsync()`, `createAsync()` | The same without blocking: a `CompletionStage` that completes with the topic or fails with the same exception | | `withTimeout(duration)` | How long they may wait (default 5 s). On timeout they fail with `TopicCreationTimeoutException`. | `getOrCreate()` and `create()` **block the calling thread** until the topic is ready (usually much less than a millisecond). That is fine in a service, but not on an actor's thread: there, use the async form and receive the topic as a message with `pipeToSelf`, as the [chat example](../../examples/chat.md)'s room actor does. Called on a thread of the actor system (an actor's `create()` or handler), the blocking forms throw `IllegalStateException` at once instead of waiting out the timeout. Call them once and keep the `SpringTopicRef`, for example in a service field or in an actor's state: === "Java" ```java import io.github.seonwkim.actor.topic.SpringTopicManager; import io.github.seonwkim.actor.topic.SpringTopicRef; import io.github.seonwkim.actor.topic.TopicName; import org.springframework.stereotype.Service; @Service public class AnnouncementService { private final SpringTopicRef announcements; public AnnouncementService(SpringTopicManager topics) { this.announcements = topics .topic(TopicName.of(UserActor.Command.class, "announcements")) .getOrCreate(); } public void announce(String text) { announcements.publish(new UserActor.ChatPosted("all", "system", text)); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.topic.SpringTopicManager import io.github.seonwkim.actor.topic.SpringTopicRef import io.github.seonwkim.actor.topic.TopicName import org.springframework.stereotype.Service @Service class AnnouncementService(topics: SpringTopicManager) { private val announcements: SpringTopicRef = topics .topic(TopicName.of(UserActor.Command::class.java, "announcements")) .getOrCreate() fun announce(text: String) { announcements.publish(UserActor.ChatPosted("all", "system", text)) } } ``` ## Publishing and subscribing | Method on `SpringTopicRef` | What it does | |---|---| | `publish(message)` | Sends the message to every current subscriber. Returns at once. With no subscribers, the message is dropped. | | `subscribe(ref)` | Delivers the topic's messages to `ref` until it unsubscribes or stops. Subscribing twice is the same as once. | | `unsubscribe(ref)` | Stops delivery to `ref`. Unsubscribing an actor that isn't subscribed does nothing. | | `name()` | The topic's `TopicName` | | `unwrap(Class)` | Pekko's topic actor, for features the starter doesn't wrap | `subscribe` and `unsubscribe` take any `SpringActorRef`: a handle from `getOrSpawn`, `ctx.getSelf()`, or a ref received in a message. A subscriber that stops is removed from the topic for you. Subscribing takes effect shortly after the call, not instantly. A message published right after `subscribe` can miss the new subscriber. In cluster mode, it also takes a moment for other nodes to learn about a new subscriber. ## Example: chat rooms The [chat example](../../examples/chat.md) has one actor per room and one per connected user. The room actor owns the room's topic: it subscribes users when they join and publishes what they say. It asks for the topic with `getOrCreateAsync()` and receives it as a message through `pipeToSelf`, so its thread never blocks (`create()` runs while the actor is being spawned). Commands that arrive before the topic wait in a list. Simplified from its `ChatRoomActor`: === "Java" ```java @Component public class ChatRoomActor implements SpringActor { private final SpringTopicManager topics; public ChatRoomActor(SpringTopicManager topics) { this.topics = topics; } public interface Command extends JsonSerializable {} public record JoinRoom(String userId, SpringActorRef user) implements Command {} public record SendMessage(String userId, String text) implements Command {} // Sent by the actor to itself; it never crosses nodes. private record TopicReady(SpringTopicRef topic, Throwable error) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { String roomId = actorContext.actorId(); return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> { ctx.pipeToSelf( topics.topic(TopicName.of(UserActor.Command.class, "chat-room-" + roomId)) .getOrCreateAsync(), TopicReady::new); return new Room(roomId); }) .onMessage(TopicReady.class, Room::onTopicReady) .onMessage(JoinRoom.class, Room::handle) .onMessage(SendMessage.class, Room::handle) .build(); } private static class Room { private final String roomId; private final List pending = new ArrayList<>(); private SpringTopicRef topic; Room(String roomId) { this.roomId = roomId; } SpringActorBehavior onTopicReady(TopicReady ready) { if (ready.error() != null) { throw new IllegalStateException("No topic for room " + roomId, ready.error()); } topic = ready.topic(); pending.forEach(this::handle); pending.clear(); return SpringActorBehavior.same(); } SpringActorBehavior handle(Command command) { if (topic == null) { pending.add(command); } else if (command instanceof JoinRoom join) { topic.subscribe(join.user()); } else if (command instanceof SendMessage send) { topic.publish(new UserActor.ChatPosted(roomId, send.userId(), send.text())); } return SpringActorBehavior.same(); } } } ``` === "Kotlin" ```kotlin @Component class ChatRoomActor(private val topics: SpringTopicManager) : SpringActor { sealed interface Command : JsonSerializable data class JoinRoom(val userId: String, val user: SpringActorRef) : Command data class SendMessage(val userId: String, val text: String) : Command // Sent by the actor to itself; it never crosses nodes. private data class TopicReady(val topic: SpringTopicRef?, val error: Throwable?) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior { val roomId = actorContext.actorId() return actorBehavior(actorContext) .withState { ctx -> ctx.pipeToSelf( topics.topic(TopicName.of(UserActor.Command::class.java, "chat-room-$roomId")) .getOrCreateAsync(), ) { topic, error -> TopicReady(topic, error) } Room(roomId) } .onMessage(TopicReady::class.java) { room, ready -> room.onTopicReady(ready) } .onMessage(JoinRoom::class.java) { room, msg -> room.handle(msg) } .onMessage(SendMessage::class.java) { room, msg -> room.handle(msg) } .build() } private class Room(private val roomId: String) { private val pending = mutableListOf() private var topic: SpringTopicRef? = null fun onTopicReady(ready: TopicReady): SpringActorBehavior { topic = ready.topic ?: throw IllegalStateException("No topic for room $roomId", ready.error) pending.forEach { handle(it) } pending.clear() return SpringActorBehavior.same() } fun handle(command: Command): SpringActorBehavior { val topic = topic when { topic == null -> pending.add(command) command is JoinRoom -> topic.subscribe(command.user) command is SendMessage -> topic.publish(UserActor.ChatPosted(roomId, command.userId, command.text)) } return SpringActorBehavior.same() } } } ``` The example's real room actor is a [sharded actor](../cluster/sharded-actors.md), so each room lives on one node of the cluster while its users can be on any node. It also handles leaving the room. ## Delivery guarantees - **At most once.** A message reaches each subscriber once or not at all. Messages to a subscriber that is stopping, on a node that is unreachable, or that subscribed a moment too late are lost. - **Order.** Messages from one publisher arrive at each subscriber in the order they were published. - **No history.** A new subscriber gets only messages published after it joined. To show recent history, keep it in an actor or a database and send it when someone joins. ## Pitfalls - **Topic type and subscriber type differ.** `subscribe` takes a `SpringActorRef` of the topic's type, so the compiler stops a mismatch. Make published events part of the subscribers' command type. - **Creating topics on every call.** `getOrCreate()` blocks the caller briefly. Keep the ref. - **Blocking an actor's thread.** Inside an actor, use `getOrCreateAsync()` with `pipeToSelf`. - **Using `create()` where `getOrCreate()` is meant.** `create()` throws if the topic already exists. - **Expecting delivery.** For messages that must arrive, send them directly and confirm with ask, or store them first. ## Related - [Messaging](messaging.md): direct messages and ask - [Receptionist](receptionist.md): finding actors by service name - [Routers](routers.md): one message to one of many workers - [Chat example](../../examples/chat.md): topics with sharded rooms - [Cluster formation](../cluster/cluster-formation.md): running topics across nodes --- # Receptionist (Service Discovery) The receptionist finds actors by a **service name** instead of by class and id. Actors register under a name; other code looks the name up once, or subscribes and is told whenever the set of registered actors changes. In cluster mode, the registrations are shared across nodes, so a lookup on one node finds actors on every node. It wraps Pekko's typed [Receptionist](https://pekko.apache.org/docs/pekko/current/typed/actor-discovery.html). Use it when the caller doesn't know (or shouldn't know) the ids of the actors it needs: - finding all instances of a worker, wherever they run; - reacting when instances of a service start and stop; - reaching actors on other cluster nodes without sharding them. When you know the id, use `getOrSpawn` or `get` ([Actors](actors.md)) or a [sharded actor](../cluster/sharded-actors.md) instead. To send one message to many actors, a [topic](pub-sub-topics.md) is simpler. The `SpringReceptionist` bean comes with the core starter. It is created with `@ConditionalOnMissingBean`, so you can replace it with your own bean. ## Service names A `ServiceName` combines a message type and an id. Names with the same type and id are equal on every node. The type is the command type of the registered actors, so lookups return handles you can `tell` and `ask` directly. === "Java" ```java public static final ServiceName WORKERS = ServiceName.of(WorkerActor.Command.class, "workers"); ``` === "Kotlin" ```kotlin val WORKERS: ServiceName = ServiceName.of(WorkerActor.Command::class.java, "workers") ``` The id must not be blank. In cluster mode the messages must implement `JsonSerializable` or `CborSerializable`, as for any message that crosses nodes. ## Registering An actor can register itself when it starts, in its `withState` factory: === "Java" ```java import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.serialization.JsonSerializable; import org.springframework.stereotype.Component; @Component public class WorkerActor implements SpringActor { public interface Command extends JsonSerializable {} public record DoJob(String jobId) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> { ctx.registerWithReceptionist(WORKERS); return ctx; }) .onMessage(DoJob.class, (ctx, msg) -> { ctx.getLog().info("Running job {}", msg.jobId()); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.kotlin.actorBehavior import io.github.seonwkim.actor.serialization.JsonSerializable import org.springframework.stereotype.Component @Component class WorkerActor : SpringActor { sealed interface Command : JsonSerializable data class DoJob(val jobId: String) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = actorBehavior(actorContext) .withState { ctx -> ctx.registerWithReceptionist(WORKERS) ctx } .onMessage(DoJob::class.java) { ctx, msg -> ctx.log.info("Running job {}", msg.jobId) SpringActorBehavior.same() } .build() } ``` Or any code can register an actor it has a ref to, with `receptionist.register(name, ref)`: === "Java" ```java SpringActorHandle worker = actorSystem.actor(WorkerActor.class) .withId("worker-1") .spawnAndWait(); receptionist.register(WORKERS, worker); ``` === "Kotlin" ```kotlin // In a suspend function val worker = actorSystem.actor().withId("worker-1").awaitSpawn() receptionist.register(WORKERS, worker) ``` A stopped actor is removed from its services automatically. To remove a running one, call `receptionist.deregister(name, ref)`. ## Finding `find(name)` returns the actors registered under the name right now. The set may be empty. === "Java" ```java @Service public class JobDispatcher { private final SpringReceptionist receptionist; public JobDispatcher(SpringReceptionist receptionist) { this.receptionist = receptionist; } public CompletionStage dispatch(String jobId) { return receptionist.find(WORKERS).thenApply(workers -> { workers.forEach(w -> w.tell(new WorkerActor.DoJob(jobId))); return workers.size(); }); } } ``` === "Kotlin" ```kotlin @Service class JobDispatcher(private val receptionist: SpringReceptionist) { suspend fun dispatch(jobId: String): Int { val workers = receptionist.find(WORKERS).await() workers.forEach { it.tell(WorkerActor.DoJob(jobId)) } return workers.size } } ``` `find(name)` waits up to 3 seconds for the receptionist's answer; `find(name, timeout)` sets another limit. The result is a `Set>`; each handle supports `tell` and `ask`. ## Subscribing to changes `subscribe(name, listener)` calls the listener with the current set right away, then with the full new set every time an actor registers, deregisters or stops: === "Java" ```java SpringReceptionistSubscription subscription = receptionist.subscribe(WORKERS, workers -> log.info("{} workers available", workers.size())); // later, for example in a @PreDestroy method subscription.cancel(); ``` === "Kotlin" ```kotlin val subscription: SpringReceptionistSubscription = receptionist.subscribe(WORKERS) { workers -> log.info("{} workers available", workers.size) } // later, for example in a @PreDestroy method subscription.cancel() ``` - The listener runs on an actor thread. Keep it short and never block in it. A common pattern is to copy the set into a field (an `AtomicReference`) that request code reads. - If the listener throws, the error is logged and the subscription stays. - Each subscription is backed by a small helper actor. `cancel()` stops it and is safe to call twice; after `cancel()` returns, the listener isn't called again. `isCancelled()` tells whether it was cancelled, and `whenTerminated()` completes once the helper actor has stopped. ## Cluster mode In a cluster, registrations are replicated to all nodes. `find` on node 2 can return an actor that runs on node 1, and `tell` on the returned handle goes over the network. !!! warning "Eventually consistent" Replication takes time. Right after an actor registers on one node, a lookup on another node can still return an empty or older set. Don't treat an empty result as final: retry with a bounded wait, or use `subscribe` and act when the actor appears. Registrations of a node that leaves the cluster are removed once the node is removed from membership. ## API summary | Method | Description | |---|---| | `ServiceName.of(type, id)` | Creates a service name | | `register(name, ref)` | Registers an actor under a name | | `deregister(name, ref)` | Removes an actor from a name | | `find(name)`, `find(name, timeout)` | One-time lookup; default timeout 3 s | | `subscribe(name, listener)` | Calls the listener now and on every change; returns a cancellable subscription | | `SpringBehaviorContext.registerWithReceptionist(name)` | Registers the current actor from inside it | ## Related - [Actors](actors.md): finding actors by class and id - [Pub/sub topics](pub-sub-topics.md): one message to many actors - [Sharded actors](../cluster/sharded-actors.md): one actor per id across a cluster - [Cluster formation](../cluster/cluster-formation.md): running a cluster --- # Dispatchers and Mailboxes A **dispatcher** is the thread pool that runs actors. When an actor has messages, the dispatcher gives it a thread, the actor handles a batch of messages, and the thread moves on to another actor. Thousands of actors share a few threads this way. A **mailbox** is the queue an actor's messages wait in until it handles them. Most actors need neither setting: the default dispatcher and the default (unbounded) mailbox fit non-blocking work. Change them when an actor blocks, when a group of actors must not slow down the others, or when a queue must not grow without bound. ## Choosing a dispatcher | Work in the handler | Dispatcher | |---|---| | Non-blocking: in-memory state, `tell`, `ask` with `pipeToSelf` | Default (nothing to set) | | Blocking I/O: JDBC/JPA, file I/O, blocking HTTP clients | `withBlockingDispatcher()` | | Blocking I/O, many concurrent calls, Java 21 | The blocking dispatcher on [virtual threads](#virtual-threads) | | A group of actors that must be isolated from the rest | A [custom dispatcher](#custom-dispatchers) | | Work on a thread pool your application already manages | A dispatcher on a [Spring `Executor` bean](#spring-executor-beans) | !!! danger "Never block on the default dispatcher" The default dispatcher has about as many threads as CPU cores. An actor that blocks there holds one of them, and a few blocking actors can stall every other actor in the application. ## Selecting a dispatcher Choose the dispatcher when you spawn the actor: === "Java" ```java // Blocking work: Pekko's blocking I/O dispatcher actorSystem.actor(ReportActor.class) .withId("report-1") .withBlockingDispatcher() .spawn(); // A dispatcher defined in configuration (see below) actorSystem.actor(ReportActor.class) .withId("report-2") .withDispatcherFromConfig("reports") .spawn(); ``` === "Kotlin" ```kotlin // In a suspend function // Blocking work: Pekko's blocking I/O dispatcher actorSystem.actor() .withId("report-1") .withBlockingDispatcher() .awaitSpawn() // A dispatcher defined in configuration (see below) actorSystem.actor() .withId("report-2") .withDispatcherFromConfig("reports") .awaitSpawn() ``` Both the spawn builder and the child builder take every form (the child builder's shortcut methods and the spawn builder's `withDispatcher(DispatcherConfig)` since 1.1.0): | Shortcut | `DispatcherConfig` form | Runs the actor on | |---|---|---| | `withDefaultDispatcher()` (the default) | `withDispatcher(DispatcherConfig.defaultDispatcher())` | The default dispatcher | | `withBlockingDispatcher()` | `withDispatcher(DispatcherConfig.blocking())` | Pekko's `default-blocking-io-dispatcher` | | `withDispatcherFromConfig(name)` | `withDispatcher(DispatcherConfig.fromConfig(name))` | The dispatcher defined under `spring.actor.` or `spring.actor.dispatchers.` | | `withDispatcherSameAsParent()` | `withDispatcher(DispatcherConfig.sameAsParent())` | The parent's dispatcher | For a child actor: === "Java" ```java ctx.getSelf().child(ExportWorker.class) .withId("export-1") .withBlockingDispatcher() .spawn(); ``` === "Kotlin" ```kotlin ctx.self.child() .withId("export-1") .withBlockingDispatcher() .spawn() ``` An unknown dispatcher name makes the spawn fail; the actor system keeps working. ## The blocking dispatcher `withBlockingDispatcher()` uses Pekko's `default-blocking-io-dispatcher`, a thread pool meant for blocking calls. Pekko gives it 16 threads by default. Its threads are separate from the default dispatcher's, so blocking actors can only slow each other down. Change its size with raw Pekko keys: ```yaml spring: actor: pekko: actor: default-blocking-io-dispatcher: thread-pool-executor: fixed-pool-size: 32 ``` ## Custom dispatchers Define your own dispatcher under `spring.actor.` with Pekko's dispatcher keys. Every key under `spring.actor` that the starter doesn't know is passed to Pekko without the prefix, so `spring.actor.my-dispatcher` becomes Pekko's `my-dispatcher` (see [Configuration](../operations/configuration.md)). Then spawn with `withDispatcherFromConfig("my-dispatcher")`. A fixed thread pool, for blocking work you want to keep apart from the rest: ```yaml spring: actor: db-dispatcher: type: Dispatcher executor: thread-pool-executor thread-pool-executor: fixed-pool-size: 16 throughput: 1 ``` A fork-join pool, for CPU-heavy work you want to keep apart: ```yaml spring: actor: cpu-dispatcher: type: Dispatcher executor: fork-join-executor fork-join-executor: parallelism-min: 2 parallelism-factor: 1.0 # threads = CPU cores x factor, within min and max parallelism-max: 8 throughput: 100 ``` A thread pool that grows and shrinks: ```yaml spring: actor: elastic-dispatcher: type: Dispatcher executor: thread-pool-executor thread-pool-executor: core-pool-size-min: 4 core-pool-size-factor: 2.0 core-pool-size-max: 16 max-pool-size-min: 8 max-pool-size-factor: 2.0 max-pool-size-max: 32 throughput: 10 ``` Pekko also has `type: PinnedDispatcher`, which gives each actor its own thread. It uses one thread per actor, so keep it for a handful of actors. All dispatcher keys are in the [Pekko dispatcher documentation](https://pekko.apache.org/docs/pekko/current/typed/dispatchers.html). ### Throughput `throughput` is the number of messages an actor may handle before its thread moves on to the next actor. A high value (100) means fewer switches and more speed; a low value (1) is fairer, so one busy actor can't keep others waiting. Use 1 for dispatchers whose actors block. ## Spring Executor beans A dispatcher can run its actors on an `Executor` bean of your application, for example a `ThreadPoolTaskExecutor` you already tune and monitor: === "Java" ```java @Bean ThreadPoolTaskExecutor reportExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("reports-"); executor.setCorePoolSize(8); return executor; } ``` === "Kotlin" ```kotlin @Bean fun reportExecutor(): ThreadPoolTaskExecutor = ThreadPoolTaskExecutor().apply { setThreadNamePrefix("reports-") corePoolSize = 8 } ``` ```yaml spring: actor: dispatchers: reports: executor: reportExecutor # the bean name throughput: 10 # optional ``` Spawn with `withDispatcherFromConfig("reports")`. The Spring context owns the executor: the actor system never shuts it down, and it keeps running while the actor system stops. | Key | Meaning | |---|---| | `spring.actor.dispatchers..executor` | The name of an `Executor` bean | | `spring.actor.dispatchers..virtual` | `true` for a dispatcher on virtual threads (see below) | | `spring.actor.dispatchers..throughput` | Optional throughput | A dispatcher sets either `executor` or `virtual: true`, not both. The name may contain letters, digits, `-` and `_`. ## Virtual threads On Java 21, blocking actors can run on virtual threads: a blocked virtual thread doesn't hold a platform thread, so many blocking calls can wait at once. ```yaml spring: actor: virtual-threads: enabled: true # auto (default) | true | false dispatchers: virtual-thread-dispatcher: virtual: true ``` - `spring.actor.virtual-threads.enabled` runs the blocking dispatcher (`withBlockingDispatcher()`) on virtual threads. The default, `auto`, follows Spring Boot's `spring.threads.virtual.enabled`, so an application that turns on virtual threads for Spring gets them for blocking actors too. `false` keeps platform threads even when Spring's flag is on. - `spring.actor.dispatchers..virtual: true` defines a named dispatcher on virtual threads, whatever the switch says. Spawn with `withDispatcherFromConfig("")`. - The default dispatcher always stays on its platform fork-join pool: actors that never block gain nothing from virtual threads. - A raw `spring.actor.pekko.actor.default-blocking-io-dispatcher.executor` still wins over the switch, with a warning in the log. !!! warning "Pinning" A virtual thread that blocks inside a `synchronized` block, or in some native calls, pins its carrier (platform) thread until it unblocks, and too many pinned carriers stall every virtual thread. Use `java.util.concurrent` locks (`ReentrantLock`) around blocking calls, and find pinning with `-Djdk.tracePinnedThreads=short`. Virtual threads help blocking I/O, not CPU-heavy work. The JVM's own settings (`jdk.virtualThreadScheduler.parallelism`, `jdk.virtualThreadScheduler.maxPoolSize`) rarely need changes. The [virtual-threads example](../../examples/virtual-threads.md) compares platform and virtual threads on the same workload. ## Mailboxes By default each actor has an unbounded mailbox: it accepts every message, and a slow actor's queue grows until memory runs out. Bound the mailbox of an actor that serves requests, such as one that HTTP handlers ask. When it falls behind, its callers' asks time out (after 3 s by default) and the callers retry, but every message they sent stays in the queue, so the queue grows faster the slower the actor gets, until the JVM runs out of memory. With a bound, the messages beyond it go to dead letters, and those asks fail with a timeout instead. Set another mailbox when you spawn the actor: === "Java" ```java // At most 1,000 waiting messages; further messages go to dead letters actorSystem.actor(IngestActor.class) .withId("ingest") .withMailbox(MailboxConfig.bounded(1_000)) .spawn(); // A mailbox defined in configuration actorSystem.actor(IngestActor.class) .withId("ingest-priority") .withMailbox(MailboxConfig.fromConfig("priority-mailbox")) .spawn(); ``` === "Kotlin" ```kotlin // In a suspend function // At most 1,000 waiting messages; further messages go to dead letters actorSystem.actor() .withId("ingest") .withMailbox(MailboxConfig.bounded(1_000)) .awaitSpawn() // A mailbox defined in configuration actorSystem.actor() .withId("ingest-priority") .withMailbox(MailboxConfig.fromConfig("priority-mailbox")) .awaitSpawn() ``` | `MailboxConfig` | Mailbox | |---|---| | `defaultMailbox()` | Unbounded (the default) | | `bounded(capacity)` | Holds at most `capacity` messages; messages beyond that are dropped to dead letters. `capacity` must be positive. | | `fromConfig(name)` | The mailbox defined under `spring.actor.` | A mailbox from configuration names a Pekko mailbox class, for example a priority mailbox that handles some messages before others: ```yaml spring: actor: priority-mailbox: mailbox-type: com.example.PriorityMailbox ``` Pekko's priority mailboxes (`UnboundedPriorityMailbox`, `UnboundedStablePriorityMailbox`, `BoundedPriorityMailbox`, `BoundedStablePriorityMailbox`) need a subclass that supplies the ordering; see the [Pekko mailbox documentation](https://pekko.apache.org/docs/pekko/current/typed/mailboxes.html). A bounded mailbox drops messages silently from the sender's point of view: `tell` still returns, and an `ask` times out. Use it to protect memory, and make senders slow down (with ask, or with [streams](../streaming/reactor-streams.md)) when you need back-pressure. ## Pitfalls - **Blocking on the default dispatcher.** The most common cause of an application that stops responding under load. - **One huge blocking pool for everything.** Give separate dispatchers to workloads that must not wait for each other (for example, the database and a slow partner API). - **Unbounded mailboxes in front of slow actors.** Watch mailbox sizes (see [Monitoring](../operations/monitoring.md)) and bound the ones that can grow. - **`virtual` and `executor` on one dispatcher.** The application fails to start; choose one. ## Related - [Actors](actors.md): the spawn builder - [Configuration](../operations/configuration.md): all `spring.actor` keys - [Monitoring](../operations/monitoring.md): dispatcher and mailbox metrics - [Virtual threads example](../../examples/virtual-threads.md) --- # Logging with MDC and Tags Logs from actors are harder to follow than logs from request threads: one actor handles messages for many requests, and one request can pass through several actors. The starter gives you three ways to put context on every log line an actor writes: - **Static MDC**: key-value pairs fixed when the actor is spawned (a user id, a service name). - **Dynamic MDC**: key-value pairs computed from each message (an order id, a request id). - **Tags**: labels on an actor (`worker`, `critical`), written to the `pekkoTags` field. MDC (Mapped Diagnostic Context) is SLF4J's map of values that the log pattern can print with `%X{key}`. Inside actors, log through the actor's logger, `ctx.getLog()` (`ctx.log` in Kotlin): its lines carry the fields below and the actor's MDC. ## Fields Pekko adds Every line written through `ctx.getLog()` already carries these MDC fields: | Field | Value | Example | |---|---|---| | `pekkoSource` | The actor's path | `pekko://my-app/user/...` | | `pekkoAddress` | The actor system's address | `pekko://my-app@10.0.0.5:25520` | | `pekkoTags` | The actor's tags, comma-separated | `worker,high-priority` | | `sourceActorSystem` | The actor system's name | `my-app` | ## Static MDC Set values that stay the same for the actor's whole life when you spawn it: === "Java" ```java actorSystem.actor(SessionActor.class) .withId("session-" + sessionId) .withMdc(MdcConfig.of(Map.of( "sessionId", sessionId, "userId", userId))) .spawn(); ``` === "Kotlin" ```kotlin // In a suspend function actorSystem.actor() .withId("session-$sessionId") .withMdc(MdcConfig.of(mapOf("sessionId" to sessionId, "userId" to userId))) .awaitSpawn() ``` Every line the actor logs then carries `sessionId` and `userId`. `MdcConfig.of` needs at least one entry; `MdcConfig.empty()` means none. ## Dynamic MDC Compute values from each message with `withMdc` on the behavior builder. The function receives every message and returns the map for the time that message is handled: === "Java" ```java import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Component; @Component public class OrderProcessorActor implements SpringActor { public interface Command {} public record ProcessOrder(String orderId, String userId, String requestId) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withMdc(msg -> { if (msg instanceof ProcessOrder order) { Map mdc = new HashMap<>(); mdc.put("orderId", order.orderId()); mdc.put("userId", order.userId()); if (order.requestId() != null) { // MDC values must not be null mdc.put("requestId", order.requestId()); } return mdc; } return Map.of(); }) .onMessage(ProcessOrder.class, (ctx, msg) -> { ctx.getLog().info("Processing order"); // carries orderId, userId, requestId return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.kotlin.actorBehavior import org.springframework.stereotype.Component @Component class OrderProcessorActor : SpringActor { sealed interface Command data class ProcessOrder(val orderId: String, val userId: String, val requestId: String?) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = actorBehavior(actorContext) .withMdc { msg -> when (msg) { is ProcessOrder -> buildMap { put("orderId", msg.orderId) put("userId", msg.userId) msg.requestId?.let { put("requestId", it) } // MDC values must not be null } } } .onMessage(ProcessOrder::class.java) { ctx, _ -> ctx.log.info("Processing order") // carries orderId, userId, requestId SpringActorBehavior.same() } .build() } ``` Return an empty map for messages without context. Static and dynamic MDC combine: a line carries both the spawn-time values and the values of the current message. ### Carrying a request id into an actor The MDC of the thread that sends a message does not travel with the message: the actor runs on another thread. To see a request id in the actor's logs, read it on the sending side, put it in the message, and add it back with `withMdc`. The [logging example](../../examples/logging.md) does this: a `WebFilter` puts `requestId` in the MDC of the request, the service reads it and passes it in `ProcessOrder`, and the actor's `withMdc` (above) puts it on the actor's lines. === "Java" ```java public Mono processOrder(String userId) { String requestId = MDC.get("requestId"); // on the request thread String orderId = UUID.randomUUID().toString(); return Mono.fromCompletionStage(actorSystem.getOrSpawn(OrderProcessorActor.class, "order-processor") .thenCompose(actor -> actor .ask(new OrderProcessorActor.ProcessOrder(orderId, userId, requestId)) .execute())); } ``` === "Kotlin" ```kotlin suspend fun processOrder(userId: String): OrderProcessed { val requestId = MDC.get("requestId") // read before the first suspension point val orderId = UUID.randomUUID().toString() return actorSystem.awaitGetOrSpawn("order-processor") .awaitAsk(OrderProcessorActor.ProcessOrder(orderId, userId, requestId)) } ``` (Here `ProcessOrder` is an `AskCommand`, as in the example.) With Micrometer Tracing on, the trace itself travels with messages, and lines carry `traceId` and `spanId`; see [Monitoring](../operations/monitoring.md#tracing). ## Tags Tags label an actor by role, priority or workload. They are written to the `pekkoTags` field of every line, so you can filter on them: === "Java" ```java actorSystem.actor(PaymentProcessor.class) .withId("payment-processor") .withTags(TagsConfig.of("payment-service", "critical")) .spawn(); ``` === "Kotlin" ```kotlin // In a suspend function actorSystem.actor() .withId("payment-processor") .withTags(TagsConfig.of("payment-service", "critical")) .awaitSpawn() ``` `TagsConfig.of(...)` takes one or more strings or a `Set`; `TagsConfig.empty()` means none. Duplicate tags count once. ## Children The child builder has the same `withMdc` and `withTags`. A child does not inherit its parent's MDC or tags; give it its own: === "Java" ```java ctx.getSelf().child(WorkerActor.class) .withId("worker-1") .withTags(TagsConfig.of("worker")) .withMdc(MdcConfig.of(Map.of("parentId", actorContext.actorId()))) .spawn(); ``` === "Kotlin" ```kotlin ctx.self.child() .withId("worker-1") .withTags(TagsConfig.of("worker")) .withMdc(MdcConfig.of(mapOf("parentId" to actorContext.actorId()))) .spawn() ``` ## Printing MDC with Logback MDC values appear only if the log pattern prints them. A console pattern: ```xml %d{ISO8601} %-5level [%X{pekkoSource}] [%X{pekkoTags}] [reqId=%X{requestId}] [userId=%X{userId}] %logger{36} - %msg%n ``` For log aggregation (Elasticsearch, Loki), write JSON with the [Logstash encoder](https://github.com/logfellow/logstash-logback-encoder) and list the MDC keys to include: ```xml pekkoSource pekkoTags requestId userId orderId traceId spanId ``` It needs `net.logstash.logback:logstash-logback-encoder` on the classpath. In production, put file and JSON appenders behind Logback's `AsyncAppender` so that writing a log line never makes an actor wait on disk. The logging example's [`logback.xml`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/logging/src/main/resources/logback.xml) has console, rolling file and JSON appenders, each async. ## Good practice - Use the same MDC key names everywhere (`userId`, `requestId`, `orderId`), so one query finds a request across services and actors. - Keep the number of keys small; every key is copied for every message. - Never put secrets or personal data (passwords, card numbers, tokens) in MDC or tags. - Use tags for what an actor *is* (role, service, priority) and MDC for what it is *working on*. ## Troubleshooting | Symptom | Cause | |---|---| | MDC keys are empty in the output | The pattern has no `%X{key}` for them, or the line was logged outside the actor's handler (for example in a future callback) | | `requestId` missing in actor logs | Thread MDC doesn't follow messages; pass the id in the message and add it with `withMdc` | | `pekkoTags` empty | The actor was spawned without `withTags(...)`, or the pattern lacks `%X{pekkoTags}` | ## Related - [Actors](actors.md): the spawn and child builders - [Behaviors](behaviors.md): the behavior builder - [Monitoring](../operations/monitoring.md): metrics, tracing and log setup in production - [Logging example](../../examples/logging.md) - [Pekko logging](https://pekko.apache.org/docs/pekko/current/typed/logging.html) --- # Sharded Actors A sharded actor is an actor type whose instances, called **entities**, are spread over the nodes of a cluster. Each entity has an id. The cluster runs at most one entity per id at a time, starts it on its first message, and moves it when nodes join or leave. You send a message to an id from any node, and it reaches the entity wherever it runs. Use sharding when you have many things that each need their own actor: users, orders, devices, chat rooms. It spreads them over the nodes, so you scale out by adding nodes. For one actor for the whole cluster, use a [cluster singleton](singletons.md) instead. For actors that live on one node only, use regular actors ([Actors](../core/actors.md)). ## Setup Sharded actors need the cluster starter: === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-spring-boot-starter-cluster:$version") ``` === "Maven" ```xml io.github.seonwkim actor-spring-boot-starter-cluster ${actor.version} ``` Then run the actor system in cluster mode. This is the configuration of the [cluster example](../../examples/cluster.md), three nodes on one machine: ```yaml spring: actor: name: spring-pekko-example provider: cluster remote: hostname: 127.0.0.1 port: 2551 cluster: seed-nodes: - pekko://spring-pekko-example@127.0.0.1:2551 - pekko://spring-pekko-example@127.0.0.1:2552 - pekko://spring-pekko-example@127.0.0.1:2553 downing: strategy: keep-majority ``` Each node uses its own `remote.port` (2551, 2552, 2553) and the same `spring.actor.name`. See [Cluster Formation](cluster-formation.md) for joining without fixed addresses, and [Split Brain and Leases](split-brain-and-leases.md) for the downing strategy. ## Write a sharded actor Implement `SpringShardedActor` and annotate the class with `@Component`. The starter registers every sharded actor bean with the cluster when the actor system starts. === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.serialization.JsonSerializable; import io.github.seonwkim.actor.shard.ShardedEntityType; import io.github.seonwkim.actor.shard.SpringShardedActor; import io.github.seonwkim.actor.shard.SpringShardedActorContext; import org.springframework.stereotype.Component; @Component public class HelloActor implements SpringShardedActor { public static final ShardedEntityType TYPE_KEY = ShardedEntityType.of(Command.class, "HelloActor"); public interface Command extends JsonSerializable {} public static class SayHello extends AskCommand implements Command { public final String message; public SayHello(String message) { this.message = message; } } @Override public ShardedEntityType entityType() { return TYPE_KEY; } @Override public SpringActorBehavior create(SpringShardedActorContext ctx) { String entityId = ctx.getEntityId(); return SpringActorBehavior.builder(Command.class, ctx) .onMessage(SayHello.class, (behaviorCtx, msg) -> { String reply = "Received from entity [" + entityId + "] on node [" + behaviorCtx.nodeAddress() + "]"; behaviorCtx.getLog().info(reply); msg.reply(reply); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.kotlin.actorBehavior import io.github.seonwkim.actor.serialization.JsonSerializable import io.github.seonwkim.actor.shard.ShardedEntityType import io.github.seonwkim.actor.shard.SpringShardedActor import io.github.seonwkim.actor.shard.SpringShardedActorContext import org.springframework.stereotype.Component @Component class HelloActor : SpringShardedActor { companion object { val TYPE_KEY: ShardedEntityType = ShardedEntityType.of(Command::class.java, "HelloActor") } sealed interface Command : JsonSerializable class SayHello(val message: String) : AskCommand(), Command override fun entityType(): ShardedEntityType = TYPE_KEY override fun create(ctx: SpringShardedActorContext): SpringActorBehavior { val entityId = ctx.entityId return actorBehavior(ctx) .onMessage(SayHello::class.java) { behaviorCtx, msg -> val reply = "Received from entity [$entityId] on node [${behaviorCtx.nodeAddress()}]" behaviorCtx.log.info(reply) msg.reply(reply) SpringActorBehavior.same() } .build() } } ``` What differs from a regular actor: | Part | What it does | |---|---| | `ShardedEntityType.of(Command.class, "HelloActor")` | Names the entity type and its message type. Nodes reach the same entities when they use the same name, so keep it stable across deployments. | | `entityType()` | Returns that type. | | `create(SpringShardedActorContext)` | Builds the behavior of one entity, on the node that hosts it. `ctx.getEntityId()` is the entity's id (also `ctx.actorId()`), and the same `SpringActorBehavior` builder works as for a regular actor, `withState` included. | | `sharding()` | Optional: how ids map to shards. Default `ShardingStrategy.defaults()`, 100 shards. | | `role()` | Optional: the cluster role whose nodes host the entities. Default: every node. | Messages cross the network, so the command interface extends `JsonSerializable` (or `CborSerializable`), and so do the replies when they are not `String` or a number. ## Send messages `actorSystem.sharded(HelloActor.class).withId(id).get()` returns a handle to the entity with that id. Getting a handle does not start the entity and costs nearly nothing: the entity starts on its first message. === "Java" ```java @Service public class HelloService { private final SpringActorSystem actorSystem; public HelloService(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } public Mono hello(String message, String entityId) { SpringShardedActorHandle entity = actorSystem.sharded(HelloActor.class).withId(entityId).get(); CompletionStage reply = entity .ask(new HelloActor.SayHello(message)) .withTimeout(Duration.ofSeconds(3)) .onTimeout(() -> "Request timed out for entity: " + entityId) .execute(); return Mono.fromCompletionStage(reply); } } ``` === "Kotlin" ```kotlin @Service class HelloService(private val actorSystem: SpringActorSystem) { suspend fun hello(message: String, entityId: String): String { val entity = actorSystem.sharded().withId(entityId).get() return entity.ask(HelloActor.SayHello(message)) .withTimeout(3.seconds) .onTimeout { "Request timed out for entity: $entityId" } .await() } } ``` The handle has `tell`, `ask`, `entityId()` and `entityType()`. `withTimeout` on the builder sets the default ask timeout of the handle (3 seconds otherwise). There is no `spawn`, `exists` or `stop` for an entity, and no need to cache handles: get one per request. | | Regular actor | Sharded entity | |---|---|---| | Created | By you, with `spawn()` or `getOrSpawn()` | By the cluster, on its first message | | Where it runs | The node that spawned it | One node of the cluster, chosen by its shard | | How many per id | One per node | One per cluster | | Handle | From `spawn`, `get` or `getOrSpawn` | From `sharded(...).withId(id).get()`, any time | | Messages | Any Java object | Serializable (`JsonSerializable`, `CborSerializable`) | ## Shards and ids Entities are grouped into shards: a hash of the entity id picks the shard, and the cluster places whole shards on nodes. When a node joins or leaves, shards move, and their entities start again on their new node on the next message. === "Java" ```java @Override public ShardingStrategy sharding() { return ShardingStrategy.hashed(300); } ``` === "Kotlin" ```kotlin override fun sharding(): ShardingStrategy = ShardingStrategy.hashed(300) ``` - Use about ten times the largest number of nodes you expect. The default is 100. - Every node must use the same strategy for an entity type, and it must stay the same across deployments: a different number of shards sends the same id to a different shard. - Pick ids with many distinct values, such as user ids or order numbers, so the entities spread evenly. ## Run entities on some nodes only Override `role()` and give the hosting nodes that role: === "Java" ```java @Override public Optional role() { return Optional.of("backend"); } ``` === "Kotlin" ```kotlin override fun role(): Optional = Optional.of("backend") ``` ```yaml spring: actor: cluster: roles: [backend] ``` Nodes without the role still send messages to the entities, through a proxy; they just don't host any. ## State and passivation An entity's state lives in memory. It is lost when the entity stops: when its shard moves to another node, when its node stops, or when the entity is passivated. Passivation is Pekko's: an entity that receives no message for a while is stopped to free memory, and started again on its next message. Pekko's default idle timeout is 2 minutes. Change it with the raw key: ```yaml spring: actor: pekko: cluster: sharding: passivation: default-idle-strategy: idle-entity: timeout: 10m ``` When the state must survive, load it when the entity starts and save it when it changes, as in [State in a Database](../data/state-in-a-database.md), or use an [event-sourced actor](../data/event-sourcing.md). ## One entity per id, even in a split In a network split, both sides may start the same shard. A downing strategy stops one side; with `spring.actor.cluster.sharding.use-lease: true`, each shard also takes a lease before it starts its entities, so a shard never runs on two nodes. See [Split Brain and Leases](split-brain-and-leases.md#leases). ## Monitoring With `actor-metrics` and Micrometer, each node reports `actor.sharding.regions`, `actor.sharding.shards` and `actor.sharding.entities`, tagged `type` with the entity type name. The `actors` Actuator endpoint lists, for each entity type, the regions and the shards and entities on this node. See [Monitoring](../operations/monitoring.md). ## Pitfalls - **Unstable names or shard counts.** Renaming the entity type or changing the number of shards sends existing ids to other entities. Keep both fixed. - **Blocking in an entity.** Entities run on the default dispatcher. Use a non-blocking client, or hand the blocking call off and send the result back with `pipeToSelf` (see [State in a Database](../data/state-in-a-database.md#non-blocking-calls-with-r2dbc)). - **Many messages between entities.** Every message to another entity may cross the network. Keep what is used together in one entity. - **Holding state only in memory.** It is gone after passivation or a move. Store what must survive. ## Related - [Cluster example](../../examples/cluster.md): sharded actors on three nodes - [Cluster Singletons](singletons.md): one actor for the whole cluster - [Split Brain and Leases](split-brain-and-leases.md): downing and shard leases - [State in a Database](../data/state-in-a-database.md) and [Event-Sourced Actors](../data/event-sourcing.md): keep an entity's state - [Testing](../testing.md#cluster-tests-with-actorcluster): several nodes in one test --- # Cluster Singletons A cluster singleton is an actor that runs on exactly one node of the cluster. Every node can send it messages through a proxy, and when the node that runs it leaves or fails, the singleton starts again on another node. Use a singleton for work that must happen once for the whole cluster: - a coordinator that hands out work or ids, - a scheduler that runs a job every few minutes, - an aggregator that collects numbers from every node, - a cluster-wide limit, such as a rate limiter shared by all nodes. Don't use one for work that grows with your traffic. A singleton is one actor on one node: every message for it goes through that node, one at a time. For many independent things (users, orders, devices), use [sharded actors](sharded-actors.md) instead: one entity per id, spread over the nodes. ## Setup Singletons need the cluster starter and cluster mode: === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-spring-boot-starter-cluster:$version") ``` === "Maven" ```xml io.github.seonwkim actor-spring-boot-starter-cluster ${actor.version} ``` ```yaml spring: actor: name: orders provider: cluster remote: hostname: 127.0.0.1 port: 2551 cluster: seed-nodes: - pekko://orders@127.0.0.1:2551 - pekko://orders@127.0.0.1:2552 downing: strategy: keep-majority ``` See [Cluster Formation](cluster-formation.md) for how nodes find each other, and [Split Brain and Leases](split-brain-and-leases.md) for the downing strategy. ## Write the actor A singleton is a regular actor. Nothing in the class says it is a singleton: you choose that when you spawn it. Its messages cross the network, so they must be serializable (`JsonSerializable` or `CborSerializable`), the same as for sharded actors. This one is adapted from the [cluster example](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/cluster): === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.serialization.JsonSerializable; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Component; @Component public class ClusterMetricsAggregator implements SpringActor { public interface Command extends JsonSerializable {} public static class RecordMetric implements Command { public final String nodeAddress; public final String metricName; public final long value; public RecordMetric(String nodeAddress, String metricName, long value) { this.nodeAddress = nodeAddress; this.metricName = metricName; this.value = value; } } public static class GetTotal extends AskCommand implements Command { public final String metricName; public GetTotal(String metricName) { this.metricName = metricName; } } @Override public SpringActorBehavior create(SpringActorContext actorContext) { Map totals = new HashMap<>(); return SpringActorBehavior.builder(Command.class, actorContext) .onMessage(RecordMetric.class, (ctx, msg) -> { totals.merge(msg.metricName, msg.value, Long::sum); return SpringActorBehavior.same(); }) .onMessage(GetTotal.class, (ctx, msg) -> { msg.reply(totals.getOrDefault(msg.metricName, 0L)); return SpringActorBehavior.same(); }) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.kotlin.actorBehavior import io.github.seonwkim.actor.serialization.JsonSerializable import org.springframework.stereotype.Component @Component class ClusterMetricsAggregator : SpringActor { sealed interface Command : JsonSerializable class RecordMetric(val nodeAddress: String, val metricName: String, val value: Long) : Command class GetTotal(val metricName: String) : AskCommand(), Command override fun create(actorContext: SpringActorContext): SpringActorBehavior { val totals = mutableMapOf() return actorBehavior(actorContext) .onMessage(RecordMetric::class.java) { _, msg -> totals.merge(msg.metricName, msg.value, Long::plus) SpringActorBehavior.same() } .onMessage(GetTotal::class.java) { _, msg -> msg.reply(totals.getOrDefault(msg.metricName, 0L)) SpringActorBehavior.same() } .build() } } ``` ## Spawn it Call `asClusterSingleton()` on the spawn builder: === "Java" ```java SpringActorHandle aggregator = actorSystem .actor(ClusterMetricsAggregator.class) .withId("metrics-aggregator") .asClusterSingleton() .spawn() .toCompletableFuture() .get(); ``` === "Kotlin" ```kotlin // In a suspend fun or a coroutine val aggregator: SpringActorHandle = actorSystem .actor() .withId("metrics-aggregator") .asClusterSingleton() .awaitSpawn() ``` `asClusterSingleton(boolean)` does the same with a flag, for code that decides at run time. ### A handle you can use at once `spawn()` returns a `CompletionStage`, so code that may run before it completes has to hold an `Optional` or wait. `singletonHandle()` (*new in the next release*) starts the singleton the same way and returns the handle at once: === "Java" ```java SpringActorHandle aggregator = actorSystem .actor(ClusterMetricsAggregator.class) .withId("metrics-aggregator") .singletonHandle(); ``` === "Kotlin" ```kotlin val aggregator: SpringActorHandle = actorSystem .actor() .withId("metrics-aggregator") .singletonHandle() ``` Messages sent through it before the singleton runs, for example before this node has joined the cluster, wait in the proxy and are delivered once the singleton starts (up to the proxy's buffer, see [Where it runs](#where-it-runs)). It throws `IllegalStateException` outside cluster mode. What you get back is a handle to a **proxy** on this node, not to the actor itself. The proxy finds the node that runs the singleton and forwards every message there. `tell` and `ask` work as on any handle. Every node spawns the singleton with the same class and id. The class name and the id form the singleton's name (`:`), and nodes that use the same name share one singleton. Spawning it again, on the same node or another one, is safe: it returns a proxy to the same singleton and does not start a second one. The usual place is a bean that spawns it once at startup and keeps the handle: === "Java" ```java @Service public class ClusterSingletonService { private final SpringActorSystem actorSystem; private SpringActorHandle aggregator; public ClusterSingletonService(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } @PostConstruct public void init() throws Exception { aggregator = actorSystem .actor(ClusterMetricsAggregator.class) .withId("metrics-aggregator") .asClusterSingleton() .spawn() .toCompletableFuture() .get(); } public void record(String name, long value) { aggregator.tell(new ClusterMetricsAggregator.RecordMetric(actorSystem.nodeAddress(), name, value)); } public CompletionStage total(String name) { return aggregator .ask(new ClusterMetricsAggregator.GetTotal(name)) .withTimeout(Duration.ofSeconds(3)) .execute(); } } ``` === "Kotlin" ```kotlin @Service class ClusterSingletonService(private val actorSystem: SpringActorSystem) { private lateinit var aggregator: SpringActorHandle @PostConstruct fun init() { aggregator = actorSystem .actor() .withId("metrics-aggregator") .asClusterSingleton() .spawn() .toCompletableFuture() .get() } fun record(name: String, value: Long) { aggregator.tell(ClusterMetricsAggregator.RecordMetric(actorSystem.nodeAddress(), name, value)) } suspend fun total(name: String): Long = aggregator.awaitAsk(ClusterMetricsAggregator.GetTotal(name), timeout = 3.seconds) } ``` The proxy stays valid for the life of the node, also when the singleton moves. Keep it and reuse it. The other spawn settings apply to the singleton: `withSupervisionStrategy`, the dispatcher (`withBlockingDispatcher()`, `withDispatcherFromConfig(...)`), the mailbox and tags. !!! warning "`find` and `exists` see only singletons this node spawned" `actorSystem.find(...)` and `exists(...)` find a singleton on the nodes that called `spawn()` with `asClusterSingleton()` for it. On another node they report no actor: call `spawn()` with `asClusterSingleton()` there too (it is idempotent), or `getOrSpawn()`. A child actor can't be a singleton: only actors spawned from `SpringActorSystem` can. In local mode (`spring.actor.provider` not `cluster`), the stage returned by `spawn()` fails with `IllegalStateException`: "Cluster singleton requested but cluster mode is not enabled. Set spring.actor.provider=cluster and depend on io.github.seonwkim:actor-spring-boot-starter-cluster." ### Stopping `stop()` on a singleton's handle throws `UnsupportedOperationException`, and the singleton and the handle keep working. The handle is this node's proxy: stopping it would not stop the singleton, only cut this node off from it, and every later `spawn()` on the node would get the same stopped proxy back. A singleton runs as long as the cluster does. ## Where it runs The singleton runs on the **oldest member** of the cluster whose status is `Up`: the node that joined first. The other nodes run only a proxy. | When | What happens | |---|---| | A node joins | Nothing. The oldest node keeps the singleton. | | The host shuts down gracefully (`SIGTERM`, `context.close()`) | It leaves the cluster, the singleton stops there and starts on the next oldest node. | | The host crashes or stops answering | The singleton starts on another node only after the host is downed and removed. That needs a downing strategy; without one, the singleton waits until you remove the node by hand. | | No node is `Up` yet | Messages wait in the proxy until a host is up. | While the singleton moves, the proxies keep the messages sent to it and deliver them once the new instance runs. Pekko's proxy keeps up to 1000 messages per node and drops what doesn't fit; set `spring.actor.pekko.cluster.singleton-proxy.buffer-size` to change it. An `ask` whose reply doesn't come back in time fails with its timeout, or returns its `onTimeout` value. ### State is lost when it moves The new instance is a new actor: it starts from `create(...)` with empty state. In the example above, the totals start again from zero. If the singleton must keep its state, store it: - load it in `withState(...)` from a table and save it after each change, as in [State in a Database](../data/state-in-a-database.md), or - make the singleton an [event-sourced actor](../data/event-sourcing.md), which rebuilds its state from its stored events wherever it starts. ### Limit it to some nodes To run singletons only on some nodes, give those nodes a role with `spring.actor.cluster.roles` and set `spring.actor.cluster.singleton.role` on **every** node: ```yaml # Nodes that may run singletons spring: actor: cluster: roles: [backend] singleton: role: backend ``` ```yaml # Other nodes: no role, same singleton.role spring: actor: cluster: singleton: role: backend ``` The singleton then runs on the oldest `Up` node with that role. Every node still gets a proxy, and the nodes without the role still spawn it, as in [Spawn it](#spawn-it). Set the same `singleton.role` on every node, so all proxies look for the same host. The role applies to every singleton of the application, including the ones the starter starts for [projections](../data/projections.md). | Key | Default | Meaning | |---|---|---| | `spring.actor.cluster.singleton.role` | none | Singletons run only on nodes with this role. Sets Pekko's `pekko.cluster.singleton.role`. | A sharded actor picks its role in code (`role()` on the actor, see [Sharded Actors](sharded-actors.md#run-entities-on-some-nodes-only)). A singleton's role is one setting for the node instead, because Pekko places all singletons of a node by the same role and the `actor.cluster.singleton.host` gauge reports one host for all of them. ## Leases: never two at once A singleton runs on one node only as long as the nodes agree on who is in the cluster. In a network split, each side may see itself as the oldest and start its own singleton. The [downing strategy](split-brain-and-leases.md#downing-strategy) stops one side, but it takes some time. When two copies would do harm (two schedulers sending the same email, two coordinators handing out the same id), turn on the singleton lease: ```yaml spring: actor: cluster: singleton: use-lease: true lease: store: jdbc # or redis, or custom (your LeaseStore bean) ``` The singleton then starts only after it takes its lease from the store, and stops when it loses it. A node that can't get the lease keeps retrying, and the singleton does not run on that node meanwhile. Each singleton has its own lease; its name starts with `-singleton-` and ends with the singleton's name, such as `orders-singleton-...:metrics-aggregator`. The owner is the node address. | Key | Default | Meaning | |---|---|---| | `spring.actor.cluster.singleton.use-lease` | `false` | A singleton runs only while it holds its lease. | | `spring.actor.cluster.lease.store` | none | Where leases live: `jdbc`, `redis` or `custom`. Required with `use-lease`. | | `spring.actor.cluster.lease.ttl` | `120s` | How long a lease stays held after its last renewal. | | `spring.actor.cluster.lease.renew-interval` | `12s` | How often the holder renews it. | | `spring.actor.cluster.lease.expiry-margin` | `10s` | The holder stops this long before the ttl runs out. | The ttl also bounds how long a singleton can stay down after a crash: another node can take the lease only once the crashed node's lease has expired. Pekko's `spring.actor.pekko.cluster.singleton.lease-retry-interval` sets how often a node retries a refused lease. With `store: redis`, a lease can be lost in a Redis failover, and two nodes can hold it for a moment. Use `jdbc` when a singleton must never run twice. See [Leases](split-brain-and-leases.md#leases) for the stores, the tables and your own `LeaseStore`. ## See where it runs With `actor-metrics` and Micrometer, every node reports the gauge `actor.cluster.singleton.host`: `1` on the node that runs the singletons, `0` on the others. Summed over the nodes it should be `1`. The Prometheus rules in [`monitoring/`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/monitoring) alert with `ActorClusterSingletonMissing` when the sum stays below `1` for 5 minutes. The gauge means "this node is the oldest `Up` member with the singleton role" (any member when `singleton.role` is not set). It does not look at the lease: with `use-lease`, the host it names may still be waiting for its lease. The `actors` Actuator endpoint (`/actuator/actors`, when exposed) shows the same flag in this node's view of the cluster. ## Singletons the starter starts Each [projection](../data/projections.md) runs as a cluster singleton in cluster mode, so one node handles its events. Its singleton is named `projection-`. ## Pitfalls - **One node does all the work.** Keep the work a singleton does small, or have it hand work out to sharded entities or routers. - **Blocking calls.** A singleton that calls a database or an HTTP service should run on the blocking dispatcher (`withBlockingDispatcher()`), like any blocking actor. - **Downing turned off.** With `downing.strategy: none`, a crashed host keeps the singleton until someone removes the node. The starter logs a warning at startup. - **Different ids on different nodes.** Nodes that spawn with another id start another singleton. - **State in memory.** It is gone when the singleton moves. Store what must survive. ## Related - [Sharded Actors](sharded-actors.md): one actor per id, spread over the nodes - [Split Brain and Leases](split-brain-and-leases.md): downing strategies and lease stores - [Cluster Formation](cluster-formation.md): how nodes join - [Cluster example](../../examples/cluster.md): a singleton aggregator you can run on three nodes and fail over - [Monitoring](../operations/monitoring.md): the cluster meters and alerts --- # Cluster Formation A node joins a cluster in one of two ways, set by `spring.actor.cluster.join`: | `join` | How the node finds the cluster | Use it when | |---|---|---| | `seed-nodes` (default) | The addresses in `spring.actor.cluster.seed-nodes` | Nodes have fixed addresses | | `discovery` | Peers found through `spring.actor.cluster.discovery.method`, then Pekko Cluster Bootstrap forms or joins the cluster | Nodes come and go with changing addresses (Kubernetes, autoscaling groups) | ## Joining through a store you already run With `discovery.method` set to `jdbc` or `redis`, each node writes its own entry to a table or a Redis key, and reads the others' entries to find its peers. This needs no Kubernetes API access (no RBAC) and no DNS setup: only the store the application already uses, and network access between the nodes. What each node does: 1. At startup it registers itself (its management host and the port its management server bound) and starts Cluster Bootstrap. 2. Every `heartbeat-interval` (default `5s`) it renews its entry. 3. Bootstrap lists the entries renewed within `ttl` (default `30s`), contacts those nodes on their management port, and either joins the cluster they are in or, if there is none yet, the node with the lowest address forms it. 4. On a graceful shutdown it deletes its entry first, so new nodes no longer contact it. A node that crashes stops renewing, and its entry is ignored once it is older than the ttl. Times come from the store's clock (the database's `CURRENT_TIMESTAMP`, Redis `TIME`), so the nodes' clocks need not agree. ### Dependencies Discovery uses Pekko Cluster Bootstrap and the management HTTP server, plus the module of your store. With the [BOM](../../getting-started.md#several-modules-import-the-bom) imported, leave out their versions: it manages the Pekko Management modules at the version the starter is built with (*new in the next release*; with 1.1.0, add `:1.1.1` to each): === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-spring-boot-starter-cluster") implementation("org.apache.pekko:pekko-management-cluster-bootstrap_3") implementation("org.apache.pekko:pekko-management-cluster-http_3") implementation("io.github.seonwkim:actor-jdbc") // or actor-redis ``` === "Maven" ```xml io.github.seonwkim actor-spring-boot-starter-cluster org.apache.pekko pekko-management-cluster-bootstrap_3 org.apache.pekko pekko-management-cluster-http_3 io.github.seonwkim actor-jdbc ``` `kubernetes-api` discovery also needs `org.apache.pekko:pekko-discovery-kubernetes-api_3`, which the BOM manages too. `actor-jdbc` uses the application's `DataSource` (or [one of its own](#a-separate-datasource)), and `actor-redis` its `RedisConnectionFactory` (`spring-boot-starter-data-redis`). ### JDBC ```yaml spring: datasource: url: jdbc:postgresql://db:5432/orders actor: name: orders provider: cluster cluster: join: discovery discovery: method: jdbc jdbc: initialize-schema: always # default: embedded (only H2, HSQLDB, Derby) pekko: management: http: port: 7626 ``` The entries live in the `actor_peer` table. `spring.actor.jdbc.initialize-schema` decides when the starter creates it: `embedded` (the default) only in an embedded database, `always`, or `never`. With `never`, create it yourself, for example in a Flyway or Liquibase migration, from the schema file for your database in the `actor-jdbc` jar: `io/github/seonwkim/actor/jdbc/schema-{h2,postgresql,mysql,mariadb}.sql`. With `always`, nodes that start together each run the script. On PostgreSQL they take an advisory lock first and create the tables one at a time, since concurrent `CREATE TABLE IF NOT EXISTS` fails there. For production, prefer `never` with a migration (Flyway, Liquibase or a one-off job), so the application's database user needs no `CREATE` rights. ```sql CREATE TABLE IF NOT EXISTS actor_peer ( service_name VARCHAR(200) NOT NULL, node_id VARCHAR(500) NOT NULL, host VARCHAR(255) NOT NULL, port INT NOT NULL, last_seen BIGINT NOT NULL, PRIMARY KEY (service_name, node_id) ); ``` A node that crashes leaves its row behind; it is ignored once it is older than the ttl, and you can delete old rows at any time. `last_seen` holds the database's time in epoch milliseconds, so nodes in different time zones compare it alike. Tables created by 1.1.0 or earlier have `last_seen TIMESTAMP` (and `actor_lease.expires_at TIMESTAMP(3)`): stop the nodes, drop `actor_peer` and `actor_lease`, and let them be created again. Both hold only live entries, which the nodes write again within a heartbeat. #### A separate `DataSource` By default the JDBC stores (peers, leases, generations) and the [event journal](../data/event-sourcing.md) share the application's `DataSource` and its pool. To give them a database, a user or a pool of their own, declare a `DataSource` bean marked `@ActorDataSource` (*new in the next release*): ```java import com.zaxxer.hikari.HikariDataSource; import io.github.seonwkim.actor.ActorDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class ActorDatabaseConfig { // defaultCandidate = false: Spring Boot still creates the application's DataSource from spring.datasource.* @Bean(defaultCandidate = false) @ActorDataSource @ConfigurationProperties("actor.datasource") HikariDataSource actorDataSource() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } } ``` ```yaml actor: datasource: jdbc-url: jdbc:postgresql://db:5432/actors username: actors password: ${ACTOR_DB_PASSWORD} maximum-pool-size: 5 ``` The starter then creates its tables there, the journal's threads match that pool, and lease renewals and heartbeats no longer compete with the application's queries for a connection. Projections stay on the application's `DataSource`, because a projection writes its offset in the same transaction as its read model. ### Redis ```yaml spring: data: redis: host: redis actor: name: orders provider: cluster cluster: join: discovery discovery: method: redis ``` Each node is a hash under `actor:peer::` that expires after the ttl, so a crashed node's entry removes itself. The starter reads the keys with `SCAN`, which sees one server: use a single Redis or a primary with replicas (Sentinel), not Redis Cluster. ### Your own store Implement `io.github.seonwkim.actor.spi.PeerRegistry` (in `actor-api`, no Pekko types) and declare it as a bean. Set `discovery.method: custom`. A `PeerRegistry` bean of your own also replaces the `jdbc` and `redis` stores. === "Java" ```java @Bean PeerRegistry peerRegistry(MyStore store) { return new PeerRegistry() { public void register(Peer peer) { store.upsert(peer); } // also marks it seen now public void deregister(Peer peer) { store.delete(peer); } public List peers(String service, Duration ttl) { return store.seenWithin(service, ttl); } }; } ``` === "Kotlin" ```kotlin @Bean fun peerRegistry(store: MyStore): PeerRegistry = object : PeerRegistry { override fun register(peer: Peer) = store.upsert(peer) // also marks it seen now override fun deregister(peer: Peer) = store.delete(peer) override fun peers(service: String, ttl: Duration): List = store.seenWithin(service, ttl) } ``` `MyStore` stands for your own storage code. A `Peer` is the service name, the node id, and the management host and port. `heartbeat(peer)` runs every `heartbeat-interval` and calls `register` unless you override it. Methods may block: the starter calls them on the blocking dispatcher. The starter owns the timers and the shutdown hook; a store only stores and reads entries. Run `PeerRegistryContract` from `actor-test` against your store to check it behaves like the built-in ones (see [Testing](../testing.md#contract-suites-for-your-own-store)). ## Other discovery methods `discovery.method` also accepts Pekko's own methods. Each needs its library and its Pekko settings: | `method` | Pekko method | Library | |---|---|---| | `kubernetes-api` | `kubernetes-api` | `pekko-discovery-kubernetes-api_3` (the pods' service account needs RBAC to list pods) | | `dns` | `pekko-dns` | built in | | `config` | `config` | built in; peers under `spring.actor.pekko.discovery.config.services` | ## Who is in the cluster `actorSystem.cluster()` (*new in the next release*) tells a node who it is and who is in the cluster now: === "Java" ```java ClusterMember me = actorSystem.cluster().self(); List up = actorSystem.cluster().members().stream() .filter(member -> member.status() == MemberStatus.UP) .toList(); ``` === "Kotlin" ```kotlin val me: ClusterMember = actorSystem.cluster().self() val up = actorSystem.cluster().members().filter { it.status() == MemberStatus.UP } ``` - `self()` is this node: its address, its roles and its status. - `members()` lists the members this node sees, in every status, oldest first. A node that left drops out once it is removed. - Each call reads the current state. To react to changes, listen for `ClusterEvent`s instead (`@EventListener void on(ClusterEvent.MemberUp event)`). - `ClusterMember.host()` and `port()` read the host and port from the address (`::1`, without brackets, for `pekko://app@[::1]:25520`). - Outside cluster mode, `self()` is this node with the address `nodeAddress()` returns, status `UP` and no roles, and `members()` lists only it. To tell nodes apart in your own code, give each one a role and read it back, rather than working it out from its port or address: ```yaml spring: actor: cluster: roles: [zone-a] ``` ```java boolean inZoneA = actorSystem.cluster().self().roles().contains("zone-a"); ``` The roles also include one that Pekko adds for the node's data center (`dc-default`), so check for the role you set rather than comparing the whole set. ## Properties | Key | Default | Meaning | |---|---|---| | `spring.actor.cluster.join` | `seed-nodes` | `seed-nodes` or `discovery` | | `spring.actor.cluster.seed-nodes` | none | Addresses to join, as `pekko://@:` | | `spring.actor.cluster.discovery.method` | none | `jdbc`, `redis`, `custom`, `kubernetes-api`, `dns` or `config` | | `spring.actor.cluster.discovery.heartbeat-interval` | `5s` | How often a node renews its entry | | `spring.actor.cluster.discovery.ttl` | `30s` | Entries older than this are ignored | | `spring.actor.cluster.discovery.service-name` | `spring.actor.name`, or `-` (see below) | The name entries are stored and looked up under | | `spring.actor.cluster.join-self` | `false` | Form a one-node cluster without seed nodes, for local runs and tests | | `spring.actor.cluster.roles` | none | Roles of this node, for [sharded actors](sharded-actors.md#run-entities-on-some-nodes-only) and [singletons](singletons.md#limit-it-to-some-nodes) | | `spring.actor.jdbc.initialize-schema` | `embedded` | When to create `actor_peer` and `actor_lease`: `embedded`, `always`, `never` | ## What the nodes need - **Management port** (Pekko's default `7626`, `spring.actor.pekko.management.http.port`): Bootstrap contacts peers there. `spring.actor.pekko.management.http.hostname` must be an address other nodes can reach (the default is the machine's address). With `jdbc` or `redis` discovery the port may be `0`: the node registers the port it bound. - **Remoting port** (`spring.actor.remote.port`, default `25520`) between all nodes. Other nodes reach this one at `spring.actor.remote.hostname`. When that is not an address on the host, such as a StatefulSet pod's DNS name that may not resolve yet at startup, NAT or a load balancer, set `spring.actor.remote.bind-hostname: 0.0.0.0` (*new in the next release*) so the node listens on every interface (`bind-port` likewise when the port is mapped). - **The store** (database or Redis) from every node. - The nodes of one cluster use the same `spring.actor.name`: it is the service name their entries are stored under. With `spring.actor.generation.color` set, `jdbc`, `redis` and `custom` store them under `-` (`orders-blue`, `orders-green`), so the two colors of a [blue-green deployment](../operations/deployments.md#blue-green) can share the store and still form separate clusters. `spring.actor.cluster.discovery.service-name` sets the name yourself. The Kubernetes example has ready-made overlays for both stores, with the NetworkPolicies: see `example/kubernetes/overlays/discovery-jdbc` and `discovery-redis` and the "Without RBAC" section of its README. Bootstrap waits for `pekko.management.cluster.bootstrap.contact-point-discovery.required-contact-point-nr` (default `2`) peers before it forms a new cluster. Set it to `1` for a single replica. With `join: discovery`, the split brain resolver defaults to `keep-majority`. To choose another strategy, or to keep singletons and shards on one node with a lease, see [Split Brain and Leases](split-brain-and-leases.md). ## Securing the discovery store With `jdbc` or `redis` discovery, the store decides which hosts a new node contacts and joins: Bootstrap trusts every entry it reads. Leases in the same store ([Split Brain and Leases](split-brain-and-leases.md#leases)) decide which node may run a singleton or a shard, or stays up after a split. So whoever can write `actor_peer`, `actor_lease` or the `actor:peer:` and `actor:lease:` keys can point new nodes at a host they control, or take a lease. Treat the store as part of the cluster's trust boundary: only the nodes write to it. Remoting (`25520`) accepts any connection unless you set up Pekko's TLS transport (`spring.actor.pekko.remote.artery.transport: tls-tcp` and its `ssl` settings), and the management port (`7626`) has no authentication. So the store's permissions and the network rules (only the cluster's nodes reach these ports) are the controls. **Redis.** Give the nodes a dedicated ACL user that can touch only the starter's keys and run only the commands the stores use: ```text ACL SETUSER actor-store on >change-me resetkeys ~actor:peer:* ~actor:lease:* resetchannels -@all +@connection +time +scan +hgetall +get +set +del +eval +evalsha +hset +pexpire ``` - `HSET`, `PEXPIRE`, `GET` and `DEL` also run inside the stores' Lua scripts, and Redis checks a script's commands against the same ACL. - Turn on TLS (`spring.data.redis.ssl.enabled: true`) and auth (`spring.data.redis.username`, `password`). - Don't share the Redis database with untrusted writers. `SCAN` lists key names of the whole database, whatever the user's key patterns. **JDBC.** Give the nodes a database user with rights only on the two tables, and create the tables from your migrations with another user (`spring.actor.jdbc.initialize-schema: never`): ```sql -- PostgreSQL CREATE ROLE actor_store LOGIN PASSWORD 'change-me'; GRANT SELECT, INSERT, UPDATE, DELETE ON actor_peer, actor_lease TO actor_store; -- MySQL / MariaDB (orders is the schema) CREATE USER 'actor_store'@'%' IDENTIFIED BY 'change-me'; GRANT SELECT, INSERT, UPDATE, DELETE ON orders.actor_peer TO 'actor_store'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE ON orders.actor_lease TO 'actor_store'@'%'; ``` No user that untrusted code can reach (another service, a reporting tool, an admin console) should be able to write these tables. The built-in stores use the application's `DataSource` and `RedisConnectionFactory`, so these rights are the rights of the user the application connects as. If the application needs more rights on the same server, give the stores their own connection. For JDBC, declare an [`@ActorDataSource`](#a-separate-datasource) connecting as a user with only these rights. For Redis, declare `PeerRegistry` and `LeaseStore` beans built on a separate `RedisConnectionFactory` (`new RedisPeerRegistry(connectionFactory, ttl)`, `new RedisLeaseStore(connectionFactory)`) and set `discovery.method: custom` and `lease.store: custom` (see [Your own store](#your-own-store)). ## Related - [Split Brain and Leases](split-brain-and-leases.md): what happens when nodes lose each other - [Sharded Actors](sharded-actors.md) and [Cluster Singletons](singletons.md): what runs on the cluster - [Kubernetes example](../../examples/kubernetes.md): discovery overlays and network policies - [Testing](../testing.md#cluster-tests-with-actorcluster): several nodes in one JVM --- # Split Brain and Leases When nodes stop hearing from each other (a network split, a long GC pause, a crashed machine), each side sees the other as unreachable. Without a decision, both sides keep running: a cluster singleton and a sharded entity can then run twice, once on each side. A **downing strategy** (Pekko's split brain resolver) decides which side stays and which side stops. A **lease** adds a lock in a store both sides can reach, so only one side can hold it. ## Downing strategy Set `spring.actor.cluster.downing.strategy`: | `strategy` | Which side stays | |---|---| | `keep-majority` | The side with more nodes; on a tie, the side with the lowest address. | | `lease-majority` | The side that takes the lease in `spring.actor.cluster.lease.store`. The bigger side tries first. | | `static-quorum` | A side with at least `downing.quorum-size` nodes. Set it above half the cluster's size. | | `keep-oldest` | The side with the oldest node. | | `down-all` | No side: all nodes stop. | | `none` | No downing. Unreachable nodes stay members until removed by hand. | The default is `keep-majority` (*new in the next release for clusters joined through seed nodes; 1.1.0 left them without downing*). Setting `none` logs a warning at startup: a crashed node then stays an unreachable member, and its shards and singletons wait until someone removes it. A node that is downed leaves the cluster and its actor system stops; with the default `spring.actor.shutdown.exit-process: true`, the process exits too, and your platform (Kubernetes, systemd) starts it again as a fresh node. ```yaml spring: actor: provider: cluster cluster: downing: strategy: keep-majority ``` `keep-majority` needs no store, but on an even split (2 and 2) only the lowest address decides. When the store is reachable from both sides, `lease-majority` decides by who takes the lease instead. ## Leases A lease is a lock with an owner and an expiry, kept in a store. The holder renews it; when it stops renewing, another node can take it after the lease's ttl. Three things can use one: | Setting | Lease | Effect | |---|---|---| | `downing.strategy: lease-majority` | one per cluster | Only the side that takes it stays up. | | `singleton.use-lease: true` | one per cluster singleton | A singleton starts only after it takes its lease, so it never runs on two nodes. See [Cluster Singletons](singletons.md#leases-never-two-at-once). | | `sharding.use-lease: true` | one per shard | A shard starts its entities only after it takes its lease. | Each needs `spring.actor.cluster.lease.store`: | `store` | Where leases live | Module | |---|---|---| | `jdbc` | The `actor_lease` table on the application's `DataSource`, or on [its own](cluster-formation.md#a-separate-datasource) | `actor-jdbc` | | `redis` | Keys with a TTL on the application's `RedisConnectionFactory` | `actor-redis` | | `custom` | Your `LeaseStore` bean | none | Whoever can write the lease store can take a lease, so the store is part of the cluster's trust boundary. See [Securing the discovery store](cluster-formation.md#securing-the-discovery-store) for the Redis ACL and the database grants. ```yaml spring: actor: provider: cluster jdbc: initialize-schema: always # creates actor_peer and actor_lease cluster: downing: strategy: lease-majority lease: store: jdbc singleton: use-lease: true sharding: use-lease: true ``` Timings: | Key | Default | Meaning | |---|---|---| | `lease.ttl` | `120s` | How long a lease stays held after its last renewal before another node may take it. | | `lease.renew-interval` | `12s` | How often the holder renews it. Keep it well under the ttl. | | `lease.expiry-margin` | `10s` | The holder treats the lease as lost this long before the ttl runs out, so it stops before another node can take over. Must be less than `ttl`. | Times come from the store's clock (the database's `CURRENT_TIMESTAMP`, Redis `TIME`). The holder also counts the ttl on its own clock from the last successful renewal: if the store is unreachable until then (minus the margin), it gives the lease up. A singleton or shard whose lease is lost stops. Lease names: `-pekko-sbr` for the downing lease, `-singleton-` for a singleton and `-shard--` for a shard, where `` is `spring.actor.name`. The owner is `@:` of the holding node. ### When the lease store is down With leases, the store is needed while the cluster runs, not only when it forms. What a store outage does depends on what uses the lease: | Uses | Outage shorter than `ttl` minus `expiry-margin` (110 s by default) | Longer outage | |---|---|---| | `singleton.use-lease` | Nothing: renewals fail, and the holder keeps its lease and its singleton. | Each singleton stops on every node. Pekko retries the lease every 5 s, and the singleton starts again once the store answers. | | `sharding.use-lease` | Nothing, as for singletons. | Every shard stops with its entities, on every node. Each retries its lease every 5 s and starts again once the store answers. | `downing.strategy: lease-majority` takes its lease only when a node becomes unreachable and the downing strategy has to decide. If that happens while the store is down, no side can take the lease and every side downs itself: the whole cluster stops, however short the outage. So with `singleton.use-lease` and `sharding.use-lease`, the cluster's uptime is at most the store's. A singleton or entity that stops loses its in-memory state; keep what must survive in a database or an event journal ([State in a Database](../data/state-in-a-database.md)). To limit the effect: - Use a lease only where running twice is worse than not running. Without one, a singleton or shard keeps running through a store outage. `keep-majority` needs no store. - Raise `lease.ttl` to ride out longer outages. The cost: when a holder crashes, another node waits up to the ttl to take its lease, so its singletons and shards are down that long. - Run the store with failover that completes within the ttl minus the margin. ### JDBC `actor_lease` is created together with `actor_peer` when `spring.actor.jdbc.initialize-schema` is `always` (or `embedded` with an embedded database). With `never`, create it from the schema file for your database in the `actor-jdbc` jar: `io/github/seonwkim/actor/jdbc/schema-{h2,postgresql,mysql,mariadb}.sql`. ```sql CREATE TABLE IF NOT EXISTS actor_lease ( lease_name VARCHAR(500) NOT NULL, owner VARCHAR(500) NOT NULL, expires_at BIGINT NOT NULL, PRIMARY KEY (lease_name) ); ``` Taking a lease is one conditional `UPDATE` (free, expired or already ours), then an `INSERT` if no row exists. The primary key makes only one of two concurrent inserts succeed. ### Redis A lease is a key `actor:lease:` set with `SET NX PX`; renew and release check the owner first. Redis replicates to replicas asynchronously: if the primary fails right after a node took a lease, the new primary may not have the key, and a second node can take it. Use the JDBC store, or a Redis without failover, when a singleton must never run twice. ### Your own store Implement `io.github.seonwkim.actor.spi.LeaseStore` (in `actor-api`, no Pekko types), declare it as a bean and set `lease.store: custom`. A `LeaseStore` bean of your own also replaces the `jdbc` and `redis` stores. The interface: ```java public interface LeaseStore { boolean tryAcquire(String lease, String owner, Duration ttl); // free, expired or already ours boolean renew(String lease, String owner, Duration ttl); // only while we hold it void release(String lease, String owner); // only if we hold it Optional holder(String lease); // the current, unexpired owner } ``` An implementation, as a bean: === "Java" ```java import io.github.seonwkim.actor.spi.LeaseStore; import java.time.Duration; import java.util.Optional; import org.springframework.stereotype.Component; @Component public class MyLeaseStore implements LeaseStore { private final MyLeaseTable table; // your own storage code public MyLeaseStore(MyLeaseTable table) { this.table = table; } @Override public boolean tryAcquire(String lease, String owner, Duration ttl) { return table.insertOrTakeOver(lease, owner, ttl); // one atomic statement } @Override public boolean renew(String lease, String owner, Duration ttl) { return table.extendIfOwner(lease, owner, ttl); } @Override public void release(String lease, String owner) { table.deleteIfOwner(lease, owner); } @Override public Optional holder(String lease) { return table.unexpiredOwner(lease); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.spi.LeaseStore import java.time.Duration import java.util.Optional import org.springframework.stereotype.Component @Component class MyLeaseStore(private val table: MyLeaseTable) : LeaseStore { // MyLeaseTable: your own storage code override fun tryAcquire(lease: String, owner: String, ttl: Duration): Boolean = table.insertOrTakeOver(lease, owner, ttl) // one atomic statement override fun renew(lease: String, owner: String, ttl: Duration): Boolean = table.extendIfOwner(lease, owner, ttl) override fun release(lease: String, owner: String) = table.deleteIfOwner(lease, owner) override fun holder(lease: String): Optional = table.unexpiredOwner(lease) } ``` `Duration` is `java.time.Duration` in both. Each method must be atomic in the store. Methods may block: the starter calls them on the lease's own four threads (`spring-actor.lease-dispatcher`), not on Pekko's blocking pool, so the application's blocking work cannot hold up a renewal. It owns the renewal timers, and counts a lease lost at its deadline on another thread, so a hung store call cannot delay that either. Run `LeaseStoreContract` from `actor-test` against your store to check it (see [Testing](../testing.md#contract-suites-for-your-own-store)). ## Related - [Cluster Singletons](singletons.md): what a singleton lease protects - [Sharded Actors](sharded-actors.md): what a shard lease protects - [Cluster Formation](cluster-formation.md): `actor-jdbc` and `actor-redis` also find peers - [Production](../operations/production.md): graceful shutdown, so a leaving node is never downed --- # Replicated Data Replicated data is a map, a counter or a set that every node of the cluster keeps a copy of. Any node reads and writes its own copy without a round trip, and the copies converge: changes made on different nodes at the same time are merged, never lost. These are Pekko Distributed Data's CRDTs (conflict-free replicated data types) behind a small API with no Pekko types. Use it for small, shared, often-read state: feature flags, who is online, rate-limit counters, a cache of settings. It is not a database: the data lives in memory and is gone when every node stops. ## Setup Replicated data needs the cluster starter and cluster mode: ```yaml spring: actor: provider: cluster ``` The starter then provides a `ReplicatedData` bean. Each node starts Pekko's replicator when its actor system starts. ## Maps, counters and sets `ReplicatedData` hands out a handle per name. Declare the handles you use as beans and inject them where you need them: === "Java" ```java import io.github.seonwkim.actor.ddata.ReplicatedCounter; import io.github.seonwkim.actor.ddata.ReplicatedData; import io.github.seonwkim.actor.ddata.ReplicatedMap; import io.github.seonwkim.actor.ddata.ReplicatedSet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class ReplicatedDataConfig { @Bean ReplicatedMap carts(ReplicatedData data) { return data.map("carts"); } @Bean ReplicatedCounter visits(ReplicatedData data) { return data.counter("visits"); } @Bean ReplicatedSet onlineUsers(ReplicatedData data) { return data.set("online-users"); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.ddata.ReplicatedCounter import io.github.seonwkim.actor.ddata.ReplicatedData import io.github.seonwkim.actor.ddata.ReplicatedMap import io.github.seonwkim.actor.ddata.ReplicatedSet import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class ReplicatedDataConfig { @Bean fun carts(data: ReplicatedData): ReplicatedMap = data.map("carts") @Bean fun visits(data: ReplicatedData): ReplicatedCounter = data.counter("visits") @Bean fun onlineUsers(data: ReplicatedData): ReplicatedSet = data.set("online-users") } ``` Or inject `ReplicatedData` and ask for a handle when the name is only known at run time, such as one counter per tenant: `data.counter("requests-" + tenantId)`. A handle is a cheap view: two handles with the same name and kind read and write the same data. Use each name for one kind only. Every read and write returns a `CompletionStage`: === "Java" ```java @Service class CartService { private final ReplicatedMap carts; CartService(ReplicatedMap carts) { this.carts = carts; } CompletionStage save(String user, Cart cart) { return carts.put(user, cart); } CompletionStage> find(String user) { return carts.get(user); } } ``` === "Kotlin" ```kotlin @Service class CartService(private val carts: ReplicatedMap) { // await() is kotlinx.coroutines.future.await (kotlinx-coroutines-core, which actor-kotlin brings) suspend fun save(user: String, cart: Cart) { carts.put(user, cart).await() } suspend fun find(user: String): Cart? = carts.get(user).await().orElse(null) } ``` | Type | Reads | Writes | When two nodes write at once | |---|---|---|---| | `ReplicatedMap` | `entries()`, `get(key)` | `put(key, value)`, `remove(key)` | The later write to a key wins, by wall clock | | `ReplicatedCounter` | `value()` | `increment(delta)`, `decrement(delta)` | Both changes count | | `ReplicatedSet` | `elements()` | `add(element)`, `remove(element)` | An add wins over a concurrent remove | A map, counter or set nobody has written yet reads as empty (or zero). ## Consistency Each read and write takes an optional `Consistency`: how many nodes to wait for. | `Consistency` | Waits for | Use it when | |---|---|---| | `local()` (default) | This node only | Fast reads and writes; other nodes see the change shortly after, in the background | | `majority(timeout)` | More than half of the nodes | A write followed by a read on another node must see it | | `all(timeout)` | Every node | Rarely: one unreachable node makes it fail | === "Java" ```java Consistency majority = Consistency.majority(Duration.ofSeconds(3)); carts.put("alice", cart, majority); // on node A carts.get("alice", majority); // on node B: sees the write ``` === "Kotlin" ```kotlin val majority = Consistency.majority(Duration.ofSeconds(3)) carts.put("alice", cart, majority) // on node A carts.get("alice", majority) // on node B: sees the write ``` A majority write followed by a majority read always sees the write, because the two majorities share at least one node. If the nodes don't answer within the timeout, the stage completes with `ReplicationTimeoutException`. A write that times out is still applied on this node and spreads to the others later; it is not rolled back. ## What can be stored Keys, values and set elements travel between nodes, so they must be serializable: `String`, `Integer`, `Long`, or a type that implements `JsonSerializable` or `CborSerializable`, the same as actor messages. Values that implement `JsonSerializable` use the starter's Jackson mapper, or your application's `ObjectMapper` with `spring.actor.serialization.application-object-mapper: true`. === "Java" ```java public record Cart(List items, int quantity) implements JsonSerializable {} ``` === "Kotlin" ```kotlin data class Cart(val items: List, val quantity: Int) : JsonSerializable ``` ## Limits - **Small data.** Each node holds every entry, a new node receives all of them, and a change can send a whole map or set to the other nodes. Keep each one to thousands of entries, not millions; split big data over several names. - **In memory.** The data survives a node restart while other nodes keep it, and is lost when all nodes stop. Keep the source of truth in a database. - **Clock skew.** A map decides concurrent writes to the same key by wall clock, so keep the nodes' clocks in sync (NTP). ## Tuning Pekko's settings under `pekko.cluster.distributed-data` apply through the raw override, for example a shorter gossip interval: ```yaml spring: actor: pekko: cluster: distributed-data: gossip-interval: 1s ``` ## Related - [Pub/Sub Topics](../core/pub-sub-topics.md): send messages to every subscriber instead of sharing state - [Sharded Actors](sharded-actors.md): one owner per key, for state that must not merge - [Cluster Formation](cluster-formation.md): forming the cluster the data is replicated over --- # State in a Database An actor's fields live in memory. They are lost when the actor stops: after a restart of the application, a deploy, a passivated or moved [sharded entity](../cluster/sharded-actors.md), or a [singleton](../cluster/singletons.md) that moves to another node. To keep the state, store it in your database with the tools you already use: Spring Data JPA, `JdbcTemplate`, R2DBC. The pattern is simple: the actor **loads** its state when it starts and **saves** it in the message handler that changes it. Actors are Spring beans, so repositories and services are injected into them like into any other bean. No module of the starter is needed for this. Use this when you need the latest state only. When the history of changes matters (an audit trail, read models, replays), use [event sourcing](event-sourcing.md) instead. ## Setup Add Spring Data and your database driver next to the starter: === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-spring-boot-starter:$version") implementation("org.springframework.boot:spring-boot-starter-data-jpa") runtimeOnly("org.postgresql:postgresql") ``` === "Maven" ```xml org.springframework.boot spring-boot-starter-data-jpa org.postgresql postgresql runtime ``` Configure the `DataSource` as usual (`spring.datasource.*`). The samples below use an `Order` JPA entity and this repository, from the [persistence example](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/persistence): === "Java" ```java public interface OrderRepository extends JpaRepository { Optional findByOrderId(String orderId); } ``` === "Kotlin" ```kotlin interface OrderRepository : JpaRepository { fun findByOrderId(orderId: String): Optional } ``` ## Load on start, save on change The actor id is the key of the row. `withState` runs once when the actor starts: load the row there. Each handler that changes the state saves it before it replies. === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.SpringBehaviorContext; import org.springframework.stereotype.Component; @Component public class OrderActor implements SpringActor { private final OrderRepository orderRepository; public OrderActor(OrderRepository orderRepository) { this.orderRepository = orderRepository; } public interface Command {} public static class CreateOrder extends AskCommand implements Command { public final String customerId; public final double amount; public CreateOrder(String customerId, double amount) { this.customerId = customerId; this.amount = amount; } } public static class GetOrder extends AskCommand implements Command {} public record OrderResponse(boolean success, Order order, String message) {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { String orderId = actorContext.actorId(); return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> new OrderBehavior( ctx, orderId, orderRepository, orderRepository.findByOrderId(orderId).orElse(null))) .onMessage(CreateOrder.class, OrderBehavior::onCreate) .onMessage(GetOrder.class, OrderBehavior::onGet) .build(); } private static class OrderBehavior { private final SpringBehaviorContext ctx; private final String orderId; private final OrderRepository repository; private Order current; // null until the order is created OrderBehavior(SpringBehaviorContext ctx, String orderId, OrderRepository repository, Order current) { this.ctx = ctx; this.orderId = orderId; this.repository = repository; this.current = current; } SpringActorBehavior onCreate(CreateOrder msg) { if (current != null) { msg.reply(new OrderResponse(false, current, "Order already exists")); return SpringActorBehavior.same(); } current = repository.save(new Order(orderId, msg.customerId, msg.amount)); ctx.getLog().info("Order created: {}", orderId); msg.reply(new OrderResponse(true, current, "Order created")); return SpringActorBehavior.same(); } SpringActorBehavior onGet(GetOrder msg) { msg.reply(current == null ? new OrderResponse(false, null, "Order not found") : new OrderResponse(true, current, "OK")); return SpringActorBehavior.same(); } } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.SpringBehaviorContext import io.github.seonwkim.actor.kotlin.actorBehavior import org.springframework.stereotype.Component @Component class OrderActor(private val orderRepository: OrderRepository) : SpringActor { sealed interface Command class CreateOrder(val customerId: String, val amount: Double) : AskCommand(), Command class GetOrder : AskCommand(), Command data class OrderResponse(val success: Boolean, val order: Order?, val message: String) override fun create(actorContext: SpringActorContext): SpringActorBehavior { val orderId = actorContext.actorId() return actorBehavior(actorContext) .withState { ctx -> OrderBehavior(ctx, orderId, orderRepository, orderRepository.findByOrderId(orderId).orElse(null)) } .onMessage(CreateOrder::class.java) { state, msg -> state.onCreate(msg) } .onMessage(GetOrder::class.java) { state, msg -> state.onGet(msg) } .build() } class OrderBehavior( private val ctx: SpringBehaviorContext, private val orderId: String, private val repository: OrderRepository, private var current: Order?, // null until the order is created ) { fun onCreate(msg: CreateOrder): SpringActorBehavior { if (current != null) { msg.reply(OrderResponse(false, current, "Order already exists")) return SpringActorBehavior.same() } current = repository.save(Order(orderId, msg.customerId, msg.amount)) ctx.log.info("Order created: {}", orderId) msg.reply(OrderResponse(true, current, "Order created")) return SpringActorBehavior.same() } fun onGet(msg: GetOrder): SpringActorBehavior { msg.reply( current?.let { OrderResponse(true, it, "OK") } ?: OrderResponse(false, null, "Order not found"), ) return SpringActorBehavior.same() } } } ``` Because an actor handles one message at a time, the state and the row never see two changes at once. The database is still the source of truth: the next time the actor starts, it reads what was saved. !!! warning "Save before you reply" Reply only after the save has succeeded. If the save throws, the caller gets no success reply, and the actor's field and the row don't drift apart. Catch the exception and reply with an error when the caller should learn about it instead of waiting for its timeout. ## Run it on the blocking dispatcher JPA and JDBC calls block their thread until the database answers. On the default dispatcher, which every actor shares, a few slow queries can hold all its threads and stall unrelated actors. Spawn actors that block on the **blocking dispatcher** with `withBlockingDispatcher()`: === "Java" ```java @RestController @RequestMapping("/api/orders") public class OrderController { private final SpringActorSystem actorSystem; public OrderController(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } @PostMapping("/{orderId}") public CompletionStage createOrder( @PathVariable String orderId, @RequestParam String customerId, @RequestParam double amount) { return actorSystem .actor(OrderActor.class) .withId(orderId) .withBlockingDispatcher() .getOrSpawn() // the running actor, or a new one on the blocking dispatcher .thenCompose(order -> order.ask(new OrderActor.CreateOrder(customerId, amount)) .withTimeout(Duration.ofSeconds(5)) .execute()); } } ``` === "Kotlin" ```kotlin @RestController @RequestMapping("/api/orders") class OrderController(private val actorSystem: SpringActorSystem) { // A suspend handler: see the Kotlin guide for what it needs on the classpath @PostMapping("/{orderId}") suspend fun createOrder( @PathVariable orderId: String, @RequestParam customerId: String, @RequestParam amount: Double, ): OrderActor.OrderResponse = actorSystem .actor() .withId(orderId) .withBlockingDispatcher() .awaitGetOrSpawn() // the running actor, or a new one on the blocking dispatcher .awaitAsk(OrderActor.CreateOrder(customerId, amount), timeout = 5.seconds) } ``` Use `getOrSpawn()` on the spawn builder, as above, rather than `actorSystem.getOrSpawn(OrderActor.class, id)`: only the builder carries the dispatcher. The blocking dispatcher is Pekko's default blocking dispatcher, a fixed pool of threads. To run it on virtual threads instead, set `spring.actor.virtual-threads.enabled: true` (or keep the default `auto` and turn on Spring Boot's `spring.threads.virtual.enabled`). See [Dispatchers](../core/dispatchers.md). ## Non-blocking calls with R2DBC Spring Data R2DBC returns a `Mono` instead of blocking, so the actor can stay on the default dispatcher. Turn the result into a message with `pipeToSelf`: the actor handles it like any other message, one at a time, so its state stays safe without locks. === "Java" ```java @Component public class ReactiveOrderActor implements SpringActor { private final ReactiveOrderRepository repository; // a Spring Data R2DBC repository public ReactiveOrderActor(ReactiveOrderRepository repository) { this.repository = repository; } public interface Command {} public record SaveOrder(Order order) implements Command {} // The result of a save, sent by the actor to itself. private record SaveDone(Order saved, Throwable failure) implements Command {} @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ReactiveBehavior::new) .onMessage(SaveOrder.class, ReactiveBehavior::onSave) .onMessage(SaveDone.class, ReactiveBehavior::onSaveDone) .build(); } private class ReactiveBehavior { private final SpringBehaviorContext ctx; private Order current; ReactiveBehavior(SpringBehaviorContext ctx) { this.ctx = ctx; } SpringActorBehavior onSave(SaveOrder msg) { // Returns at once; the save runs on R2DBC's threads, not the actor's. ctx.pipeToSelf(repository.save(msg.order()).toFuture(), SaveDone::new); return SpringActorBehavior.same(); } SpringActorBehavior onSaveDone(SaveDone done) { if (done.failure() != null) { ctx.getLog().error("Save failed", done.failure()); } else { current = done.saved(); // state changes only inside a message handler } return SpringActorBehavior.same(); } } } ``` === "Kotlin" ```kotlin @Component class ReactiveOrderActor( private val repository: ReactiveOrderRepository, // a Spring Data R2DBC repository ) : SpringActor { sealed interface Command data class SaveOrder(val order: Order) : Command // The result of a save, sent by the actor to itself. private data class SaveDone(val saved: Order?, val failure: Throwable?) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = actorBehavior(actorContext) .withState { ctx -> ReactiveBehavior(ctx) } .onMessage(SaveOrder::class.java) { state, msg -> state.onSave(msg) } .onMessage(SaveDone::class.java) { state, done -> state.onSaveDone(done) } .build() private inner class ReactiveBehavior(private val ctx: SpringBehaviorContext) { private var current: Order? = null fun onSave(msg: SaveOrder): SpringActorBehavior { // Returns at once; the save runs on R2DBC's threads, not the actor's. ctx.pipeToSelf(repository.save(msg.order).toFuture()) { saved, failure -> SaveDone(saved, failure) } return SpringActorBehavior.same() } fun onSaveDone(done: SaveDone): SpringActorBehavior { if (done.failure != null) { ctx.log.error("Save failed", done.failure) } else { current = done.saved // state changes only inside a message handler } return SpringActorBehavior.same() } } } ``` To reply to the caller once the save is done, carry the `AskCommand` in the result message and call `reply` in its handler. !!! warning "Don't touch state in a callback" Never change actor state in `subscribe(...)`, `thenAccept(...)` or any other callback: it runs on another thread, alongside the actor. Send the result to the actor with `pipeToSelf` and change state in the handler. ## Transactions When one change writes several tables, put the writes in a `@Transactional` method of a Spring service and call it from the actor. Spring's transaction works as anywhere else, because the call runs on the actor's thread from start to end. === "Java" ```java @Service public class OrderService { private final OrderRepository orders; private final OrderItemRepository items; public OrderService(OrderRepository orders, OrderItemRepository items) { this.orders = orders; this.items = items; } @Transactional public Order createWithItems(String orderId, String customerId, double amount, List newItems) { Order order = orders.save(new Order(orderId, customerId, amount)); for (OrderItem item : newItems) { item.setOrder(order); items.save(item); } return order; } } ``` === "Kotlin" ```kotlin @Service class OrderService( private val orders: OrderRepository, private val items: OrderItemRepository, ) { @Transactional fun createWithItems(orderId: String, customerId: String, amount: Double, newItems: List): Order { val order = orders.save(Order(orderId, customerId, amount)) for (item in newItems) { item.setOrder(order) items.save(item) } return order } } ``` Inject `OrderService` into the actor instead of the repositories, and call it in the handler. Run the actor on the blocking dispatcher, as above. Don't put `@Transactional` on the actor class: the actor's handlers are not called through a Spring proxy. ## Snapshots of large state When building the state from many rows is slow, store a snapshot of it now and then: serialize the state to JSON in a snapshot table every N changes or every few seconds, and on start, load the latest snapshot before falling back to the rows. The persistence example's [`SnapshotOrderActor`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/persistence/src/main/java/io/github/seonwkim/example/persistence/snapshot) does this with its own `SnapshotStrategy` and `HybridSnapshotStrategy` classes. These classes belong to the example, not to the starter. [Event-sourced actors](event-sourcing.md) have snapshots built in (`snapshotEvery(n)`). ## Choosing an approach | Approach | Use it when | What to watch | |---|---|---| | JPA or JDBC on the blocking dispatcher | The app already uses JPA, as most Spring apps do | Each call holds a thread of the blocking dispatcher. Size the pool, or use virtual threads | | R2DBC with `pipeToSelf` | Many actors talk to the database at once, or the app is already reactive | Every result comes back as a message, so each call needs a result message type | | Event sourcing with `actor-persistence` | The history of changes matters, not only the latest state | Events are a stored contract: their JSON shape must stay readable. See [Event-Sourced Actors](event-sourcing.md) | ## One writer per row The pattern is safe because one actor owns one row. Keep it that way: - **One node.** A regular actor with a given id runs once per node, so one node never has two writers. - **Several nodes.** Each node can spawn its own `OrderActor` with the same id, and then two actors write the same row. Make the actor a [sharded entity](../cluster/sharded-actors.md) (one per id in the cluster) or, for a single global actor, a [singleton](../cluster/singletons.md). For extra safety, add a version column (`@Version` in JPA) so a stale write fails instead of overwriting. ## Pitfalls - **Blocking on the default dispatcher.** Always spawn JPA and JDBC actors with `withBlockingDispatcher()`. - **Changing state in callbacks.** Use `pipeToSelf`. - **Replying before saving.** The caller then sees a success that may not be stored. - **Lazy JPA associations.** The actor keeps the entity after the transaction has ended; load what you need in the query (`JOIN FETCH`) or map it to your own class. ## Related - [Persistence example](../../examples/persistence.md): JPA, a hand-made event log and snapshots - [Event-Sourced Actors](event-sourcing.md): store events instead of state - [Dispatchers](../core/dispatchers.md): the blocking dispatcher and virtual threads - [Sharded Actors](../cluster/sharded-actors.md): one actor per id across a cluster --- # Event-Sourced Actors An event-sourced actor stores what happened (events) instead of its current state. Each command decides which events to store; each event changes the state. When the actor starts again, after a restart, a deploy or a crash, it rebuilds its state from the stored events. !!! info "Incubating" `actor-persistence` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. The `actor-persistence` module runs event-sourced actors on Pekko Persistence. The journal and the snapshots live in tables on your application's `DataSource`: no second connection pool, no Pekko configuration, and no Pekko types in your code. !!! tip "Event sourcing or a state store?" If you only need the latest state of an actor, keep it in a table with Spring Data, as in [State in a Database](state-in-a-database.md). Use event sourcing when the history matters: an audit trail, rebuilding read models with [projections](#tags-for-projections), or undoing a bug by replaying events. ## Add the module ```kotlin dependencies { implementation("io.github.seonwkim:actor-spring-boot-starter:$version") implementation("io.github.seonwkim:actor-persistence:$version") implementation("org.springframework.boot:spring-boot-starter-jdbc") // or data-jpa: any DataSource runtimeOnly("org.postgresql:postgresql") } ``` ## Write an event-sourced actor An event-sourced actor is a `SpringActor` whose `create` returns a `SpringEventSourcedBehavior`: === "Java" ```java import io.github.seonwkim.actor.AskCommand; import io.github.seonwkim.actor.SpringActor; import io.github.seonwkim.actor.SpringActorBehavior; import io.github.seonwkim.actor.SpringActorContext; import io.github.seonwkim.actor.persistence.PersistenceId; import io.github.seonwkim.actor.persistence.SpringEventSourcedBehavior; import io.github.seonwkim.actor.serialization.JsonSerializable; import org.springframework.stereotype.Component; @Component public class AccountActor implements SpringActor { public interface Command {} public static final class Deposit extends AskCommand implements Command { public final long amount; public Deposit(long amount) { this.amount = amount; } } public static final class GetBalance extends AskCommand implements Command {} // Events and the state are stored: they must be serializable. public interface Event extends JsonSerializable {} public record Deposited(long amount) implements Event {} public record Account(long balance) implements JsonSerializable { Account add(long amount) { return new Account(balance + amount); } } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringEventSourcedBehavior.builder( Command.class, Event.class, PersistenceId.of("Account", actorContext.actorId()), new Account(0)) .onCommand(Deposit.class, (ctx, account, cmd) -> ctx.persist(new Deposited(cmd.amount)) .thenReply(cmd, Account::balance)) .onCommand(GetBalance.class, (ctx, account, cmd) -> ctx.none() .thenReply(cmd, Account::balance)) .onEvent(Deposited.class, (account, event) -> account.add(event.amount())) .snapshotEvery(100) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.AskCommand import io.github.seonwkim.actor.SpringActor import io.github.seonwkim.actor.SpringActorBehavior import io.github.seonwkim.actor.SpringActorContext import io.github.seonwkim.actor.persistence.PersistenceId import io.github.seonwkim.actor.persistence.SpringEventSourcedBehavior import io.github.seonwkim.actor.serialization.JsonSerializable import org.springframework.stereotype.Component @Component class AccountActor : SpringActor { sealed interface Command class Deposit(val amount: Long) : AskCommand(), Command class GetBalance : AskCommand(), Command // Events and the state are stored: they must be serializable. sealed interface Event : JsonSerializable data class Deposited(val amount: Long) : Event data class Account(val balance: Long) : JsonSerializable { fun add(amount: Long) = Account(balance + amount) } override fun create(actorContext: SpringActorContext): SpringActorBehavior = SpringEventSourcedBehavior.builder( Command::class.java, Event::class.java, PersistenceId.of("Account", actorContext.actorId()), Account(0), ) .onCommand(Deposit::class.java) { ctx, _, cmd -> ctx.persist(Deposited(cmd.amount)).thenReply(cmd) { it.balance } } .onCommand(GetBalance::class.java) { ctx, _, cmd -> ctx.none().thenReply(cmd) { it.balance } } .onEvent(Deposited::class.java) { account, event -> account.add(event.amount) } .snapshotEvery(100) .build() } ``` Spawn it and send it commands like any other actor: === "Java" ```java SpringActorHandle account = actorSystem.actor(AccountActor.class).withId("alice").spawnAndWait(); long balance = account.ask(new AccountActor.Deposit(5)).execute().toCompletableFuture().join(); ``` === "Kotlin" ```kotlin // In a suspend fun or a coroutine val account = actorSystem.actor().withId("alice").awaitSpawn() val balance: Long = account.awaitAsk(AccountActor.Deposit(5)) ``` Spawn `alice` again after a restart and it has the same balance. ### The parts | Part | What it does | |---|---| | `PersistenceId.of(entityType, entityId)` | The key of the actor's events: `Account\|alice`. It must be unique in the application and the same on every start. | | empty state | The state before any event. | | `onCommand(type, (ctx, state, command) -> effect)` | Decides what to do with a command. It returns an `Effect`; it must not change the state itself. | | `onEvent(type, (state, event) -> newState)` | Applies a stored event. It runs after the event is stored and again on every recovery, so it must not have side effects. | | `snapshotEvery(n)` | Stores a snapshot of the state every `n` events and keeps the latest two. Recovery loads the latest snapshot and replays only the events after it. | | `withTagger(event -> Set.of(...))` | Tags stored with each event, for projections. | ### Effects Start from the context, which knows the event and state types: | Effect | Meaning | |---|---| | `ctx.persist(event)`, `ctx.persist(List.of(e1, e2))` | Store the events (a list atomically), then apply them | | `ctx.none()` | Store nothing | | `ctx.unhandled()` | The command isn't handled in this state | | `ctx.stop()` | Store nothing and stop the actor | | `.thenReply(cmd, state -> value)` | Reply to an `AskCommand` with the state after the events | | `.thenRun(state -> ...)` | Any other side effect, after the events are stored | | `.thenStop()` | Stop after the side effects | Side effects run only after the events are stored, never during recovery. `ctx.actorContext()` gives the actor's own context (`getSelf()`, `getLog()`, timers). ### Serialization Events and states are written to the database with Jackson. Implement `JsonSerializable` (or `CborSerializable`) from `io.github.seonwkim.actor.serialization` on your events and your state. Once events are stored, their JSON shape is a contract: add fields with defaults rather than renaming or removing them. The starter writes them with its own Jackson mapper, so changing the application's `ObjectMapper` for the REST API leaves stored events readable. With `spring.actor.serialization.application-object-mapper: true` they use the application's mapper, and its settings become part of that contract. ## Tables The journal (`event_journal`, `event_tag`) and the snapshots (`snapshot`) are the tables of [Pekko Persistence JDBC](https://pekko.apache.org/docs/pekko-persistence-jdbc/current/) 1.1. `spring.actor.persistence.initialize-schema` decides when the starter creates them: | Value | When | |---|---| | `embedded` (default) | Only in an embedded database, such as H2 in tests | | `always` | On every start (the scripts use `CREATE TABLE IF NOT EXISTS`; on PostgreSQL, nodes starting together take turns through an advisory lock) | | `never` | You create them, for example with Flyway | The scripts are in the `actor-persistence` jar as `io/github/seonwkim/actor/persistence/schema-.sql` for `h2`, `postgresql`, `mysql` and `mariadb` (tested on H2, PostgreSQL 16 and MySQL 8.4). Copy the one for your database into a Flyway or Liquibase migration for production. For Oracle and SQL Server the starter picks the matching dialect but ships no script and has no test: create their tables from the `schema/oracle` or `schema/sqlserver` scripts in the `pekko-persistence-jdbc` jar. The actor system starts after the database is initialized (the starter's scripts, Flyway or Liquibase), so an actor can recover as soon as it is spawned. The JDBC calls run on their own threads, as many as your Hikari pool has connections (10 otherwise). The starter never closes your `DataSource`. To keep the journal off the application's pool, give it a `DataSource` of its own with `@ActorDataSource`, as described in [A separate DataSource](../cluster/cluster-formation.md#a-separate-datasource); the tables are then created there. ## Tags for projections A projection reads the events of one tag in the order they were stored, for example to fill a read model or publish to Kafka: === "Java" ```java .withTagger(event -> Set.of("accounts")) ``` === "Kotlin" ```kotlin .withTagger { setOf("accounts") } ``` See [Projections](projections.md). ## Failures If storing an event fails, the actor stops (Pekko's default) and the command gets no reply; an `ask` times out. Spawn the actor again to recover it from the stored events. Commands are never stored: a command that was being handled when the application stopped is lost, so let the caller retry. ## In a cluster Run at most one actor per persistence id at a time: two actors that store events under the same id conflict on their sequence numbers. On one node, a regular actor with a given id runs once. On several nodes, each node could spawn its own copy of a regular actor, so don't spawn event-sourced actors per id with `actorSystem.actor(...)` in a cluster. **Make it a sharded entity.** Sharding runs each entity id on one node of the cluster at a time, so there is one writer per persistence id. Return a `SpringEventSourcedBehavior` from a [`SpringShardedActor`](../cluster/sharded-actors.md), with the entity id in the persistence id: === "Java" ```java @Component public class AccountEntity implements SpringShardedActor { // Commands cross nodes in a cluster: make them serializable too. public interface Command extends JsonSerializable {} public static final ShardedEntityType TYPE = ShardedEntityType.of(Command.class, "Account"); @Override public ShardedEntityType entityType() { return TYPE; } @Override public SpringActorBehavior create(SpringShardedActorContext ctx) { return SpringEventSourcedBehavior.builder( Command.class, Event.class, PersistenceId.of("Account", ctx.getEntityId()), new Account(0)) .onCommand(Deposit.class, (es, account, cmd) -> es.persist(new Deposited(cmd.amount)) .thenReply(cmd, Account::balance)) .onEvent(Deposited.class, (account, event) -> account.add(event.amount())) .build(); } } ``` === "Kotlin" ```kotlin @Component class AccountEntity : SpringShardedActor { // Commands cross nodes in a cluster: make them serializable too. interface Command : JsonSerializable override fun entityType(): ShardedEntityType = TYPE override fun create(ctx: SpringShardedActorContext): SpringActorBehavior = SpringEventSourcedBehavior.builder( Command::class.java, Event::class.java, PersistenceId.of("Account", ctx.entityId), Account(0)) .onCommand(Deposit::class.java) { es, _, cmd -> es.persist(Deposited(cmd.amount)).thenReply(cmd, Account::balance) } .onEvent(Deposited::class.java) { account, event -> account.add(event.amount) } .build() companion object { val TYPE: ShardedEntityType = ShardedEntityType.of(Command::class.java, "Account") } } ``` When the entity's node leaves the cluster, the entity starts on another node and rebuilds its state from the journal. All nodes must use the same database. The starter's build tests this (`ShardedEventSourcedActorTest` in `actor-persistence`): three nodes send commands to one entity, the node that runs it leaves, and the entity answers from another node with the state from all the events stored before. For a single global event-sourced actor, use a [cluster singleton](../cluster/singletons.md). ## Not supported yet - **R2DBC.** The R2DBC plugin for Pekko 1.1 (`pekko-persistence-r2dbc` 1.0) supports only PostgreSQL and Yugabyte, and its next version needs Pekko 1.2. The journal runs on JDBC for now. - **Framework commands** (`FrameworkCommand`, spawning children by message) are not handled by event-sourced actors. ## Related - [Projections](projections.md): read the stored events into read models or Kafka - [State in a Database](state-in-a-database.md): keep only the latest state with Spring Data - [Persistence example](../../examples/persistence.md) --- # Projections A projection reads the events that [event-sourced actors](event-sourcing.md) store and writes them somewhere else: a read model in your database through Spring Data, or a Kafka topic through Spring Kafka. It remembers how far it got (its offset) in your database, so after a restart it resumes where it stopped. !!! info "Incubating" `actor-projection` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. The `actor-projection` module runs projections on Pekko Projections, with no Pekko types in your code. ## Add the module ```kotlin dependencies { implementation("io.github.seonwkim:actor-spring-boot-starter:$version") implementation("io.github.seonwkim:actor-projection:$version") // brings actor-persistence implementation("org.springframework.boot:spring-boot-starter-jdbc") // or data-jpa } ``` ## Tag the events A projection reads the events of one tag. Tag them in the event-sourced actor: === "Java" ```java SpringEventSourcedBehavior.builder(Command.class, Event.class, PersistenceId.of("Account", id), new Account(0)) // ... .withTagger(event -> Set.of("accounts")) .build(); ``` === "Kotlin" ```kotlin SpringEventSourcedBehavior.builder(Command::class.java, Event::class.java, PersistenceId.of("Account", id), Account(0)) // ... .withTagger { setOf("accounts") } .build() ``` Only events stored after you add the tagger carry the tag. ## Write a projection A projection is a bean that implements `SpringProjection`: === "Java" ```java import io.github.seonwkim.actor.projection.ProjectedEvent; import io.github.seonwkim.actor.projection.SpringProjection; import org.springframework.stereotype.Component; @Component public class BalanceProjection implements SpringProjection { private final BalanceRepository balances; // a Spring Data repository public BalanceProjection(BalanceRepository balances) { this.balances = balances; } @Override public String name() { return "balances"; } @Override public String tag() { return "accounts"; } @Override public void handle(ProjectedEvent event) { if (event.event() instanceof AccountActor.Deposited deposited) { Balance balance = balances.findById(event.persistenceId()).orElseGet(() -> new Balance(event.persistenceId())); balance.add(deposited.amount()); balances.save(balance); } } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.projection.ProjectedEvent import io.github.seonwkim.actor.projection.SpringProjection import org.springframework.stereotype.Component @Component class BalanceProjection( private val balances: BalanceRepository, // a Spring Data repository ) : SpringProjection { override fun name() = "balances" override fun tag() = "accounts" override fun handle(event: ProjectedEvent) { val deposited = event.event() as? AccountActor.Deposited ?: return val balance = balances.findById(event.persistenceId()).orElseGet { Balance(event.persistenceId()) } balance.add(deposited.amount) balances.save(balance) } } ``` Every `SpringProjection` bean starts when the application starts. `handle` gets the events of its tag one at a time, in the order they were stored, with the id of the actor that stored each one (`persistenceId()`, such as `Account|alice`), its sequence number and its timestamp. `name()` identifies the stored offset. Rename a projection and it starts again from the first event, which is also how you rebuild a read model. ## Exactly once or at least once `delivery()` decides when the offset is stored: | `delivery()` | Offset stored | Use it for | |---|---|---| | `EXACTLY_ONCE` (default) | In the same transaction as `handle` | Writes to the application's database: repositories, `JdbcTemplate` | | `AT_LEAST_ONCE` | After `handle`, in batches | Writes elsewhere, such as Kafka | `handle` always runs in a Spring transaction on your `DataSource`, using your `PlatformTransactionManager` bean when there is exactly one (otherwise a `JdbcTransactionManager` on the `DataSource`). With `EXACTLY_ONCE`, the rows `handle` writes and the new offset commit together, or roll back together. When `handle` throws, the transaction rolls back and the projection restarts after a backoff, from the stored offset, so the event is handled again. ## Spring Kafka Publish with `AT_LEAST_ONCE`, and wait for the send so a failed send fails the event: === "Java" ```java @Component public class AccountEventsToKafka implements SpringProjection { private final KafkaTemplate kafka; public AccountEventsToKafka(KafkaTemplate kafka) { this.kafka = kafka; } @Override public String name() { return "account-events-to-kafka"; } @Override public String tag() { return "accounts"; } @Override public Delivery delivery() { return Delivery.AT_LEAST_ONCE; } @Override public void handle(ProjectedEvent event) throws Exception { kafka.send("account-events", event.persistenceId(), event.event()).get(); } } ``` === "Kotlin" ```kotlin @Component class AccountEventsToKafka( private val kafka: KafkaTemplate, ) : SpringProjection { override fun name() = "account-events-to-kafka" override fun tag() = "accounts" override fun delivery() = Delivery.AT_LEAST_ONCE override fun handle(event: ProjectedEvent) { kafka.send("account-events", event.persistenceId(), event.event()).get() } } ``` After a crash the last events are published again: consumers should ignore an event they have already seen (the persistence id and sequence number identify it). ## Tables The offsets live in `pekko_projection_offset_store` and `pekko_projection_management`. `spring.actor.persistence.initialize-schema` creates them together with the journal tables (`embedded` by default, `always`, or `never`). The scripts are in the `actor-projection` jar as `io/github/seonwkim/actor/projection/schema-.sql` for `h2`, `postgresql`, `mysql` and `mariadb` (tested on H2, PostgreSQL 16 and MySQL 8.4); copy them into a Flyway or Liquibase migration for production. ## Cluster In cluster mode each projection runs as a [cluster singleton](../cluster/singletons.md) named `projection-`, so one node handles its events. When that node leaves, the projection starts on another node and resumes from the stored offset. ## Not supported yet - **Kafka as the source.** Projections read events stored by event-sourced actors. Reading a Kafka topic (`pekko-projection-kafka`) is not wrapped: consume it with Spring Kafka's `@KafkaListener`. - **Several instances of one projection.** A projection reads its tag with one consumer. To spread a busy tag, split it into several tags (for example `accounts-0` to `accounts-3` by entity id) and declare one projection per tag. ## Related - [Event-Sourced Actors](event-sourcing.md): where the tagged events come from - [Cluster Singletons](../cluster/singletons.md): how a projection runs in a cluster - [State in a Database](state-in-a-database.md): the read model side, with Spring Data --- # Reactor Streams `actor-streams` connects actors to Project Reactor. It gives you three things, all as `Mono` and `Flux`: | You want | Method | Backpressure | |---|---|---| | The reply of one ask | `ask(askBuilder)` | n/a | | To send a stream of elements to an actor | `askEach(elements, parallelism, ask)` | at most `parallelism` asks in flight | | The messages an actor sends | `messages(type)...flux(onSubscribe)` | a bounded buffer, or an acknowledgement per message | !!! info "Incubating" `actor-streams` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. No Pekko type appears in this API. Pekko Streams runs underneath and stays an implementation detail. ## Setup Add the module next to the starter: === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-spring-boot-starter:$version") implementation("io.github.seonwkim:actor-streams:$version") ``` === "Maven" ```xml io.github.seonwkim actor-streams ${actor.version} ``` With `actor-streams` on the classpath, the application has an `ActorStreams` bean. Inject it where you need it: === "Java" ```java import io.github.seonwkim.actor.SpringActorSystem; import io.github.seonwkim.actor.streams.ActorStreams; import org.springframework.stereotype.Service; @Service public class OrderService { private final ActorStreams streams; private final SpringActorSystem actorSystem; public OrderService(ActorStreams streams, SpringActorSystem actorSystem) { this.streams = streams; this.actorSystem = actorSystem; } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActorSystem import io.github.seonwkim.actor.streams.ActorStreams import org.springframework.stereotype.Service @Service class OrderService( private val streams: ActorStreams, private val actorSystem: SpringActorSystem, ) ``` ## `Mono` of an ask Pass the ask builder you already use. The command is sent when the `Mono` is subscribed, not when it is created, and again on each new subscription. The builder's timeout and `onTimeout` fallback apply. === "Java" ```java Mono order = streams.ask(orders.ask(new GetOrder(id)).withTimeout(Duration.ofSeconds(2))); ``` === "Kotlin" ```kotlin val order: Mono = streams.ask(orders.ask(GetOrder(id)).withTimeout(2.seconds)) ``` It works the same for a sharded entity's handle. ## Feeding an actor from a `Flux` `askEach` asks an actor about each element and emits the replies in the order of the elements: === "Java" ```java Flux receipts = streams.askEach(payments, 8, payment -> ledger.ask(new Charge(payment))); ``` === "Kotlin" ```kotlin val receipts: Flux = streams.askEach(payments, 8) { payment -> ledger.ask(Charge(payment)) } ``` At most `parallelism` asks (here 8) wait for a reply at once. Until one of them is answered, `askEach` requests nothing more from `payments`. So a slow actor slows the upstream `Flux` (a Kafka consumer, a database cursor, an HTTP body) instead of filling its mailbox. A failed ask, for example a timeout, fails the `Flux`. Give the builder `onTimeout(...)` for a fallback reply, or use Reactor's `onErrorResume` and `retry` operators. The actor replies as for any ask: === "Java" ```java .onMessage(Charge.class, (ctx, msg) -> { msg.reply(ledger.charge(msg.payment())); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin .onMessage(Charge::class.java) { _, msg -> msg.reply(ledger.charge(msg.payment)) SpringActorBehavior.same() } ``` ## A `Flux` of the messages an actor sends `messages(type)` creates, for each subscriber, a reference that actors can send messages to. Whatever they send to it comes out of the `Flux`. Pass the reference to the actor in `flux(onSubscribe)`: === "Java" ```java Flux prices = streams.messages(Price.class) .onClose(ref -> ticker.tell(new Unsubscribe(ref))) .flux(ref -> ticker.tell(new Subscribe(ref))); ``` === "Kotlin" ```kotlin val prices: Flux = streams.messages(Price::class.java) .onClose { ref -> ticker.tell(Unsubscribe(ref)) } .flux { ref -> ticker.tell(Subscribe(ref)) } ``` The reference is a `SpringActorRef`, so the actor stores it and calls `tell` like on any other reference. In this ticker, the state holds the behavior context (`ctx`) and a set of subscribers: === "Java" ```java .onMessage(Subscribe.class, (state, msg) -> { state.subscribers().add(msg.subscriber()); state.ctx().watch(msg.subscriber()); return SpringActorBehavior.same(); }) .onMessage(PriceChanged.class, (state, msg) -> { state.subscribers().forEach(subscriber -> subscriber.tell(msg.price())); return SpringActorBehavior.same(); }) .onSignal(ActorTerminated.class, (state, signal) -> { state.subscribers().remove(signal.ref()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin .onMessage(Subscribe::class.java) { state, msg -> state.subscribers.add(msg.subscriber) state.ctx.watch(msg.subscriber) SpringActorBehavior.same() } .onMessage(PriceChanged::class.java) { state, msg -> state.subscribers.forEach { subscriber -> subscriber.tell(msg.price) } SpringActorBehavior.same() } .onSignal(ActorTerminated::class.java) { state, signal -> state.subscribers.removeIf { it == signal.ref() } SpringActorBehavior.same() } ``` ### When the subscriber goes away When the subscriber cancels (an HTTP client disconnects, a `take(10)` is satisfied), the reference stops. The actor can learn it in two ways; use either: - It `watch`es the reference and receives `ActorTerminated`, as above. - `onClose` runs with the reference when the `Flux` ends for that subscriber: completed, failed or cancelled. Tell the actor to forget it there. Messages sent to a stopped reference go to dead letters. ### Ending the stream from the actor `completeWhen` names the message that ends the `Flux`. Messages sent before it are still emitted; it is not: === "Java" ```java Flux events = streams.messages(Event.class) .completeWhen(event -> event instanceof Done) .flux(ref -> job.tell(new Watch(ref))); ``` === "Kotlin" ```kotlin val events: Flux = streams.messages(Event::class.java) .completeWhen { event -> event is Done } .flux { ref -> job.tell(Watch(ref)) } ``` ### Buffer and overflow A subscriber may request fewer messages than the actor sends. The reference keeps up to `bufferSize` messages (default 256) that the subscriber has not requested yet. When the buffer is full, `overflow` decides: | `Overflow` | Effect | |---|---| | `FAIL` (default) | The `Flux` fails with an error | | `DROP_OLDEST` | The oldest buffered message is dropped | | `DROP_NEWEST` | The new message is dropped | === "Java" ```java Flux prices = streams.messages(Price.class) .bufferSize(16) .overflow(ActorStreams.Overflow.DROP_OLDEST) .flux(ref -> ticker.tell(new Subscribe(ref))); ``` === "Kotlin" ```kotlin val prices: Flux = streams.messages(Price::class.java) .bufferSize(16) .overflow(ActorStreams.Overflow.DROP_OLDEST) .flux { ref -> ticker.tell(Subscribe(ref)) } ``` `DROP_OLDEST` suits values where only the latest matters, such as prices or positions. ### Backpressure to the sending actor When nothing may be dropped, let the sending actor wait for the subscriber. With `ackTo(sender, ack)`, the reference sends `ack` to `sender` each time a message has gone on to the subscriber. The sender sends its next message only after an `ack`: === "Java" ```java Flux rows = streams.messages(Row.class) .ackTo(exporter, new Exporter.Ack()) .completeWhen(row -> row.isLast()) .flux(ref -> exporter.tell(new Exporter.Start(ref))); ``` === "Kotlin" ```kotlin val rows: Flux = streams.messages(Row::class.java) .ackTo(exporter, Exporter.Ack()) .completeWhen { row -> row.isLast } .flux { ref -> exporter.tell(Exporter.Start(ref)) } ``` === "Java" ```java .onMessage(Start.class, (state, msg) -> { state.subscriber = msg.subscriber(); state.sendNext(); return SpringActorBehavior.same(); }) .onMessage(Ack.class, (state, msg) -> { state.sendNext(); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin .onMessage(Start::class.java) { state, msg -> state.subscriber = msg.subscriber state.sendNext() SpringActorBehavior.same() } .onMessage(Ack::class.java) { state, _ -> state.sendNext() SpringActorBehavior.same() } ``` With `ackTo`, there is no buffer, so `bufferSize` and `overflow` do not apply. ## Limits - The bridges are tested on one node. The reference that `messages` creates lives on the subscriber's node. - An actor cannot fail a `messages` `Flux`; it can end it with `completeWhen`. To report an error, send a message that the subscriber maps to an error with Reactor's `handle` operator. ## Related - [Streaming to Clients](streaming-to-clients.md): Server-Sent Events, WebSocket and gRPC on top of `messages` - [Messaging](../core/messaging.md): `tell`, `ask` and replies - [Behaviors](../core/behaviors.md): `watch` and `ActorTerminated` --- # Streaming to Clients Send what actors produce to browsers and services over Server-Sent Events, WebSocket or gRPC. Each bridge builds on the `messages` `Flux` of [Reactor Streams](reactor-streams.md): a client gets a reference that actors send to, and when the client disconnects, the reference stops. An actor that `watch`es it receives `ActorTerminated` and can forget the client or stop itself. !!! info "Incubating" `actor-streams` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. All three need `actor-streams`: === "Gradle" ```kotlin implementation("io.github.seonwkim:actor-streams:$version") ``` === "Maven" ```xml io.github.seonwkim actor-streams ${actor.version} ``` | Transport | Stack | What you write | |---|---|---| | Server-Sent Events | Spring MVC or WebFlux | A controller method that returns the `messages` `Flux` | | WebSocket | WebFlux | An `ActorWebSocketHandler` with a connector | | gRPC | grpc-java or Spring gRPC | `ActorGrpc.respond(flux, responseObserver)` in the service method | ## Server-Sent Events Return the `Flux` from a controller with `produces = text/event-stream`. Spring MVC and WebFlux both write each element as an event, and cancel the `Flux` when the client goes away: === "Java" ```java import io.github.seonwkim.actor.SpringActorSystem; import io.github.seonwkim.actor.streams.ActorStreams; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController public class PricesController { private final ActorStreams streams; private final SpringActorSystem actorSystem; public PricesController(ActorStreams streams, SpringActorSystem actorSystem) { this.streams = streams; this.actorSystem = actorSystem; } @GetMapping(path = "/prices", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux prices() { return Mono.fromCompletionStage(actorSystem.actor(TickerActor.class).withId("ticker").getOrSpawn()) .flatMapMany(ticker -> streams.messages(Price.class) .bufferSize(16) .overflow(ActorStreams.Overflow.DROP_OLDEST) .flux(ref -> ticker.tell(new Subscribe(ref)))); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActorSystem import io.github.seonwkim.actor.kotlin.actor import io.github.seonwkim.actor.streams.ActorStreams import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Flux import reactor.core.publisher.Mono @RestController class PricesController( private val streams: ActorStreams, private val actorSystem: SpringActorSystem, ) { @GetMapping(path = ["/prices"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE]) fun prices(): Flux = Mono.fromCompletionStage(actorSystem.actor().withId("ticker").getOrSpawn()) .flatMapMany { ticker -> streams.messages(Price::class.java) .bufferSize(16) .overflow(ActorStreams.Overflow.DROP_OLDEST) .flux { ref -> ticker.tell(Subscribe(ref)) } } } ``` The ticker keeps its subscribers and forgets one when it stops, as shown in [Reactor Streams](reactor-streams.md#a-flux-of-the-messages-an-actor-sends). When the client disconnects: - **WebFlux** notices at once, and the reference stops. - **Spring MVC** (a servlet container) notices only on its next write to that client. The reference stops after the next message the actor sends, which fails to write. If an actor may stay quiet for a long time, send a heartbeat now and then. Use a small buffer with `DROP_OLDEST` for values where only the latest matters, so a slow client never holds many messages. ## WebSocket (WebFlux) `ActorWebSocketHandler` is a WebFlux `WebSocketHandler`. For each connection it creates a `client` reference and calls your connector, which connects it to actors and returns where the client's text frames go: === "Java" ```java @Configuration public class WebSocketConfig { @Bean public HandlerMapping chatSocket(ActorStreams streams, SpringActorSystem actorSystem) { ActorWebSocketHandler handler = new ActorWebSocketHandler(streams, (session, client) -> actorSystem .actor(UserActor.class) .withContext(new UserContext(UUID.randomUUID().toString(), client)) .spawn() .thenApply(user -> text -> user.tell(new Incoming(text)))); return new SimpleUrlHandlerMapping(Map.of("/ws/chat", handler), 1); } } ``` === "Kotlin" ```kotlin @Configuration class WebSocketConfig { @Bean fun chatSocket(streams: ActorStreams, actorSystem: SpringActorSystem): HandlerMapping { val handler = ActorWebSocketHandler(streams) { _, client -> actorSystem.actor() .withContext(UserContext(UUID.randomUUID().toString(), client)) .spawn() .thenApply { user -> Consumer { text -> user.tell(Incoming(text)) } } } return SimpleUrlHandlerMapping(mapOf("/ws/chat" to handler), 1) } } ``` The user actor sends text to the browser with `client.tell(json)`. To stop with the connection, it watches the reference (`context` is the actor's own `SpringActorContext` subclass, which carries the client reference): === "Java" ```java .withState(ctx -> { ctx.watch(context.client()); return new UserState(ctx, context.client()); }) .onSignal(ActorTerminated.class, (state, signal) -> SpringActorBehavior.stopped()) ``` === "Kotlin" ```kotlin .withState { ctx -> ctx.watch(context.client) UserState(ctx, context.client) } .onSignal(ActorTerminated::class.java) { _, _ -> SpringActorBehavior.stopped() } ``` When the client disconnects, the reference stops and the user actor stops with it. The other way round, when the outgoing `Flux` completes (see `completeWhen` below), the session closes. The third constructor argument configures the outgoing messages, with the same settings as [`messages`](reactor-streams.md#buffer-and-overflow): === "Java" ```java new ActorWebSocketHandler(streams, connector, messages -> messages.bufferSize(64).completeWhen("bye"::equals)); ``` === "Kotlin" ```kotlin ActorWebSocketHandler(streams, connector) { messages -> messages.bufferSize(64).completeWhen { it == "bye" } } ``` By default the reference buffers 256 messages the client has not taken yet, and closes the session with an error when the buffer is full. The [chat example](../../examples/chat.md) uses this bridge. ## gRPC `ActorGrpc.respond` sends a `Flux` (or a `Mono`, or any Reactive Streams `Publisher`) to a gRPC response stream. Call it in a server-streaming or unary method of a grpc-java service, or of a Spring gRPC service: === "Java" ```java @Service public class PriceService extends PriceServiceGrpc.PriceServiceImplBase { private final ActorStreams streams; private final SpringActorHandle ticker; // spawned at startup, set in the constructor @Override public void watch(WatchRequest request, StreamObserver responses) { ActorGrpc.respond( streams.messages(Price.class).flux(ref -> ticker.tell(new Subscribe(ref))), responses); } @Override public void getPrice(PriceRequest request, StreamObserver responses) { ActorGrpc.respond(streams.ask(ticker.ask(new GetPrice(request.getSymbol()))), responses); } } ``` === "Kotlin" ```kotlin @Service class PriceService( private val streams: ActorStreams, private val ticker: SpringActorHandle, // spawned at startup ) : PriceServiceGrpc.PriceServiceImplBase() { override fun watch(request: WatchRequest, responses: StreamObserver) { ActorGrpc.respond( streams.messages(Price::class.java).flux { ref -> ticker.tell(Subscribe(ref)) }, responses, ) } override fun getPrice(request: PriceRequest, responses: StreamObserver) { ActorGrpc.respond(streams.ask(ticker.ask(GetPrice(request.symbol))), responses) } } ``` - It requests the next element only while the call is ready to send, so a slow client slows the `Flux`. With [`ackTo`](reactor-streams.md#backpressure-to-the-sending-actor), the slowness reaches the sending actor. - When the client cancels or disconnects, the `Flux` is cancelled and the reference stops. - When the `Flux` fails, the call ends with the error's gRPC status (`UNKNOWN` unless the error is a `StatusException` or `StatusRuntimeException`). `actor-streams` does not bring grpc-java: the application has it already (directly or through Spring gRPC). The bridge is built against grpc-java 1.83 and uses only its stable `grpc-stub` API. ## Related - [Reactor Streams](reactor-streams.md): `ask`, `askEach` and `messages` - [Chat example](../../examples/chat.md): the WebSocket bridge in a full application - [Kotlin](../kotlin.md): suspend functions and coroutine controllers --- # Running in Production This guide covers what matters when you run an actor application in production, for example on Kubernetes: how it shuts down without losing work, how health checks report the actor system and the cluster, a checklist to go through before the first release, and GraalVM native images. For metrics, tracing and alerts, see [Monitoring](monitoring.md). For rolling, canary and blue-green releases, see [Deployments](deployments.md). ## Graceful shutdown When the Spring application context closes (on `SIGTERM`, or when you call `context.close()`), the starter shuts the actor system down through Pekko **coordinated shutdown**. In cluster mode the node leaves the cluster on purpose: other nodes see it go `Leaving` → `Exiting` → `Removed`, sharded entities and cluster singletons move to the remaining nodes, and the node is never reported as unreachable or downed by the split brain resolver. ### Shutdown order The starter registers a Spring `SmartLifecycle` bean, `ActorSystemShutdownLifecycle`, at phase `ActorSystemShutdownLifecycle.PHASE` (`Integer.MAX_VALUE - 4096`). Spring stops lifecycle beans from the highest phase to the lowest before it destroys any bean, so on shutdown: 1. With `server.shutdown=graceful`, the web server stops accepting requests and drains in-flight ones (Spring Boot's web server lifecycles run at higher phases). 2. The actor system runs coordinated shutdown and the starter waits for it to terminate, at most the configured timeout. 3. Spring destroys the remaining beans, including the services, repositories and connection pools your actors use. Actors are already stopped, so they never call a destroyed bean. The wait is bounded: if an actor blocks shutdown (for example a handler stuck on blocking I/O), closing the context returns after the timeout with a warning in the log, and the process can exit instead of hanging. The shutdown runs once. If the actor system has already terminated, for example because the node was downed and Pekko shut itself down, closing the context does nothing more and does not fail. ### Shutdown timeout ```yaml spring: actor: shutdown: timeout: 20s # default ``` `spring.actor.shutdown.timeout` is how long closing the context waits for the actor system to terminate. It takes any Spring Boot duration (`15s`, `500ms`, `PT20S`). The default is `20s`. Keep Pekko's own coordinated shutdown phase timeouts (`pekko.coordinated-shutdown.phases..timeout`) shorter than this setting, so the phases that matter for a graceful leave (`cluster-leave`, `cluster-sharding-shutdown-region`, `cluster-exiting`) finish inside the wait. ### When the actor system stops by itself If the actor system terminates while the application runs (for example after the split brain resolver downed this node), the Spring context closes and the process exits with status 1, so Kubernetes or systemd restarts it. Set `spring.actor.shutdown.exit-process=false` to only close the context. Your code can wait for this with `SpringActorSystem.whenTerminated()`. ### Kubernetes: `terminationGracePeriodSeconds` and the `preStop` hook When Kubernetes stops a pod it runs the `preStop` hook, then sends `SIGTERM`, and sends `SIGKILL` once `terminationGracePeriodSeconds` has passed since the start, whatever is still running. A pod killed with `SIGKILL` cannot leave the cluster and is seen as unreachable by the other nodes. So the grace period must cover all three steps: ``` terminationGracePeriodSeconds >= preStop sleep + web server drain (spring.lifecycle.timeout-per-shutdown-phase) + spring.actor.shutdown.timeout + a few seconds margin ``` A `preStop` sleep gives the readiness probe time to fail and the load balancer time to stop sending traffic before the application begins to shut down: ```yaml spec: terminationGracePeriodSeconds: 45 containers: - name: app lifecycle: preStop: exec: command: ["/bin/sh", "-c", "sleep 10"] ``` With matching application settings: ```yaml server: shutdown: graceful spring: lifecycle: timeout-per-shutdown-phase: 10s # web server drain actor: shutdown: timeout: 20s # actor system coordinated shutdown pekko: coordinated-shutdown: phases: cluster-leave: timeout: 10s cluster-sharding-shutdown-region: timeout: 10s ``` Here the worst case is 10s (`preStop`) + 10s (web drain) + 20s (actor system) = 40s, inside the 45s grace period. If you must keep `terminationGracePeriodSeconds: 30` with a 10s `preStop` sleep, lower `spring.actor.shutdown.timeout` (for example to `15s`) and the web drain timeout so the sum stays under 30s. ## Health checks With Spring Boot Actuator on the classpath, `/actuator/health` gets these components: | Component | When | Status | |---|---|---| | `actorSystem` | always | `UP` while the actor system runs, `DOWN` once it has terminated. Details: the system's `name`. | | `actorCluster` | `spring.actor.provider=cluster` | `UP` when this node is an `Up` member; `OUT_OF_SERVICE` while it has not joined yet, is joining, weakly up, leaving or shutting down; `DOWN` when it was downed or removed, or other members report it unreachable | | `actorWarmup` | `spring.actor.provider=cluster` | `UP` when this node is an `Up` member, the cluster has at least `management.health.actor.warmup.min-members` (default 1) `Up` members, and the discovery store answers (with `jdbc` or `redis` discovery); `OUT_OF_SERVICE` otherwise | | `actorGeneration` (*new in the next release*) | `spring.actor.generation.color` and `management.health.actor.generation.enabled=true` | `UP` while this node's color is the active generation; `OUT_OF_SERVICE` otherwise, never `DOWN`. See [Deployments](deployments.md#requests-at-the-cutover). | `actorCluster` details hold this node's status (`selfStatus`, `NOT_JOINED` before it joins), whether it is unreachable (`selfUnreachable`), the member count (`members`) and the unreachable count (`unreachable`), never addresses. An unreachable peer shows only in the count: one partitioned peer does not make every node unhealthy. `actorWarmup` details hold `selfUp`, `upMembers`, `minMembers` and `discovery` (`REACHABLE`, `UNREACHABLE` or `NOT_USED`). `management.health.actor.enabled=false` turns all of them off. In cluster mode the starter puts `actorCluster` in the readiness group (*new in the next release*; with 1.1.0, set `management.endpoint.health.group.readiness.include: readinessState,actorCluster` yourself). A pod gets traffic only once it is a cluster member and stops getting it as soon as it leaves. This applies when Spring Boot's probes are on (`management.endpoint.health.probes.enabled: true`, or on Kubernetes) and the application doesn't set `management.endpoint.health.group.readiness.include` itself; an include of your own replaces it. `management.health.actor.readiness.enabled: false` turns it off. `actorCluster` stays out of liveness: a node that is still joining is not broken, and restarting it would only delay the join. Cluster Bootstrap reaches pods through Pekko Management, not through the readiness-gated Service, so a cluster still forms while no pod is ready yet. ### Actuator on its own port Actuator's endpoints (`/actuator/health`, `/actuator/metrics`, `/actuator/prometheus`, `/actuator/info`) tell anyone who can call them about the application. Serve them on a separate port, so the network can open the application port to clients and the Actuator port only to monitoring and the kubelet: ```yaml server: port: 8080 # application traffic management: server: port: 8081 # Actuator: probes and Prometheus ``` Point the probes, the ServiceMonitor or PodMonitor and any `prometheus.io/port` annotation at `8081`, and let a NetworkPolicy admit `8081` only from the monitoring namespace. The kubelet's probes come from the node, which most network plugins let through whatever the policy says; if yours doesn't, add an `ipBlock` for the node addresses on `8081`. The [Kubernetes example](../../examples/kubernetes.md) does all of this. ### Warm-up In cluster mode the starter adds a third health group beside Spring Boot's `liveness` and `readiness`: `warmup` (`/actuator/health/warmup`), with the `actorWarmup` component. It answers "can this node be activated?", which a delivery pipeline asks before it switches traffic to a new deployment ([Blue-green](deployments.md#blue-green)): | Group | Question | Who asks | Depends on traffic | |---|---|---|---| | `liveness` | Restart this pod? | kubelet | no | | `readiness` | Send this pod traffic? | the Service | yes | | `warmup` | Is this pod ready to be activated? | the delivery pipeline | no | Set `min-members` to the number of members a new deployment must have before it takes traffic: ```yaml management: health: actor: warmup: min-members: 2 ``` Like `actorCluster`, keep `actorWarmup` out of liveness. A group named `warmup` in `management.endpoint.health.group` replaces the starter's. The group shows components and details as the main health endpoint does (`management.endpoint.health.show-details`). ## Production checklist Go through this list before the first release of a clustered application. On Kubernetes, the [Kubernetes example](../../examples/kubernetes.md)'s `base/` is the minimum setup to start from: the RBAC for discovery, the cluster ports and NetworkPolicy, the probes on their own port, the `preStop` hook and the grace period, a rolling update that never shrinks the cluster, and a PodDisruptionBudget. Its tests check that the grace period covers the shutdown it has to wait for. **Cluster formation and downing** - [ ] Every node uses the same `spring.actor.name`. - [ ] Nodes find each other through `seed-nodes` or `join: discovery`, not `join-self` ([Cluster Formation](../cluster/cluster-formation.md)). - [ ] The downing strategy fits the cluster. The default is `keep-majority`; `none` logs a warning ([Split Brain and Leases](../cluster/split-brain-and-leases.md)). - [ ] If a singleton or a shard must never run on two nodes at once, it uses a lease (`singleton.use-lease`, `sharding.use-lease`), and the lease store stays up: an outage longer than 110 s stops them ([When the lease store is down](../cluster/split-brain-and-leases.md#when-the-lease-store-is-down)). - [ ] On Kubernetes, a PodDisruptionBudget with `maxUnavailable: 1` covers the pods, so a node drain moves one node's shards at a time. - [ ] The network lets pods reach each other on the remoting port (`25520` by default) and the Pekko Management port. The [Kubernetes example](../../examples/kubernetes.md) lists the rules to ask for. - [ ] With `jdbc` or `redis` discovery or leases, only the nodes can write the store: a dedicated Redis ACL user or database user, TLS and auth ([Securing the discovery store](../cluster/cluster-formation.md#securing-the-discovery-store)). **Messages** - [ ] Every message that crosses nodes (sharded commands, replies, topic messages) implements `JsonSerializable` or `CborSerializable`. The Kubernetes example also sets `spring.actor.pekko.actor.allow-java-serialization: off`. - [ ] Message changes stay readable by the previous version during a rolling or canary release ([Message compatibility](deployments.md#message-compatibility-across-versions)). **Shutdown** - [ ] `server.shutdown: graceful` is set. - [ ] `terminationGracePeriodSeconds` covers the `preStop` sleep, the web drain and `spring.actor.shutdown.timeout` ([above](#kubernetes-terminationgraceperiodseconds-and-the-prestop-hook)). - [ ] `spring.actor.shutdown.exit-process` stays `true`, so a downed node restarts. **Health and monitoring** - [ ] The readiness group includes `actorCluster` (the default with probes on); liveness does not. - [ ] Actuator runs on its own port (`management.server.port`), open only to monitoring and the kubelet ([above](#actuator-on-its-own-port)). - [ ] `actor-metrics` is on the classpath and Prometheus scrapes `/actuator/prometheus`. - [ ] The dashboard and alert rules from `monitoring/` are installed ([Monitoring](monitoring.md#dashboard-and-alerts)). - [ ] `spring.actor.metrics.path-tag-limit` stays `0`, or is small, so the series count does not grow with the number of actors. **Data** - [ ] With `actor-jdbc` or `actor-persistence`, `initialize-schema` is `never` and the tables come from your Flyway or Liquibase migrations ([Configuration Reference](configuration.md#database-tables)). - [ ] State that must survive a restart or a blue-green switch lives in a database or event journal, not only in actor memory. **Blocking work** - [ ] Actors that call blocking I/O (JDBC, blocking HTTP clients) run on `withBlockingDispatcher()` or a dispatcher of their own ([Dispatchers](../core/dispatchers.md)). - [ ] Actors that serve requests have a bounded mailbox (`MailboxConfig.bounded(n)`), so a slow actor with retrying callers can't fill the heap ([Mailboxes](../core/dispatchers.md#mailboxes)). ## Native images (GraalVM) !!! warning "Experimental" No native image of an actor application has been built and run in this project yet. The `Native image` workflow (`.github/workflows/native-image.yml`) builds the `simple` example every week. Until it passes, treat native images as experimental. Spring AOT reads `META-INF/spring/aot.factories` during a native build. The starter's modules use it to register these runtime hints: - Pekko's configuration files: every `reference.conf`, plus the `version.conf` and `pekko-http-version.conf` they include, and your `application.conf` if you have one. - The starter's classes that Pekko creates by name from configuration: the executor of a bean-backed dispatcher, the cluster discovery and lease adapters, the serializer for traced messages, and the persistence database provider. Also the Pekko Jackson serializers the starter configures. - `AskCommand`'s reply address, which Jackson writes into every ask that crosses nodes. - The schema files of `actor-jdbc`, `actor-persistence` and `actor-projection`. ### Your message classes Jackson reads and writes your messages by reflection whenever Pekko serializes them. That covers messages that cross nodes (sharded commands, replies, topic messages) and the events and state of event-sourced actors. Pekko writes each message's class name into the serialized form and loads the class by that name when it reads the message, so register every concrete message class, not only the `JsonSerializable` interface. `@RegisterReflectionForBinding` on a configuration class registers each class with its constructors, fields and property types: === "Java" ```java import org.springframework.aot.hint.annotation.RegisterReflectionForBinding; import org.springframework.context.annotation.Configuration; @Configuration @RegisterReflectionForBinding({HelloActor.SayHello.class, OrderPlaced.class}) public class NativeHintsConfiguration {} ``` === "Kotlin" ```kotlin import org.springframework.aot.hint.annotation.RegisterReflectionForBinding import org.springframework.context.annotation.Configuration @Configuration @RegisterReflectionForBinding(HelloActor.SayHello::class, OrderPlaced::class) class NativeHintsConfiguration ``` Messages between actors in one JVM aren't serialized (Pekko's `serialize-messages` is `off` by default), so they need no hints. To register classes you can't list in an annotation, write a `RuntimeHintsRegistrar` and import it with `@ImportRuntimeHints`. ### Pekko's own classes Pekko 1.1 ships no native image metadata. It creates its extensions, mailboxes, serializers, loggers and actor ref providers by reflection, from the class names in its `reference.conf`, and the starter's hints don't cover them. One way to collect them is the GraalVM tracing agent. Run the application and its tests on the JVM with `-agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image//`, use the features you need (cluster, sharding, persistence), and check in the generated files. The `actor-metrics` Java agent (`-javaagent:actor-metrics--agent.jar`) can't attach to a native image. ## Related - [Monitoring](monitoring.md): meters, the `actors` endpoint, tracing, dashboard and alerts - [Deployments](deployments.md): rolling, canary and blue-green releases - [Configuration Reference](configuration.md): every key on this page - [Kubernetes example](../../examples/kubernetes.md): manifests that apply these settings --- # Monitoring This guide covers how to see what your actors do in production: Micrometer meters for actors, mailboxes, dispatchers, the cluster and sharding; the read-only `actors` Actuator endpoint; traces that cross `tell` and `ask`; log lines with actor context; and a ready-made Grafana dashboard with Prometheus alerts. None of it needs a Java agent. An optional agent adds a few more meters (see [The optional Java agent](#the-optional-java-agent)). !!! info "Incubating" `actor-metrics` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. ## Setup Add `actor-metrics`, Actuator and a Micrometer registry (Prometheus here): === "Gradle" ```groovy dependencies { implementation 'io.github.seonwkim:actor-metrics:1.1.0' implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'io.micrometer:micrometer-registry-prometheus' } ``` === "Maven" ```xml io.github.seonwkim actor-metrics 1.1.0 org.springframework.boot spring-boot-starter-actuator io.micrometer micrometer-registry-prometheus ``` Expose the Prometheus endpoint: ```yaml management: endpoints: web: exposure: include: health,info,metrics,prometheus ``` That is all. With a `MeterRegistry` bean (Actuator registers one), every actor the starter spawns is metered. `spring.actor.metrics.enabled=false` turns every meter on this page off. ## Actor meters The actor system the starter builds records these from hooks it owns: a behavior interceptor, an instrumented default mailbox and the default dispatchers' executors. | Meter | Type | Tags | What | |---|---|---|---| | `actor.message.processed` | Counter | `actor.class`, `dispatcher`, `system` | Messages actors processed | | `actor.message.processing.time` | Timer | `actor.class`, `dispatcher`, `system` | Time spent processing a message | | `actor.message.failures` | Counter | `actor.class`, `dispatcher`, `system` | Messages whose processing threw | | `actor.lifecycle.restarts` | Counter | `actor.class`, `dispatcher`, `system` | Restarts by supervision | | `actor.lifecycle.active` | Gauge | `actor.class`, `dispatcher`, `system` | Actors running | | `actor.mailbox.size` | Gauge | `actor.class`, `dispatcher`, `system` | Messages waiting in mailboxes | | `actor.mailbox.time` | Timer | `actor.class`, `dispatcher`, `system` | Time a message waited in the mailbox | | `actor.dispatcher.threads` | Gauge | `dispatcher`, `system` | Threads in the dispatcher's pool | | `actor.dispatcher.threads.active` | Gauge | `dispatcher`, `system` | Threads running tasks | | `actor.dispatcher.queued` | Gauge | `dispatcher`, `system` | Tasks waiting for a thread | - `actor.class` is the simple name of the actor's class (for a sharded actor, its `SpringShardedActor` class), `dispatcher` the Pekko dispatcher id (`pekko.actor.default-dispatcher`), `system` the actor system's name. - Meters are per actor class, not per actor, so the series count does not grow with the number of actors: 10,000 entities of one class have the same series as one. A test spawns 10,000 actors and checks it. - **Path tags** are opt-in and capped: `spring.actor.metrics.path-tag-limit=50` adds `actor.path` to the `actor.message.*` meters for the first 50 actor paths seen, and `actor.path=other` for every other actor. What is not covered: - Mailbox meters and `actor.lifecycle.active` count actors on the default mailbox. An actor spawned with a bounded or a configured mailbox keeps that mailbox and has only the `actor.message.*` and restart meters. - Dispatcher meters cover the default and the blocking dispatcher (and dispatchers that inherit their executor) on Pekko's fork-join or thread-pool executor. A dispatcher on a Spring `Executor` bean is measured by Spring Boot's own executor metrics; one on virtual threads has no pool to measure. - A behavior from `SpringActorBehavior.wrap` (a raw Pekko behavior) is metered outside its own supervision, so its failures and restarts are not seen. ### Overhead `ActorMetersBenchmark` (`./gradlew :actor-autoconfigure:actorMetersBenchmark`) sends bursts of 1,000,000 tells to one actor in two actor systems side by side, one with the meters off and one with them on, alternating rounds. On an Apple M5 laptop with Java 21 and a `SimpleMeterRegistry` (the machine was busy with other builds, so treat the numbers as rough): | | ns per message (median of 15 rounds) | |---|---| | meters off | 126 | | meters on | 379 | | overhead | about 250 | The cost per message is two timer updates (processing time and time in mailbox), four `System.nanoTime()` calls and one small object in the mailbox; `actor.message.processed` reads the processing timer's count and costs nothing. An actor that does real work (microseconds per message) pays a small fraction of that; one that only forwards messages pays about three times the bare cost. Run the benchmark on your hardware before relying on these numbers, and set `spring.actor.metrics.enabled=false` where the overhead matters more than the meters. ## Cluster and sharding meters With `spring.actor.provider=cluster`, these meters are added too. | Meter | Type | Tags | What | |---|---|---|---| | `actor.cluster.members` | Gauge | none | Members this node sees | | `actor.cluster.unreachable` | Gauge | none | Of them, how many are unreachable | | `actor.cluster.leader` | Gauge | none | `1` while this node is the leader, else `0`. Pekko's leader is the Up member with the lowest address, not the oldest | | `actor.cluster.singleton.host` | Gauge | none | `1` while this node runs the cluster singletons (it is the oldest member that is up and has `spring.actor.cluster.singleton.role`, if set), else `0` | | `actor.cluster.events` | Counter | `event` | Cluster events this node received after the application started: `MemberUp`, `MemberRemoved`, `UnreachableMember` and the other cluster event types. Every type has a series from the start, so a dashboard sees `0`, not a gap | | `actor.sharding.regions` | Gauge | `type` | Shard regions that host the entity type in the cluster | | `actor.sharding.shards` | Gauge | `type` | The entity type's shards on this node | | `actor.sharding.entities` | Gauge | `type` | The entity type's running entities on this node | The `actor.sharding.*` gauges ask every shard region in the cluster, so a scrape never waits for the answer: each read shows the answer to the previous read. Sum `actor.sharding.entities` over the nodes for the cluster total. Pekko reports no rebalance events, so there is no rebalance counter. A shard that moves shows up as `actor.sharding.shards` going down on one node and up on another. Alert on `actor.cluster.unreachable > 0` for longer than the split brain resolver's `stable-after`, and on a `members` count below the replica count. The [alert rules](#dashboard-and-alerts) do the first. ### Prometheus names Micrometer's Prometheus registry turns the dots into underscores and adds a suffix per type: | Meter type | Example | Prometheus series | |---|---|---| | Counter | `actor.message.processed` | `actor_message_processed_total` | | Timer | `actor.mailbox.time` | `actor_mailbox_time_seconds_count`, `_seconds_sum`, `_seconds_max` (and `_seconds_bucket` with histograms on) | | Gauge | `actor.cluster.members` | `actor_cluster_members` | Tags become labels the same way: `actor.class` is `actor_class`. ## The `actors` endpoint With Actuator on the classpath, cluster mode adds a read-only `actors` endpoint. Like every Actuator endpoint except `health`, it is not exposed over HTTP until you name it: ```yaml management: endpoints: web: exposure: include: health,actors ``` `GET /actuator/actors` returns: - `node`: this node's address. - `cluster`: this node's view of the cluster: its own status (`selfStatus`), whether it is unreachable or terminated, the member and unreachable counts, whether it is the `leader` and the `singletonHost`, and `nodes`, each member oldest first with its `address`, `status`, `roles` and whether it is `reachable`. - `sharding`: for each sharded entity type, its `type`, the `regions` in the cluster, and the `shards` and `entities` on this node. A read asks every shard region, so it can take up to 3 seconds. `management.endpoint.actors.access=none` turns the endpoint off. ## Health The `actorSystem` and `actorCluster` health components are described in [Running in Production](production.md#health-checks). ## Tracing With an `ObservationRegistry` bean (Spring Boot Actuator creates one) and a tracer such as `micrometer-tracing-bridge-otel` or `micrometer-tracing-bridge-brave`, the trace of the current request crosses `tell` and `ask`. Without an `ObservationRegistry`, messages are sent as they are and nothing is added. - Sending a message in an observation (an HTTP request, another actor's message) creates an `actor.send` span (`tell Order`, `ask GetBalance`). For `ask` it ends when the reply or the timeout arrives. - The receiving actor handles the message inside an `actor.receive` span, a child of the send. Its log lines carry `traceId` and `spanId` in the MDC, as Spring Boot's tracing sets them. - Between nodes, sharded messages and messages to remote actors carry the W3C `traceparent` fields next to the message, which keeps its own serializer (`JsonSerializable`, `CborSerializable`). - Spans carry the low-cardinality tags `actor.operation` and `actor.message` (the message class); the receive span also has the actor path as a high-cardinality tag. The trace is the observation current on the sending thread. A `tell` or `ask` from a `CompletionStage` callback (`getOrSpawn().thenCompose(actor -> actor.ask(...))`) runs on an actor thread with no observation, so it starts no span. Get the handle first, then send from the request's thread, or carry the context into the callback with Micrometer's `ContextSnapshot`. In Kotlin, `awaitGetOrSpawn` followed by `awaitAsk` in a `suspend` function avoids the callback. Messages that `ask` replies are not traced: the caller is already in the trace. Messages sent through a plain `SpringActorRef` (a `replyTo`, a ref inside a message) are not traced either; handles from `SpringActorSystem`, `getSelf()`, children, the receptionist and sharding are. ## Logs Actor log lines carry MDC values: the actor path and system, any static or per-message MDC you add, actor tags, and with tracing, `traceId` and `spanId`. [Logging with MDC and Tags](../core/logging.md) shows how to add them and how to print them with Logback, also as JSON. ## Dashboard and alerts The repository's [`monitoring/`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/monitoring) directory has a Grafana dashboard and Prometheus alert rules for the meters on this page, under their [Prometheus names](#prometheus-names). A test (`MonitoringFilesTest`) checks that every metric they query is a meter described on this page. ### The Actors dashboard `monitoring/grafana/actor-dashboard.json`. [Set up Grafana](#set-up-grafana) loads it; you can also import it by hand and pick your Prometheus data source. The variables `instance` and `system` filter by instance and actor system. | Row | Panels | |---|---| | Messages | Messages processed per second, message failures per second, average and longest processing time (per actor class) | | Mailboxes and actors | Messages waiting in mailboxes, average time in mailbox, running actors, restarts | | Dispatchers | Pool threads, tasks waiting for a thread | | Cluster | Members, unreachable, leader, singleton host, members by node, cluster events | | Sharding | Entities by type, shards by node, shard regions | ### Alert rules `monitoring/prometheus/actor-alerts.yaml` is a `PrometheusRule` for the Prometheus Operator. Without the operator, its `spec` is a plain rules file: ```bash yq '.spec' monitoring/prometheus/actor-alerts.yaml > actor-alerts.rules.yml ``` | Alert | Fires when | Severity | |---|---|---| | `ActorClusterMemberUnreachable` | a member is unreachable for 5 minutes | warning | | `ActorClusterNoLeader` | no node is the leader for 5 minutes | critical | | `ActorClusterViewsDiffer` | nodes see different member counts for 10 minutes | warning | | `ActorClusterSingletonMissing` | no node runs the singletons for 5 minutes | critical | | `ActorMessageFailures` | an actor class keeps failing messages for 10 minutes | warning | | `ActorRestartsFrequent` | an actor class restarts more than 10 times in 15 minutes | warning | | `ActorMailboxBacklog` | more than 1,000 messages wait for an actor class on one instance for 10 minutes | warning | | `ActorMailboxWaitHigh` | messages wait more than a second on average for 10 minutes | warning | | `ActorDispatcherSaturated` | every thread of a dispatcher is busy and more than 100 tasks wait for 10 minutes | warning | The thresholds are starting points; tune them to your load. The rules group by `namespace`, the label the Prometheus Operator adds; with another setup, change it to the label that tells your applications apart. ### Set up Grafana #### Download the files for your version Use the files of the release you depend on: the dashboard on `main` may query meters a later release added. Each GitHub release attaches them, with the version in their names: ```text https://github.com/seonWKim/actor-spring-boot-starter/releases/download/v/actor-grafana-dashboard-.json https://github.com/seonWKim/actor-spring-boot-starter/releases/download/v/actor-prometheus-alerts-.yaml https://github.com/seonWKim/actor-spring-boot-starter/releases/download/v/actor-monitoring-.zip ``` The dashboard carries the version as a `v` tag and at the end of its description. The zip holds the `monitoring/` directory for that version: the dashboard, the alert rules, the provisioning files and `docker-compose.yml`. #### Provisioning To load the dashboard into your own Grafana without clicks, copy the two provisioning files into Grafana's provisioning directory (`/etc/grafana/provisioning` by default) and the dashboard into the directory the dashboard provider reads: | File | Goes to | Change | |---|---|---| | `monitoring/grafana/provisioning/datasources/prometheus.yaml` | `provisioning/datasources/` | `url`: your Prometheus. Skip the file if Grafana already has a default Prometheus data source | | `monitoring/grafana/provisioning/dashboards/actor.yaml` | `provisioning/dashboards/` | `options.path` if you keep dashboards elsewhere | | `monitoring/grafana/actor-dashboard.json` | `/var/lib/grafana/dashboards/actor/` (the provider's `options.path`) | | The dashboard's **Data source** variable starts on Grafana's default Prometheus data source. #### Run it locally With your application running on port 8080 and exposing `/actuator/prometheus`: ```bash cd monitoring # or the unzipped actor-monitoring-/ docker compose up -d ``` - Grafana: (`admin` / `admin`), dashboard **Actors** in the **Actors** folder. - Prometheus: , the alert rules under *Alerts*, the scrape target under *Status > Targets*. Prometheus scrapes `host.docker.internal:8080/actuator/prometheus`. Set `ACTOR_TARGET` for another address: ```bash ACTOR_TARGET=host.docker.internal:9000 docker compose up -d docker compose down -v # stop and remove the containers and the generated files ``` The `setup` service writes the scrape target and turns `actor-alerts.yaml` into a plain rules file (its `spec`) before Prometheus starts. The cluster alerts group by `namespace`, which a local stack doesn't have, so they treat everything Prometheus scrapes as one group. ### Installing on Kubernetes With the Prometheus Operator in the cluster (for example kube-prometheus-stack), the Kubernetes example installs both in one command: ```bash cd example/kubernetes ./scripts/monitoring.sh # apply; `render` prints the manifests, `delete` removes them ``` It applies a ServiceMonitor that scrapes `/actuator/prometheus`, the `actor-alerts` PrometheusRule, and the dashboard as a ConfigMap labelled `grafana_dashboard: "1"`, which Grafana's dashboard sidecar loads. Your Prometheus must select them: kube-prometheus-stack selects rules and monitors by its release label unless you set `prometheus.prometheusSpec.ruleSelectorNilUsesHelmValues=false` and `serviceMonitorSelectorNilUsesHelmValues=false`, and its sidecar searches other namespaces only with `grafana.sidecar.dashboards.searchNamespace=ALL`. ## The optional Java agent The ByteBuddy agent in `actor-metrics` instruments Pekko internals for a few meters no public hook exposes (stash size, dead letters, unhandled messages, scheduled tasks, per-message-type tags). It breaks more easily with Pekko upgrades, so use it only when you need those. ```bash ./gradlew :actor-metrics:agentJar java -javaagent:actor-metrics-{version}-agent.jar -jar your-app.jar ``` With the agent attached, it records the message, mailbox and lifecycle meters below under the same names, and the hooks register only `actor.message.failures` and the `actor.dispatcher.*` meters: no meter is registered twice. ### Agent meters | Meter | Type | Tags | What | |---|---|---|---| | `actor.lifecycle.created` | Counter | `actor.class` | Actors created | | `actor.lifecycle.terminated` | Counter | `actor.class` | Actors terminated | | `actor.lifecycle.restarts` | Counter | `actor.class` | Supervision restarts | | `actor.lifecycle.resumes` | Counter | `actor.class` | Supervision resumes | | `actor.lifecycle.active` | Gauge | none | Currently active actors | | `actor.mailbox.size` | Gauge | `actor.class` | Mailbox queue size | | `actor.mailbox.size.max` | Gauge | `actor.class` | Peak mailbox size | | `actor.mailbox.time` | Timer | `actor.class`, `message.type` | Time in mailbox | | `actor.mailbox.overflow` | Counter | none | Bounded mailbox drops | | `actor.message.processed` | Counter | `actor.class`, `message.type` | Messages processed | | `actor.message.processing.time` | Timer | `actor.class`, `message.type` | Processing duration | | `actor.stash.size` | Gauge | `actor.class` | Stashed messages | | `system.dead-letters` | Counter | none | Undeliverable messages | | `system.unhandled-messages` | Counter | none | Unhandled messages | | `scheduler.tasks.scheduled` | Counter | none | Tasks via `scheduleOnce` | Typed actors use `actor.class=TypedActor`; use `message.type` to tell behaviors apart. The agent records no failure meter of its own: failures are `actor.message.failures`, which the hooks record with or without the agent. ### Agent settings The agent reads environment variables, not Spring keys: `ACTOR_METRICS_ENABLED`, `ACTOR_METRICS_INSTRUMENT_`, `ACTOR_METRICS_TAG_` and `ACTOR_METRICS_SAMPLING_RATE`. The [Configuration Reference](configuration.md#metrics-agent-environment-variables-actor_metrics_) describes each. Module ids: `actor-lifecycle`, `mailbox`, `message-processing`, `system`, `scheduler`, `stash`. To set tags or sampling in code, declare your own `MetricsRegistry` bean: === "Java" ```java import io.github.seonwkim.actor.metrics.core.MetricsConfiguration.SamplingConfig; import io.github.seonwkim.actor.metrics.core.MetricsRegistry; import io.github.seonwkim.actor.metrics.micrometer.MicrometerMetricsRegistryBuilder; @Configuration public class ActorMetricsConfig { @Bean public MetricsRegistry actorMetricsRegistry(MeterRegistry meterRegistry) { return MicrometerMetricsRegistryBuilder.fromEnvironment(meterRegistry) .tag("custom-tag", "value") .sampling(SamplingConfig.rateBased(0.1)) .build(); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.metrics.core.MetricsConfiguration.SamplingConfig import io.github.seonwkim.actor.metrics.core.MetricsRegistry import io.github.seonwkim.actor.metrics.micrometer.MicrometerMetricsRegistryBuilder @Configuration class ActorMetricsConfig { @Bean fun actorMetricsRegistry(meterRegistry: MeterRegistry): MetricsRegistry = MicrometerMetricsRegistryBuilder.fromEnvironment(meterRegistry) .tag("custom-tag", "value") .sampling(SamplingConfig.rateBased(0.1)) .build() } ``` ### How the agent starts The agent must rewrite bytecode before Pekko classes load, but Micrometer only exists after Spring starts. So it starts in two steps: 1. **JVM startup:** `MetricsAgent.premain()` finds the modules through `ServiceLoader` and uses ByteBuddy to instrument Pekko classes. No meters are recorded yet. 2. **Spring context:** the auto-configuration creates a `MetricsRegistry` with a Micrometer backend and hands it to the agent. Meters start recording. The registry is created before the actor system bean. ## Troubleshooting | Problem | What to check | |---|---| | `/actuator/prometheus` is 404 | `prometheus` is in `management.endpoints.web.exposure.include` and `micrometer-registry-prometheus` is on the classpath. | | No `actor_*` series | `actor-metrics` is on the classpath and `spring.actor.metrics.enabled` is not `false`. Counters appear after the first message. | | No `actor_cluster_*` series | `spring.actor.provider` is `cluster`. | | No agent meters | The log has `[MetricsAgent] Metrics agent installed successfully`, and `-javaagent` is on the command line. | | Agent jar missing | Run `./gradlew :actor-metrics:agentJar`. | ## Related - [Running in Production](production.md): health checks and graceful shutdown - [Configuration Reference](configuration.md#metrics): the metrics keys - [Logging with MDC and Tags](../core/logging.md) - [Metrics example](../../examples/metrics.md) and [Kubernetes example](../../examples/kubernetes.md) --- # Deployments This guide covers how to release a new version of a clustered actor application without failing requests: rolling updates, canary releases and blue-green switches, and how to change messages so that two versions can run side by side. The commands come from the [Kubernetes example](../../examples/kubernetes.md) ([`example/kubernetes`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/kubernetes)), which runs the chat example as a three-pod cluster on a local kind cluster. The ideas apply to any platform. ## Choosing a strategy | Strategy | What runs | Traffic | Versions mix in one cluster | Script | |---|---|---|---|---| | Rolling update | One cluster; old and new pods side by side during the rollout | Moves pod by pod | Yes | `kubectl set image` | | Canary | One cluster; a few new pods join the running cluster | Share = canary pods / all pods | Yes | `scripts/canary.sh` | | Blue-green | Two separate clusters (blue and green) | Switches in one step | No | `scripts/blue-green.sh` | - Use a **rolling update** for most releases. It needs no extra capacity beyond one pod. - Use a **canary** when you want a few real requests on the new version first, with a quick way back. - Use **blue-green** when the new version cannot talk to the old one (an incompatible message change) or when you want to switch all traffic at once. It needs twice the pods for a while, and in-memory state does not move. All three rely on the [graceful shutdown](production.md#graceful-shutdown) settings: each old pod leaves the cluster on purpose, so its sharded entities and singletons move instead of waiting for the split brain resolver. ## Rolling update A rolling update replaces pods one at a time inside one cluster. The example's Deployment adds a new pod before it removes an old one, so the cluster never drops below its size: ```yaml spec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 # never fewer than 3 ready pods maxSurge: 1 # start one new pod before stopping an old one ``` Each new pod joins the running cluster. Its readiness probe includes `actorCluster`, so it gets traffic only once it is an `Up` member (see [Health checks](production.md#health-checks)). Then Kubernetes stops an old pod: the `preStop` sleep lets the load balancer drop it, and coordinated shutdown moves its entities to the other nodes. ```bash kubectl set image deployment/spring-actor spring-actor=spring-actor-chat:v2 -n spring-actor kubectl rollout status deployment/spring-actor -n spring-actor # Go back to the previous version kubectl rollout undo deployment/spring-actor -n spring-actor ``` ## Canary A canary runs a few pods of the new version in the same cluster as the main pods. `canary.sh start` copies the live Deployment as `spring-actor-canary` with the new image and a `track: canary` label. The Services select `app=spring-actor`, so they send the canary pods their share of the requests: with three main pods and one canary, about one in four. ```bash cd example/kubernetes scripts/canary.sh start spring-actor-chat:v3 # one canary pod; `start 2` for two scripts/canary.sh promote # roll the main pods to v3, then remove the canary # scripts/canary.sh abort # or remove the canary and keep the main pods as they are ``` Because the canary is a member of the same cluster, sharded entities can move to it and it exchanges messages with the old pods. Both versions must read each other's messages and entity state (see [Message compatibility](#message-compatibility-across-versions)). ## Blue-green Blue-green starts the new version as a second, separate cluster. `blue-green.sh deploy` copies the live Deployment as `spring-actor-green` with the new image, labels its pods `app=spring-actor-green`, and points its Kubernetes API discovery at that label (`--spring.actor.pekko.discovery.kubernetes-api.pod-label-selector=app=spring-actor-green`). So green forms its own cluster and never exchanges messages with blue. With `jdbc` or `redis` discovery there is no label to select: each color registers in the shared store under `-` (`spring-actor-system-green`), so Bootstrap hands green only green's pods. The generation record keeps `spring.actor.name` (or `spring.actor.generation.name`), so both colors read the same one. **Upgrading a running color in place.** Versions before this name registered every color under `spring.actor.name`. A rolling update onto this version would leave the new pods looking under `-`, where none of the running pods are. Release the upgrade as blue-green (the new color forms its own cluster anyway), or set `spring.actor.cluster.discovery.service-name` to the old name (`spring.actor.name`) for the rolling update. Before green starts, `deploy` also copies each NetworkPolicy that selects `app=spring-actor` (for example `spring-actor-green` from `spring-actor`, and `spring-actor-green-store` from `spring-actor-store` in the discovery overlays), with every `app=spring-actor` selector changed to `app=spring-actor-green`. Green gets the same restrictions as blue, and remoting (25520) and management (7626) open only between pods of the same color: blue and green cannot reach each other's cluster ports. A canary keeps `app=spring-actor`, so blue's policies cover it. ### The release pipeline A blue-green release runs in four stages. Each one waits for a signal before the next starts: | Stage | Command | Waits for | |---|---|---| | 1. Warm up | `blue-green.sh deploy ` | every green pod answers `UP` on `/actuator/health/warmup`, then is ready | | 2. Activate | `blue-green.sh activate` | the [generation endpoint](#the-active-generation) accepts green; then the HTTP Service's selector picks the green pods | | 3. Verify | `blue-green.sh verify` | the generation record says green, every pod of both colors reads its epoch (`node` in `GET /actuator/generation`), and the Service's ready endpoints are exactly the green pods | | 4. Retire | `blue-green.sh retire` | run it once green has served for a while; it deletes blue | ```bash cd example/kubernetes scripts/blue-green.sh deploy spring-actor-chat:v4 # start green beside blue and wait until it is warm scripts/blue-green.sh activate # green becomes the active generation; the Service selects it scripts/blue-green.sh verify # wait until only green pods serve # scripts/blue-green.sh rollback # activate blue again (a new epoch) and select it scripts/blue-green.sh retire # delete blue ``` The first stage gates on **warm-up**, not on `kubectl rollout status` or the Deployment's `Available` condition. Those follow traffic readiness, and in a pipeline where the standby color refuses traffic until it is activated they never come. The warm-up group says only that the pod can be activated: - the pod is an `Up` member of its cluster, - the cluster has at least `management.health.actor.warmup.min-members` `Up` members (the example sets 2), - and the discovery store answers, when the cluster forms through `jdbc` or `redis` discovery. It never depends on which color is active. The three probes stay apart: liveness says whether to restart the pod, readiness whether to send it traffic, and warm-up whether it can be activated (see [Health checks](production.md#warm-up)). In-memory state does not move: entities, singletons and topics start empty on green. Keep state that must survive the switch in a database or event journal both clusters read ([State in a Database](../data/state-in-a-database.md), [Event-Sourced Actors](../data/event-sourcing.md)). Until `retire`, `rollback` sends traffic back to blue, which still has its state. ### The active generation Which color is active is a record in the store the cluster already uses (Redis or the database), not only a Service selector. Each record is a **generation**: a color, an **epoch** that grows by one with every activation, the deployment operation ID that activated it, and when. The application can read it, and the pipeline changes it only through a compare-and-set: - **Competing deploys fail loudly.** An activation names the epoch it expects to be active. If another deploy activated in between, it is rejected (`EPOCH_MISMATCH`, HTTP 409) and nothing changes. Of several activations that expect the same epoch, exactly one wins. - **Retries are idempotent.** An activation carries an operation ID. Retrying it with the same color and expected epoch returns the generation it activated the first time (`ALREADY_ACTIVATED`, HTTP 200), even after the epoch has moved on. The same operation ID with another color or epoch is `OPERATION_CONFLICT` (409). A pipeline keeps the expected epoch and the operation ID it used, and sends both again when it retries. Make the operation ID one run of the pipeline, not the git tag: `@#`, such as `v1.4.0@d4e5f6a#8812`. A retry within the run reuses it, and a later run of the same tag (a re-release, or a rollback to it after its slot was retired) gets a new one. A bare tag can be activated only once: the second time it is `OPERATION_CONFLICT`. - **Old work stays fenced.** Blue, then green, then blue again gives epochs 1, 2 and 3. Work that blue stamped in its first turn carries epoch 1 and is refused in its second (epoch 3), because the epoch never goes back. Turn it on in each color with its color and a store: ```yaml spring: actor: generation: color: blue # green in the other deployment store: redis # jdbc: the actor_generation table; custom: your GenerationStore bean # name: orders # the record both colors share; default: spring.actor.name # refresh: 1s # how long a node reuses a read of the record management: endpoints: web: exposure: include: health,generation endpoint: generation: access: unrestricted # activation is a write: read-only by default ``` **The `generation` endpoint.** `GET /actuator/generation` returns this node's color, the active generation in the store (`active`) and what this node reads now (`node`, *new in the next release*). `POST /actuator/generation` with `color`, `expectedEpoch` (0 before the first activation) and `operationId` activates a color: ```bash curl -u deployer:$PASSWORD -X POST localhost:8080/actuator/generation \ -H 'Content-Type: application/json' \ -d '{"color":"green","expectedEpoch":1,"operationId":"release-2026-11-11-1"}' # {"outcome":"ACTIVATED","generation":{"color":"green","epoch":2,"operationId":"release-2026-11-11-1",...}} ``` **Verifying a switch.** A node reuses its read of the record for `spring.actor.generation.refresh`, so after an activation each node keeps stamping and checking with the old epoch for up to that long. `node` says what this node reads now: the generation (`active`), when it read it from the store (`readAt`), whether its own color is the active one (`colorActive`), whether it is warmed up (`warm`, from the `actorWarmup` health indicator; `null` outside cluster mode) and the build it runs (`build`, *new in the next release*: `version` from Spring Boot's build info, `springBoot { buildInfo() }`, and `commit` from `git.properties`, for example through the `com.gorylenko.gradle-git-properties` plugin; `null` without either). Reading the endpoint does not refresh the node's read. A pipeline knows the switch is done when every node of both colors reports the new epoch: ```bash curl -s localhost:8081/actuator/generation # {"deployment":"orders","color":"blue", # "active":{"color":"green","epoch":2,...}, # "node":{"active":{"color":"blue","epoch":1,...},"readAt":"2026-11-11T10:00:00.250Z","colorActive":true,"warm":true, # "build":{"version":"1.4.0","commit":"d4e5f6a"}}} # Every pod reads the record's epoch for pod in $PODS; do [ "$(kubectl exec "$pod" -- curl -s localhost:8081/actuator/generation | jq '.node.active.epoch')" = 2 ] || echo "$pod lags" done ``` `blue-green.sh verify` does this for every running pod of both colors, and skips a pod whose answer has no `node` (a version of the starter without it). With `EXPECTED_COMMIT` set, it also checks that every green pod runs that commit, so "green is live" means the build the pipeline deployed is live. Activation needs an authenticated user: a request without one is answered `401` (`UNAUTHENTICATED`). Secure the endpoint with Spring Security like any other write endpoint, for example with a role: === "Java" ```java @Bean SecurityFilterChain actuator(HttpSecurity http) throws Exception { return http.securityMatcher(EndpointRequest.to("generation")) .authorizeHttpRequests(requests -> requests .requestMatchers(HttpMethod.POST).hasRole("DEPLOYER") .anyRequest().permitAll()) .httpBasic(Customizer.withDefaults()) .csrf(csrf -> csrf.disable()) // called by a pipeline, not a browser session .build(); } ``` === "Kotlin" ```kotlin @Bean fun actuator(http: HttpSecurity): SecurityFilterChain = http.securityMatcher(EndpointRequest.to("generation")) .authorizeHttpRequests { it.requestMatchers(HttpMethod.POST).hasRole("DEPLOYER") .anyRequest().permitAll() } .httpBasic(Customizer.withDefaults()) .csrf { it.disable() } // called by a pipeline, not a browser session .build() ``` **Audit.** Every attempt that reaches the endpoint, or `DeploymentGeneration.activate` in your code, publishes an `ActivationEvent` (an `ApplicationEvent`) with the requested color, expected epoch, operation ID, the user's name and the result. The starter also logs it (`INFO` when accepted, `WARN` when rejected) and counts it in `actor.generation.activations`, tagged with `outcome`. A request that Spring Security turns away never reaches the endpoint, so it shows in Spring Security's events instead. **Fencing in your code.** Inject `DeploymentGeneration`. Without `spring.actor.generation.color` the starter's bean is a no-op (*new in the next release*): always active, `stamp()` returns 0 and nothing is stale, so the same code runs with and without blue-green. Your own `DeploymentGeneration` bean replaces it. Stamp a message with `stamp()` where the work starts (it fails when this node's color is not active). A message that implements `GenerationStamped` (a record with an `epoch` component does) can be checked where it runs by wrapping its handler with `ifCurrent` (*new in the next release*): a message of an older epoch is dropped and logged as a warning on the actor's log, and the handler does not run. === "Java" ```java record ChargeOrder(String orderId, long epoch) implements Command, GenerationStamped {} orders.tell(new ChargeOrder(orderId, generation.stamp())); // where the work starts .onMessage(ChargeOrder.class, generation.ifCurrent((ctx, msg) -> { payments.charge(msg.orderId()); // only for the active epoch return SpringActorBehavior.same(); })) ``` === "Kotlin" ```kotlin data class ChargeOrder(val orderId: String, override val epoch: Long) : Command, GenerationStamped orders.tell(ChargeOrder(orderId, generation.stamp())) // where the work starts .onMessage(ChargeOrder::class.java, generation.ifCurrent { _, msg -> payments.charge(msg.orderId) // only for the active epoch SpringActorBehavior.same() }) ``` The stamp is not added on send: messages are immutable, so the sender passes the epoch when it builds the message. With [reliable delivery](../core/reliable-delivery.md#stale-generation-not-the-owner-yet-or-anymore), call `check(epoch)` in the handler instead of `ifCurrent`. It throws `StaleGenerationException`, the retryable outcome, so the sender retries, while a dropped message would be acknowledged: === "Java" ```java sender.send(new ChargeOrder(orderId, generation.stamp()), key); .onMessage(ChargeOrder.class, (ctx, msg) -> { generation.check(msg.epoch()); // StaleGenerationException if it is old payments.charge(msg.orderId()); return SpringActorBehavior.same(); }) ``` === "Kotlin" ```kotlin sender.send(ChargeOrder(orderId, generation.stamp()), key) .onMessage(ChargeOrder::class.java) { _, msg -> generation.check(msg.epoch) // StaleGenerationException if it is old payments.charge(msg.orderId) SpringActorBehavior.same() } ``` A node reuses a read of the record for `spring.actor.generation.refresh` (1 second), so for up to that long after an activation elsewhere it still accepts the old epoch. Where that matters, keep the epoch with the data and compare it in the write itself (`UPDATE ... WHERE epoch <= ?`). **Stores.** `jdbc` keeps one row per activation in `actor_generation` (created with the other actor-jdbc tables): the primary key on deployment and epoch is the compare-and-set. `redis` keeps the record and the operation IDs in two hashes and changes them in one Lua script. Redis replicates asynchronously, so a failover can lose an activation it had just accepted; use `jdbc` where that is not acceptable. Your own `GenerationStore` bean replaces both, and must pass `GenerationStoreContract` from `actor-test`. ### Requests at the cutover In the example the Service selector switches the colors, and readiness does not depend on the color. So `deploy` waits for warm-up **and** then for the green pods to be ready. Warm-up alone is not enough there: a pod can be warm before its readiness probe first passes (the example's probe starts after 30 seconds), and a Service that selects only pods that are not ready yet has no endpoints. Measured on kind with `test-strategies.sh` (four workers asking sharded entities): | `deploy` waited for | Requests | Failed | Service served only green | |---|---|---|---| | warm-up only | 15,057 | 20, all within 10 seconds after `activate` | 15 seconds after `activate` | | warm-up, then ready (the script today) | 23,151 and 22,890 (two runs) | 0 and 0 | at the first check after `activate` | Blue keeps running and serving until `retire`, so a node whose proxy rules still point at blue for a moment after the switch still gets answers. **Readiness that follows the color** (*new in the next release*). With `management.health.actor.generation.enabled: true`, the `actorGeneration` health indicator is `UP` while this node's color is the active generation and `OUT_OF_SERVICE` otherwise, and with the probes on (`management.endpoint.health.probes.enabled: true`) the readiness group includes it. One load balancer target group (or one Service) can then hold both colors, and activation alone moves the traffic, without a selector change, a second target group or Kubernetes: 1. Deploy green beside blue. Green passes `/actuator/health/warmup` (warm-up ignores the color) and fails readiness. 2. `POST /actuator/generation` activates green. Within `spring.actor.generation.refresh` each node reads it: green turns `UP`, blue `OUT_OF_SERVICE`. 3. The load balancer's health checks admit green and drain blue. A color that loses activation stays `UP` for `management.health.actor.generation.grace` (default 30s), so the load balancer admits green before it drains blue. Set it to at least the time your load balancer takes to admit a target (its interval times its healthy threshold). During the grace blue still serves, as it does until `retire` in the selector mode, and work it stamps is refused as stale. While the store can't be read, each node keeps its last status, so an outage doesn't take both colors out. A node that starts with its color inactive gets no grace. Turn it on only where readiness should switch the colors: it also makes the standby's overall `/actuator/health` `OUT_OF_SERVICE`, and `kubectl rollout status` waits forever for a standby Deployment's pods. The example's `blue-green.sh` keeps the selector mode. In that mode the cutover waits for readiness to propagate: each pod's readiness probe has to pass (`periodSeconds` times `successThreshold` for the new color, `periodSeconds` times `failureThreshold` for the old one), then the endpoint controller and every node's kube-proxy update. **Shorter probe intervals shorten that window but don't close it**: without the grace, requests routed during it reach a pod that is about to leave or none at all. The grace keeps blue in the pool until green is in it. Measured on kind with `scripts/test-features.sh` (one Service selecting both colors, readiness probe every 5 seconds, failure threshold 3, grace 20s): every green pod was in the Service 5 seconds after activation, every blue pod out after 36, and none of 17,110 requests failed. The selector mode closes the window with draining: - switch with the Service selector (or another routing change) while both colors are ready, and keep the old pods running until `verify` shows the Service no longer selects them (`retire` comes last); - the `preStop` sleep (10 seconds in the example) keeps a terminating pod serving while the endpoint removal propagates; - `server.shutdown: graceful` finishes the requests the pod has already accepted. `scripts/test-strategies.sh` prints, for the blue-green step, how long the Service took to serve only green and how many requests failed from activation on. ## Testing the strategies under load `scripts/test-strategies.sh` runs all three strategies on the kind cluster from `setup-local.sh` while `scripts/load.sh` sends requests, and fails if any request failed: ```bash cd example/kubernetes ./setup-local.sh scripts/test-strategies.sh # rolling total=... ok=... failed=0 ok # canary total=... ok=... failed=0 ok # blue-green total=... ok=... failed=0 ok ``` It runs, in order: a rolling update to `v2` (120 seconds of load), a canary of `v3` that is then promoted (180 seconds), and a blue-green release of `v4` through the four stages above (90 seconds, then `retire`). Each step's load runs four workers that ask sharded entities (`/hello?message=hi&entityId=e<0-49>`). What it checks and what it does not: - `load.sh` counts a request as ok only when the actor replied. The chat app answers `200` with `Request timed out ...` when an ask fails, so the HTTP status alone would hide lost messages. - The new versions are retags of the same image, so it checks the rollout mechanics (joining, leaving, entities moving, the Service switching), not a change in the code. ## Message compatibility across versions **Rolling updates and canaries mix versions in one cluster.** Old and new pods exchange messages, and a sharded entity can move from an old pod to a new one. Every message and every piece of entity state that crosses nodes must be readable by both versions: - Add fields as optional. The old version must accept a message with the new field, and the new version a message without it. - Don't rename or remove fields or message types in the same release. - Keep each type on the same serializer (`JsonSerializable` or `CborSerializable`). - Make an incompatible change in two releases: first one that reads both formats, then one that writes the new format. For example, a second release adds an optional field to a command: === "Java" ```java // v1 public static class SayHello extends AskCommand implements Command { public final String message; public SayHello(String message) { this.message = message; } } // v2: a new, optional field. Messages from v1 nodes don't have it. public static class SayHello extends AskCommand implements Command { public final String message; @Nullable public final String language; public SayHello(String message, @Nullable String language) { this.message = message; this.language = language; } } ``` === "Kotlin" ```kotlin // v1 class SayHello(val message: String) : AskCommand(), Command // v2: a new, optional field. Messages from v1 nodes don't have it. class SayHello(val message: String, val language: String? = null) : AskCommand(), Command ``` The starter's build checks this on every change: `MixedVersionMessageTest` runs two nodes in one JVM, one with a message class and one with the same class plus a field, and sends a message each way between sharded entities. The old node reads the new message and ignores the field it doesn't know; the new node reads the old message with the missing field as `null`. The test covers `JsonSerializable` messages with the starter's default Jackson settings. It does not cover a renamed or removed field, a renamed class, or stored events and snapshots. To run the same check on your own messages, see [Two versions of a message in one cluster](../testing.md#two-versions-of-a-message-in-one-cluster). On Kubernetes, this was also measured on kind with a canary of the chat app: adding a field to `SayHello` lost no requests (28,842 of 28,842), while renaming the class lost 104 of 7,105, which timed out because the old nodes could not read the new type. **Blue-green never mixes versions.** The two clusters never exchange messages, so the message format can change freely. Stored state is different: events and snapshots in a journal or database must still be readable by the new version (see [Event-Sourced Actors](../data/event-sourcing.md)). ## Rollback | Strategy | How to go back | |---|---| | Rolling update | `kubectl rollout undo deployment/spring-actor -n spring-actor`: a rolling update in the other direction, so the same compatibility rules apply | | Canary | `scripts/canary.sh abort` removes the canary pods; the main pods were never changed | | Blue-green | `scripts/blue-green.sh rollback` until `retire`; blue still has its in-memory state | ## Related - [Running in Production](production.md): graceful shutdown, health checks and the production checklist - [Monitoring](monitoring.md): watch `actor.cluster.members` and `actor.cluster.unreachable` during a rollout - [Kubernetes example](../../examples/kubernetes.md): the manifests and scripts on this page - [Sharded Actors](../cluster/sharded-actors.md) --- # Configuration Reference This page lists every configuration key the starter and its modules read, with its default and what it does. The keys are published as Spring Boot configuration metadata (`META-INF/spring-configuration-metadata.json` in the `actor-autoconfigure` and `actor-metrics` jars), so IDEs offer completion and documentation for them in `application.yml` and `application.properties`. There are three kinds of settings: - **Typed keys** (`spring.actor.*`, `management.*`): bound to a properties class and checked at startup. - **Raw Pekko keys** (any other key under `spring.actor.*`): passed to Pekko as they are. - **Environment variables** (`ACTOR_METRICS_*`): read only by the optional metrics Java agent. ## Where the keys live All typed keys are bound by three `@ConfigurationProperties` classes. The store and persistence modules (`actor-jdbc`, `actor-redis`, `actor-persistence`, `actor-projection`) have no properties class of their own: their keys are part of `ActorProperties`, and they take their connection from the application's `DataSource` or `RedisConnectionFactory`. | Class | Prefix | Module | |---|---|---| | `ActorProperties` | `spring.actor` | `actor-autoconfigure` (in every starter) | | `PekkoManagementProperties` | `spring.actor.pekko.management` | `actor-autoconfigure` | | `ActorMetricsProperties` | `spring.actor.metrics` | `actor-metrics` | Typed keys are validated when the application starts. A bad value stops it with a message that names the key, for example `spring.actor.remote.port must be between 0 and 65535, got 70000`. ## Actor system | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.enabled` | `true` | none | Whether the starter starts an actor system. `false` turns off every actor auto-configuration while the starter stays on the classpath. | | `spring.actor.name` | `system` | `pekko.name` | Name of the actor system. Letters, digits, `-` and `_`, starting with a letter or digit. Nodes of one cluster must use the same name. | | `spring.actor.provider` | `local` | `pekko.actor.provider` | How actors reach each other: `local` (one JVM), `remote` (reachable from other nodes, no cluster membership) or `cluster`. `remote` and `cluster` need `actor-spring-boot-starter-cluster`. | ## Remoting Used with `provider: remote` or `provider: cluster`. | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.remote.hostname` | Pekko's default | `pekko.remote.artery.canonical.hostname` | Host name or address other nodes use to reach this node. | | `spring.actor.remote.port` | Pekko's default (`25520`) | `pekko.remote.artery.canonical.port` | Port this node listens on for other nodes, `0` to `65535`. `0` picks a free port. | | `spring.actor.remote.bind-hostname` (*new in the next release*) | `hostname` | `pekko.remote.artery.bind.hostname` | Address to listen on when `hostname` is not one of this host's addresses (a DNS name, NAT, a load balancer). Usually `0.0.0.0`. | | `spring.actor.remote.bind-port` (*new in the next release*) | `port` | `pekko.remote.artery.bind.port` | Port to listen on when it differs from `port` (NAT, port mapping). | | `spring.actor.serialization.application-object-mapper` (*new in the next release*) | `false` | none | Write `JsonSerializable` messages, events and snapshots with a copy of the application's `ObjectMapper` bean instead of the starter's own. Off by default, so a setting made for the REST API (a naming strategy, a date format, a Spring Boot upgrade) does not change what nodes exchange or what the journal stores. Pekko's own Jackson settings (`spring.actor.pekko.serialization.jackson.*`) apply either way. | ## Cluster Used with `provider: cluster`. See [Cluster Formation](../cluster/cluster-formation.md) and [Split Brain and Leases](../cluster/split-brain-and-leases.md). ### Joining | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.cluster.join` | `seed-nodes` | none | How this node finds the cluster: `seed-nodes` (the listed nodes) or `discovery` (peers found through `discovery.method`, with Pekko Cluster Bootstrap). | | `spring.actor.cluster.seed-nodes` | none | `pekko.cluster.seed-nodes` | Nodes to join at startup, as `pekko://@:`. Not with `join: discovery`. | | `spring.actor.cluster.join-self` | `false` | none | Joins this node to itself: a one-node cluster without seed nodes, also on port `0`. For local runs and tests. Not with `seed-nodes` or `join: discovery`. With Pekko Management on the classpath, Cluster Bootstrap is not started for this node. | | `spring.actor.cluster.roles` | none | `pekko.cluster.roles` | Roles of this node. Sharded actors and singletons can be limited to a role. | ### Discovery Used with `join: discovery`. | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.cluster.discovery.method` | none | `pekko.discovery.method` | Where peers are found: `jdbc` (needs `actor-jdbc`), `redis` (needs `actor-redis`), `custom` (your `PeerRegistry` bean), `kubernetes-api`, `dns` or `config`. Required with `join: discovery`. A `PeerRegistry` bean of your own replaces the `jdbc` and `redis` stores. | | `spring.actor.cluster.discovery.heartbeat-interval` | `5s` | none | How often a node renews its own entry (`jdbc`, `redis`, `custom`). Must be positive. | | `spring.actor.cluster.discovery.ttl` | `30s` | none | How long an entry counts as alive after its last renewal (`jdbc`, `redis`, `custom`). Must be positive. | | `spring.actor.cluster.discovery.service-name` | `spring.actor.name`; `-` with `spring.actor.generation.color` and `jdbc`, `redis` or `custom` | none | The name a node registers and looks up its peers under (Pekko's `contact-point-discovery.service-name`). | ### Downing (split brain resolver) | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.cluster.downing.strategy` | `keep-majority` | `pekko.cluster.downing-provider-class`, `pekko.cluster.split-brain-resolver.active-strategy` | Which side of a network split stays up: `keep-majority`, `lease-majority`, `static-quorum`, `keep-oldest`, `down-all` or `none`. `none` logs a warning. | | `spring.actor.cluster.downing.quorum-size` | none | `pekko.cluster.split-brain-resolver.static-quorum.quorum-size` | Nodes a side needs to stay up. Required with `static-quorum`; at least `1`. Set it above half the cluster's size. | ### Leases | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.cluster.lease.store` | none | none | Where leases live: `jdbc` (needs `actor-jdbc`), `redis` (needs `actor-redis`) or `custom` (your `LeaseStore` bean). Required by `downing.strategy: lease-majority`, `singleton.use-lease` and `sharding.use-lease`. | | `spring.actor.cluster.lease.ttl` | `120s` | `spring-actor.lease.heartbeat-timeout` | How long a lease stays held after its last renewal before another node may take it. | | `spring.actor.cluster.lease.renew-interval` | `12s` | `spring-actor.lease.heartbeat-interval` | How often the holder renews a lease. | | `spring.actor.cluster.lease.expiry-margin` | `10s` | `spring-actor.lease.expiry-margin` | The holder treats its lease as lost this long before the ttl ends, so it stops before another node can take the lease. Must be less than `ttl`. | | `spring.actor.cluster.singleton.role` | none | `pekko.cluster.singleton.role` | Cluster singletons run only on nodes with this role. Set the same value on every node. | | `spring.actor.cluster.singleton.use-lease` | `false` | `pekko.cluster.singleton.use-lease` | A cluster singleton runs only while it holds a lease, so two nodes never run it at once, even during a split. | | `spring.actor.cluster.sharding.use-lease` | `false` | `pekko.cluster.sharding.use-lease` | Each shard runs only while it holds a lease. | ### Pekko Management | Key | Default | Description | |---|---|---| | `spring.actor.pekko.management.enabled` | `true` | Whether to start the Pekko Management HTTP server and Cluster Bootstrap in cluster mode, when the Pekko Management libraries are on the classpath. The server's own settings (`spring.actor.pekko.management.http.port`, ...) are raw Pekko keys. | ## Database tables | Key | Default | Description | |---|---|---| | `spring.actor.jdbc.initialize-schema` | `embedded` | When to create the `actor-jdbc` tables (`actor_peer`, `actor_lease`): `embedded` (only in an embedded database), `always`, or `never` (you create them from the `schema-*.sql` files in `actor-jdbc`). | | `spring.actor.persistence.initialize-schema` | `embedded` | When to create the `actor-persistence` tables (`event_journal`, `event_tag`, `snapshot`) and the `actor-projection` offset tables: `embedded`, `always` or `never`. See [Event-Sourced Actors](../data/event-sourcing.md#tables) and [Projections](../data/projections.md). | ## Dispatchers and threads See [Dispatchers](../core/dispatchers.md). | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.dispatchers..executor` | none | `.*` | Declares a dispatcher that runs on the named Spring `Executor` bean (for example a `ThreadPoolTaskExecutor`). Actors pick it with `withDispatcherFromConfig("")`. | | `spring.actor.dispatchers..virtual` | `false` | `.executor` | Declares a dispatcher that runs on virtual threads, one per task. Set either `executor` or `virtual: true`, not both. | | `spring.actor.dispatchers..throughput` | Pekko's default (`5`) | `.throughput` | Messages an actor processes before its thread moves to the next actor. At least `1`. | | `spring.actor.virtual-threads.enabled` | `auto` | `pekko.actor.default-blocking-io-dispatcher.executor` | Runs the blocking dispatcher (`withBlockingDispatcher()`) on virtual threads: `auto`, `true` or `false`. `auto` follows `spring.threads.virtual.enabled`. The default dispatcher always stays on platform threads. | A dispatcher name is letters, digits, `-` and `_`, and must not be `pekko` or the name of a typed key (`name`, `cluster`, `dispatchers`, ...). ## Startup checks See [What not to do in an actor bean](../core/actors.md#what-not-to-do-in-an-actor-bean). | Key | Default | Description | |---|---|---| | `spring.actor.validation.actor-beans` | `warn` | What happens when an actor bean has a mutable instance field (neither `static`, `final` nor injected) or is a Spring AOP proxy: `warn` logs each problem, `fail` stops startup, `off` skips the checks. | ## Reliable delivery See [Reliable Delivery](../core/reliable-delivery.md). A receiver can override `idempotency-ttl` in code, and a sender its whole `RetryPolicy`. | Key | Default | Sets Pekko key | Description | |---|---|---|---| | `spring.actor.delivery.idempotency-ttl` | `10m` | `spring-actor.delivery.idempotency-ttl` | How long a receiver remembers the idempotency key of a message it handled; a message with a remembered key is acknowledged again without running the handler. Must be positive. | | `spring.actor.delivery.max-remembered-keys` | `10000` | `spring-actor.delivery.max-remembered-keys` | The most keys one receiver remembers; past it, the oldest are forgotten first. At least `1`. | | `spring.actor.delivery.retry.max-attempts` | `5` | none | Attempts in total, including the first. | | `spring.actor.delivery.retry.timeout` | `30s` | none | Time from the first attempt after which a sender gives up; no attempt starts after it. | | `spring.actor.delivery.retry.attempt-timeout` | `3s` | none | How long one attempt waits for the ack. | | `spring.actor.delivery.retry.initial-backoff` | `200ms` | none | The backoff before the second attempt; it doubles up to `max-backoff`, with full jitter. | | `spring.actor.delivery.retry.max-backoff` | `5s` | none | The longest backoff between attempts. | ## Blue-green generation See [The active generation](deployments.md#the-active-generation). Blue-green activation is on when `color` is set. | Key | Default | Description | |---|---|---| | `spring.actor.generation.color` | none | This deployment's color, for example `blue` or `green`. Setting it turns on blue-green activation, the store-backed `DeploymentGeneration` and the `generation` Actuator endpoint; each color runs with its own value. Without it, `DeploymentGeneration` is a no-op that is always active. | | `spring.actor.generation.store` | none | Where the active generation is kept: `jdbc` (the `actor_generation` table, needs `actor-jdbc`), `redis` (needs `actor-redis`) or `custom` (your `GenerationStore` bean). | | `spring.actor.generation.name` | `spring.actor.name` | Name of the record both colors share in the store. | | `spring.actor.generation.refresh` | `1s` | How long a read of the active generation is reused before the store is read again: the longest a node takes to see an activation made elsewhere. `0` reads the store every time. Must not be negative. | ## Shutdown See [Graceful shutdown](production.md#graceful-shutdown). | Key | Default | Description | |---|---|---| | `spring.actor.shutdown.timeout` | `20s` | How long closing the Spring context waits for the actor system's coordinated shutdown. Must be positive. | | `spring.actor.shutdown.exit-process` | `true` | When the actor system terminates by itself (for example after this node is downed), the context closes; with this set, the process then exits with status 1 so an orchestrator restarts it. | ## Metrics Needs `actor-metrics` and a Micrometer `MeterRegistry`. See [Monitoring](monitoring.md). | Key | Default | Description | |---|---|---| | `spring.actor.metrics.enabled` | `true` | Whether to register the actor meters, the actor `MetricsRegistry` bean and, in cluster mode, the `actor.cluster.*` and `actor.sharding.*` meters. | | `spring.actor.metrics.path-tag-limit` | `0` | How many actor paths get their own `actor.path` tag on the `actor.message.*` meters; the rest share `actor.path=other`. `0` adds no `actor.path` tag, so the series count never grows with the number of actors. | ## Actuator Need Spring Boot Actuator. See [Health checks](production.md#health-checks) and [The actors endpoint](monitoring.md#the-actors-endpoint). | Key | Default | Description | |---|---|---| | `management.health.actor.enabled` | `true` | Whether to add the `actorSystem` and (in cluster mode) `actorCluster` health components. | | `management.endpoint.actors.access` | `unrestricted` | Access to the `actors` endpoint (cluster mode): `unrestricted`, `read-only` or `none`. `none` turns it off. Spring Boot adds this key for every endpoint. | | `management.endpoint.actors.cache.time-to-live` | `0ms` | How long a response of the `actors` endpoint may be cached. Spring Boot adds this key for every endpoint. | `management.endpoint.actors.enabled` also appears in the metadata. Spring Boot generates it for every endpoint and marks it deprecated; use `access` instead. ## Spring Boot keys that matter These are Spring Boot's own keys. The starter reads or depends on them: | Key | Why | |---|---| | `spring.threads.virtual.enabled` | `spring.actor.virtual-threads.enabled: auto` follows it. | | `server.shutdown: graceful` and `spring.lifecycle.timeout-per-shutdown-phase` | The web server drains requests before the actor system stops. See [Shutdown order](production.md#shutdown-order). | | `management.endpoints.web.exposure.include` | The `actors` and `prometheus` endpoints are exposed over HTTP only when listed here. | | `management.endpoint.health.group.readiness.include` | Add `actorCluster` to gate traffic on cluster membership. | ## Example ```yaml spring: actor: name: orders provider: cluster remote: hostname: 10.0.0.7 port: 25520 cluster: seed-nodes: - pekko://orders@10.0.0.7:25520 - pekko://orders@10.0.0.8:25520 roles: api downing: strategy: keep-majority shutdown: timeout: 25s ``` ## Raw Pekko keys (`spring.actor.*`) Every other key under `spring.actor.*` is passed unchanged to the Pekko actor system configuration, with the `spring.actor` prefix removed. For example, `spring.actor.pekko.loglevel` becomes `pekko.loglevel`, and a dispatcher defined at `spring.actor.my-dispatcher` becomes `my-dispatcher`. Comma-separated string values are turned into lists, and a single value for a key that Pekko reads as a list is a one-item list: `spring.actor.pekko.cluster.seed-nodes=pekko://orders@10.0.0.7:25521` works like `seed-nodes[0]`. See the [Pekko reference configuration](https://pekko.apache.org/docs/pekko/current/general/configuration-reference.html) for the available keys. ```yaml spring: actor: pekko: loglevel: INFO coordinated-shutdown: phases: cluster-leave: timeout: 10s ``` !!! note "Raw keys win" When a raw key and a typed key set the same Pekko key to different values, the raw key wins and the starter logs a warning that names both, for example `spring.actor.pekko.name=raw overrides spring.actor.name=typed`. Prefer the typed key. ## Metrics agent environment variables (`ACTOR_METRICS_*`) !!! warning "Not Spring keys" These are environment variables, read by the optional metrics Java agent and by the metrics registry builder with `System.getenv` (falling back to a JVM system property of the same name). They are not Spring configuration keys: setting them in `application.yml` or `application.properties` has no effect, and they do not appear in the Spring configuration metadata. | Variable | Default | Description | |---|---|---| | `ACTOR_METRICS_ENABLED` | `true` | Read by the agent at JVM startup: `false` skips all instrumentation. Also read by the metrics registry builder to set the enabled flag of the metrics configuration. | | `ACTOR_METRICS_INSTRUMENT_` | `true` | Read by the agent: `false` skips instrumentation for one module. `` is the module id in upper case with `-` replaced by `_`: `ACTOR_LIFECYCLE`, `MESSAGE_PROCESSING`, `MAILBOX`, `SYSTEM`, `SCHEDULER`, `STASH`. | | `ACTOR_METRICS_TAG_` | none | Adds a global tag to every agent metric. The tag name is `` in lower case with `_` replaced by `.`; for example `ACTOR_METRICS_TAG_APPLICATION=my-app` adds the tag `application=my-app`. | | `ACTOR_METRICS_SAMPLING_RATE` | `1.0` | Sampling rate between `0.0` and `1.0`. | ```bash ACTOR_METRICS_TAG_APPLICATION=my-app \ ACTOR_METRICS_INSTRUMENT_MAILBOX=false \ java -javaagent:actor-metrics-{version}-agent.jar -jar app.jar ``` ## Related - [Running in Production](production.md): shutdown and health settings in context - [Monitoring](monitoring.md): what the metrics keys turn on - [Cluster Formation](../cluster/cluster-formation.md), [Split Brain and Leases](../cluster/split-brain-and-leases.md) - [Dispatchers](../core/dispatchers.md) --- # Testing The `actor-test` module has three tools for tests: - **`@ActorTest`**: a test slice that starts the actor system and your actor beans, and nothing else. - **`ActorCluster`**: several nodes of your application in one JVM, each on a port it binds itself, for cluster tests. - **Contract suites**: the tests every `PeerRegistry` and `LeaseStore` must pass, to run against your own store, plus in-memory fakes of both. !!! info "Incubating" `actor-test` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. Its types carry `@Incubating`. The compatibility promise covers the core and cluster API. Add it as a test dependency: === "Gradle" ```groovy testImplementation 'io.github.seonwkim:actor-test:1.1.0' ``` === "Maven" ```xml io.github.seonwkim actor-test 1.1.0 test ``` `actor-test` has no Pekko types in its API. It brings JUnit 5 and Spring Boot's test support, not the starter: your application already has that. ## Test actors with `@ActorTest` `@ActorTest` works like Spring Boot's `@DataJpaTest` or `@WebMvcTest`. It finds your `@SpringBootApplication`, turns its auto-configuration off and keeps only actor beans from the component scan. You get the `SpringActorSystem` and every `SpringActor` and `SpringShardedActor` bean, without a web server, a `DataSource` or your services. Only configuration properties, Jackson and Spring's task executor are auto-configured, because the actor system uses them when they are there. === "Java" ```java import io.github.seonwkim.actor.SpringActorSystem; import io.github.seonwkim.actor.test.ActorTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; @ActorTest class GreeterActorTest { @Autowired SpringActorSystem actorSystem; @Test void greets() throws Exception { String reply = actorSystem.actor(GreeterActor.class) .withId("greeter") .spawnAndWait() .ask(new GreeterActor.Greet("Ada")) .execute() .toCompletableFuture() .get(); assertThat(reply).isEqualTo("Hello, Ada!"); } } ``` === "Kotlin" ```kotlin import io.github.seonwkim.actor.SpringActorSystem import io.github.seonwkim.actor.kotlin.actor import io.github.seonwkim.actor.kotlin.awaitAsk import io.github.seonwkim.actor.kotlin.awaitSpawn import io.github.seonwkim.actor.test.ActorTest import org.junit.jupiter.api.Test import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.springframework.beans.factory.annotation.Autowired @ActorTest class GreeterActorTest { @Autowired lateinit var actorSystem: SpringActorSystem @Test fun greets() = runBlocking { val reply: String = actorSystem.actor() .withId("greeter") .awaitSpawn() .awaitAsk(GreeterActor.Greet("Ada")) assertThat(reply).isEqualTo("Hello, Ada!") } } ``` In Kotlin, `runBlocking` (from `kotlinx-coroutines-core`, which `actor-kotlin` brings) runs the `suspend` calls in the test. Name actors to start only those, and add properties: === "Java" ```java @ActorTest(actors = GreeterActor.class, properties = "spring.actor.name=greeter-test") ``` === "Kotlin" ```kotlin @ActorTest(actors = [GreeterActor::class], properties = ["spring.actor.name=greeter-test"]) ``` An actor that needs another bean gets it with `@Import(MyService.class)` or `@MockitoBean`. `includeFilters`, `excludeFilters` and `excludeAutoConfiguration` work as on Spring Boot's own slices. The actor system is the one your application's auto-configuration starts: the slice imports the same actor auto-configurations, so `spring.actor.*` properties from `application.yml` apply. ## Cluster tests with `ActorCluster` `ActorCluster` starts several Spring contexts of your application in one JVM. Each node binds port 0, so the operating system gives it a free port as it binds and no other test or process can take that port in between. Node 1 joins itself (`spring.actor.cluster.join-self`) and forms the cluster at once; the others join it at the address it bound. `start()` returns when every node sees every node up. With Pekko Management on the classpath, each node's management server binds port 0 too. With JUnit 5, register `ActorClusterExtension`. On an instance field it starts a cluster for each test; on a static field (in Kotlin, a `@JvmField` in a `companion object`), one for the whole class. === "Java" ```java class ShardedCounterClusterTest { @RegisterExtension final ActorClusterExtension cluster = new ActorClusterExtension( ActorCluster.builder(MyApplication.class) .nodes(3) .roles(1, "frontend") .properties("app.feature.enabled=true")); @Test void anEntityKeepsItsStateWhenANodeLeaves() { SpringActorSystem first = cluster.node(1).getBean(SpringActorSystem.class); // ... message a sharded entity from node 1 cluster.cluster().stop(2); cluster.cluster().awaitMembersUp(2); // ... the entity answers from another node } } ``` === "Kotlin" ```kotlin class ShardedCounterClusterTest { @JvmField @RegisterExtension val cluster = ActorClusterExtension( ActorCluster.builder(MyApplication::class.java) .nodes(3) .roles(1, "frontend") .properties("app.feature.enabled=true")) @Test fun anEntityKeepsItsStateWhenANodeLeaves() { val first = cluster.node(1).getBean(SpringActorSystem::class.java) // ... message a sharded entity from node 1 cluster.cluster().stop(2) cluster.cluster().awaitMembersUp(2) // ... the entity answers from another node } } ``` Without JUnit, use it directly; it is `AutoCloseable`: === "Java" ```java try (ActorCluster cluster = ActorCluster.builder(MyApplication.class).nodes(3).start()) { // ... } ``` === "Kotlin" ```kotlin ActorCluster.builder(MyApplication::class.java).nodes(3).start().use { cluster -> // ... } ``` | Builder method | What it sets | |---|---| | `nodes(int)` | Number of nodes, 3 by default | | `systemName(String)` | The actor system name of every node | | `properties(String...)` | `key=value` properties for every node | | `nodeProperties(int, String...)` | Properties for one node, numbered from 1 | | `roles(int, String...)` | Cluster roles of one node | | `timeout(Duration)` | How long to wait for members to be up, 30 seconds by default | | `classLoader(int, ClassLoader)` | The class loader one node, numbered from 1, loads your classes through. Use it to run two versions of a class side by side | The properties are passed as command-line arguments, so they override your `application.yml`. The cluster tracks membership through the starter's cluster events: `upMembers(node)` is the number of members a node sees up, and `awaitMembersUp(count)` waits until every running node sees that many. ### Two versions of a message in one cluster To check that a message change survives a rolling update, run one node on the next version of the message class. Compile the new version into its own folder (for example with `javax.tools.JavaCompiler` in the test), and give that node a class loader that loads the class from there and every other class from your application: === "Java" ```java ClassLoader v2 = new ClassLoader(getClass().getClassLoader()) { @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (!name.equals(SayHello.class.getName())) { return super.loadClass(name, resolve); } synchronized (getClassLoadingLock(name)) { Class loaded = findLoadedClass(name); if (loaded == null) { byte[] bytes = readClassFile(v2Classes, name); // your helper: the .class file's bytes loaded = defineClass(name, bytes, 0, bytes.length); } return loaded; } } }; try (ActorCluster cluster = ActorCluster.builder(MyApplication.class) .nodes(2) .classLoader(2, v2) .start()) { // Node 1 sends the old SayHello to an entity on node 2, and node 2 sends the new one // (created through v2.loadClass(...)) to an entity on node 1. } ``` === "Kotlin" ```kotlin val v2 = object : ClassLoader(javaClass.classLoader) { override fun loadClass(name: String, resolve: Boolean): Class<*> { if (name != SayHello::class.java.name) { return super.loadClass(name, resolve) } synchronized(getClassLoadingLock(name)) { return findLoadedClass(name) ?: readClassFile(v2Classes, name) // your helper: the .class file's bytes .let { bytes -> defineClass(name, bytes, 0, bytes.size) } } } } ActorCluster.builder(MyApplication::class.java) .nodes(2) .classLoader(2, v2) .start() .use { cluster -> // Node 1 sends the old SayHello to an entity on node 2, and node 2 sends the new one // (created through v2.loadClass(...)) to an entity on node 1. } ``` Put the entities on a given node with a role (`roles(1, "v1")` and `role()` on the sharded actor), so each message really crosses between the versions. The starter's own build runs this test (`MixedVersionMessageTest` in `actor-cluster`). ## Contract suites for your own store A `PeerRegistry` or `LeaseStore` of your own ([Cluster Formation](cluster/cluster-formation.md#your-own-store), [Split Brain and Leases](cluster/split-brain-and-leases.md#your-own-store)) must behave like the built-in ones: for example, of twenty nodes that try to take a lease at once, exactly one wins. `actor-test` publishes the tests the built-in JDBC and Redis stores pass. Extend the suite and return your store: === "Java" ```java class MyLeaseStoreContractTest extends LeaseStoreContract { private final MyLeaseStore store = new MyLeaseStore(testDatabase()); @Override protected LeaseStore store() { return store; } } ``` === "Kotlin" ```kotlin class MyLeaseStoreContractTest : LeaseStoreContract() { private val store = MyLeaseStore(testDatabase()) override fun store(): LeaseStore = store } ``` === "Java" ```java class MyPeerRegistryContractTest extends PeerRegistryContract { @Override protected PeerRegistry registry() { return new MyPeerRegistry(testDatabase()); } } ``` === "Kotlin" ```kotlin class MyPeerRegistryContractTest : PeerRegistryContract() { override fun registry(): PeerRegistry = MyPeerRegistry(testDatabase()) } ``` Each test uses its own lease or service name, so one store may serve every test. Some tests wait for a ttl of one to two seconds to pass, because stores may keep time in whole seconds. `InMemoryPeerRegistry` and `InMemoryLeaseStore` pass the same suites. Declare one as a bean to run cluster tests with `discovery.method: custom` or `lease.store: custom` without a database; nodes in one JVM can share one instance. ## Related - [Kotlin](kotlin.md): the `suspend` helpers used in the Kotlin tests - [Cluster Formation](cluster/cluster-formation.md) and [Split Brain and Leases](cluster/split-brain-and-leases.md): the stores the contract suites cover - [Sharded Actors](cluster/sharded-actors.md) --- # Kotlin The `actor-kotlin` module adds a thin Kotlin layer over the Java API: a `behavior { }` DSL for actor behaviors, `suspend` functions instead of `CompletionStage`, reified type parameters instead of `Class` arguments, and `kotlin.time.Duration` timeouts. Each function calls the Java API, so everything in the other guides applies unchanged. !!! info "Incubating" `actor-kotlin` is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. The compatibility promise covers the core and cluster API. ## Installation Add `actor-kotlin` next to the starter. It brings `kotlinx-coroutines-core`; Spring Boot manages its version. ```kotlin dependencies { implementation("io.github.seonwkim:actor-spring-boot-starter:1.1.0") implementation("io.github.seonwkim:actor-kotlin:1.1.0") } ``` The module is compiled with Kotlin 1.9.25, the version Spring Boot 3.5 manages, so applications on that version or later can use it. ### Null safety `actor-api` declares its nullability: values are non-null unless marked `@Nullable` (for example `AskCommand.getReplyTo()`). Kotlin turns those annotations into Kotlin types with the `-Xjsr305=strict` compiler flag, which projects generated by start.spring.io already set: ```kotlin kotlin { compilerOptions { freeCompilerArgs.addAll("-Xjsr305=strict") } } ``` Without the flag, Kotlin only warns, and the API's types are platform types (`String!`). ## Defining an actor `behavior(actorContext) { ... }` builds the behavior with `SpringActorBehavior.builder`. Commands are often a sealed interface: ```kotlin @Component class HelloActor : SpringActor { sealed interface Command class SayHello : AskCommand(), Command data class LogVisit(val name: String) : Command override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext) { onMessage { msg -> msg.reply("Hello from actor ${actorContext.actorId()}") same() } onMessage { msg -> log.info("{} visited", msg.name) // the behavior context is `this` same() } } } ``` Inside the block: | DSL | Java builder | |---|---| | `onMessage { msg -> next }` | `.onMessage(M.class, (ctx, msg) -> next)` | | `onSignal { signal -> next }` | `.onSignal(PostStop.class, (ctx, signal) -> next)` | | `withSupervisionStrategy(strategy)` | `.withSupervisionStrategy(strategy)` | | `withMdc { msg -> mapOf(...) }` | `.withMdc(msg -> Map.of(...))` | | `same()`, `stopped()`, `unhandled()` | `SpringActorBehavior.same()`, `.stopped()`, `.unhandled()` | A handler runs with the behavior context as `this`, so `self`, `log`, `pipeToSelf(...)`, `watch(...)` and the timers need no `ctx.` prefix. It returns the next behavior: `same()`, `stopped()`, `unhandled()`, or another `behavior { }` to switch behaviors. ### State To keep state in an object, pass a `state` factory ([`withState`](core/behaviors.md#state-with-withstate)). It runs when the actor starts and again on each restart, and the handlers then run with the state object as `this`: ```kotlin override fun create(actorContext: SpringActorContext): SpringActorBehavior = behavior(actorContext, state = { ctx -> Counter(ctx) }) { onMessage { msg -> onAdd(msg) } onMessage { msg -> onGet(msg) } } ``` `behavior` works too: Kotlin infers the state type from the factory. `actorBehavior(actorContext)` returns the Java builder itself, for code that prefers the chained `.onMessage(Type::class.java) { ctx, msg -> ... }.build()` style. ## Spawning and finding actors The reified helpers take the actor type as a type argument. Kotlin can't infer the command type from the actor type by itself, so pass `_` for it: ```kotlin // actorSystem.actor(HelloActor::class.java) val builder = actorSystem.actor() // Suspends until the actor runs val hello: SpringActorHandle = actorSystem.actor().withId("hello").withTimeout(5.seconds).awaitSpawn() val running = actorSystem.awaitGetOrSpawn("hello") // spawn when none runs val maybe = actorSystem.awaitGet("hello") // null when none runs val exists = actorSystem.awaitExists("hello") // Sharded actors (cluster mode) val counter = actorSystem.sharded().withId("counter-1").get() ``` | Kotlin | Java API it calls | |---|---| | `actor()` | `actor(A.class)` | | `sharded()` | `sharded(A.class)` | | `awaitGetOrSpawn(id)`, `awaitGet(id)`, `awaitExists(id)` | `getOrSpawn`, `find` (as a nullable), `exists` with `A.class` | | `builder.awaitSpawn()`, `builder.awaitGetOrSpawn()` | `spawn()`, `getOrSpawn()` on the spawn builder | | `behavior(actorContext) { }`, `behavior(actorContext, state = { ctx -> S(ctx) }) { }` | `SpringActorBehavior.builder(C.class, actorContext)`, then `withState`, the handlers and `build()` | | `actorBehavior(actorContext)` | `SpringActorBehavior.builder(C.class, actorContext)` | | `handle.child()`, `handle.child(id)` | `child(A.class)`, `child(A.class, id)` | | `awaitSpawn()`, `awaitGetOrSpawn()`, `awaitExists()` on a child builder; `awaitGet()`, `awaitExists()` on a child reference | `spawn()`, `getOrSpawn()`, `get()`, `exists()` | | `withTimeout(5.seconds)`, `withLimit(10, 1.minutes)`, `startSingleTimer(key, msg, 30.seconds)`, `startTimerAtFixedRate(key, msg, 10.seconds)` | the same methods with a `java.time.Duration` | | `unwrap()` on the actor system, a ref or a behavior context | `unwrap(X.class)` | ## Child actors `handle.child()` is the child builder and `handle.child(id)` the lookup reference of [Child actors](core/actors.md#child-actors). Outside the parent, the `await*` functions suspend until the operation completes. A child lookup returns `null` when the child doesn't run: ```kotlin // In a suspend function, with the parent's handle val worker = dispatcher.child() .withId("worker-1") .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes)) .withTimeout(5.seconds) .awaitGetOrSpawn() val found: SpringActorHandle? = dispatcher.child("worker-1").awaitGet() val running: Boolean = dispatcher.child("worker-1").awaitExists() ``` Inside the parent's own handlers, don't wait: pass `spawn()` or `getOrSpawn()` to `pipeToSelf`, as in [Spawning children from inside the parent](core/actors.md#spawning-children-from-inside-the-parent). ## Durations These methods also take a `kotlin.time.Duration`: `withTimeout` on the spawn, sharded, child and ask builders and on the child reference, `SupervisionStrategy.restart().withLimit`, and the timers on the behavior context: ```kotlin ctx.startSingleTimer("idle", IdleTimeout, 30.minutes) ctx.startTimerAtFixedRate("flush", Flush, 10.seconds) ``` ## Asking `awaitAsk` sends an `AskCommand` and suspends until the reply arrives. Without a timeout, the handle's default timeout (3 seconds) applies. ```kotlin val greeting: String = hello.awaitAsk(HelloActor.SayHello(), timeout = 2.seconds) ``` When no reply arrives in time, `awaitAsk` throws `java.util.concurrent.TimeoutException`. For a fallback value instead, use the ask builder and finish it with `await()`: ```kotlin val greeting = hello.ask(HelloActor.SayHello()) .withTimeout(2.seconds) .onTimeout { "no answer" } .await() ``` `awaitAsk` works the same on a sharded actor handle. Cancelling the coroutine stops the wait; the command has already been sent. ## In a WebFlux controller With `kotlinx-coroutines-reactor` and `kotlin-reflect` on the classpath, WebFlux runs `suspend` handler functions: ```kotlin @RestController class HelloController(private val actorSystem: SpringActorSystem) { @GetMapping("/hello") suspend fun hello(): String = actorSystem.awaitGetOrSpawn("hello-actor") .awaitAsk(HelloActor.SayHello(), timeout = 3.seconds) } ``` The full application is in [example/kotlin](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/kotlin): the [simple example](../examples/simple.md), written in Kotlin. The [Kotlin example](../examples/kotlin.md) page walks through it. ## Related - [Actors](core/actors.md) and [Messaging](core/messaging.md): the Java API these functions call - [Testing](testing.md): `@ActorTest` with `runBlocking` --- # AI Agents This guide shows how the starter's pieces fit together for AI agents: one supervised sharded actor per agent that keeps the conversation, `pipeToSelf` for model calls, a per-node rate limiter, a human approval step with ask and a timeout, and snapshots that survive a restart. All Java code on this page is included from the runnable example in [`example/agent`](https://github.com/seonWKim/actor-spring-boot-starter/tree/main/example/agent). The Kotlin tabs show the same code in Kotlin, written with the [`actor-kotlin`](kotlin.md) module; they are not part of the example. The example uses a fake model, so it needs no API key and no network: ```bash ./gradlew :example:agent:bootRun # runs one demo conversation and logs it ./gradlew :example:agent:test # the tests named at the end of this page ``` ## Why actors fit agents An agent is a long conversation with state, slow external calls, and side effects. Actors give you: - **One owner per conversation.** An agent's actor handles one message at a time, so its history needs no locks, even with thousands of agents on one node. - **Location transparency.** With sharding, the cluster keeps exactly one instance of each agent id and routes messages to it, wherever it lives. - **No blocked threads.** A model call can take seconds. The actor sends the call, keeps answering other messages, and handles the reply as a new message. - **Supervision.** If the agent's code throws, a supervisor restarts it from its last snapshot. ## The model behind an interface The agent only knows this interface. The example ships a scripted fake; a real provider is another bean that implements it. === "Java" ```java /** * The only thing an agent knows about the model. Swap the fake for a real provider by adding * another bean that implements this interface; the agent code does not change. */ public interface LlmClient { /** * Sends the conversation so far and returns the model's next step. Must not block the * caller: the agent pipes the result back to itself. */ CompletionStage complete(List conversation); } ``` === "Kotlin" ```kotlin /** * The only thing an agent knows about the model. Swap the fake for a real provider by adding * another bean that implements this interface; the agent code does not change. */ interface LlmClient { /** * Sends the conversation so far and returns the model's next step. Must not block the * caller: the agent pipes the result back to itself. */ fun complete(conversation: List): CompletionStage } ``` The fake model used by the example: === "Java" ```java /** * A scripted model, so the example runs without an API key or network. * *
    *
  • "weather in <city>" asks for the {@code weather} tool; *
  • "refund <order>" asks for the {@code refund} tool, which needs a human approval; *
  • "my name is <name>" is remembered, and "what is my name?" answers from the conversation; *
  • a tool result is turned into the final answer; *
  • anything else is echoed. *
*/ @Component public class FakeLlmClient implements LlmClient { private final AgentProperties properties; public FakeLlmClient(AgentProperties properties) { this.properties = properties; } @Override public CompletionStage complete(List conversation) { long latencyMillis = properties.getFakeLlmLatency().toMillis(); return CompletableFuture.supplyAsync( () -> reply(conversation), CompletableFuture.delayedExecutor(latencyMillis, TimeUnit.MILLISECONDS)); } static LlmReply reply(List conversation) { ChatMessage last = conversation.get(conversation.size() - 1); if (last.role() == ChatMessage.Role.TOOL_RESULT) { return LlmReply.answer("Tool " + last.toolName() + " says: " + last.content()); } String text = last.content().trim(); String lower = text.toLowerCase(Locale.ROOT); int weather = lower.indexOf("weather in "); if (weather >= 0) { String city = text.substring(weather + "weather in ".length()).replaceAll("[?.!]+$", ""); return LlmReply.callTool("weather", city); } if (lower.startsWith("refund ")) { return LlmReply.callTool("refund", text.substring("refund ".length())); } if (lower.startsWith("what is my name")) { for (int i = conversation.size() - 1; i >= 0; i--) { ChatMessage message = conversation.get(i); if (message.role() == ChatMessage.Role.USER && message.content().toLowerCase(Locale.ROOT).startsWith("my name is ")) { return LlmReply.answer("Your name is " + message.content().substring("my name is ".length())); } } return LlmReply.answer("You did not tell me your name."); } if (lower.startsWith("my name is ")) { return LlmReply.answer("Nice to meet you, " + text.substring("my name is ".length())); } return LlmReply.answer("You said: " + text); } } ``` === "Kotlin" ```kotlin /** * A scripted model, so the example runs without an API key or network. * * - "weather in " asks for the `weather` tool; * - "refund " asks for the `refund` tool, which needs a human approval; * - "my name is " is remembered, and "what is my name?" answers from the conversation; * - a tool result is turned into the final answer; * - anything else is echoed. */ @Component class FakeLlmClient(private val properties: AgentProperties) : LlmClient { override fun complete(conversation: List): CompletionStage = CompletableFuture.supplyAsync( { reply(conversation) }, CompletableFuture.delayedExecutor(properties.fakeLlmLatency.toMillis(), TimeUnit.MILLISECONDS), ) companion object { fun reply(conversation: List): LlmReply { val last = conversation.last() if (last.role == ChatMessage.Role.TOOL_RESULT) { return LlmReply.answer("Tool ${last.toolName} says: ${last.content}") } val text = last.content.trim() val lower = text.lowercase() val weather = lower.indexOf("weather in ") return when { weather >= 0 -> { val city = text.substring(weather + "weather in ".length).replace(Regex("[?.!]+$"), "") LlmReply.callTool("weather", city) } lower.startsWith("refund ") -> LlmReply.callTool("refund", text.substring("refund ".length)) lower.startsWith("what is my name") -> { val name = conversation.lastOrNull { it.role == ChatMessage.Role.USER && it.content.lowercase().startsWith("my name is ") } if (name != null) LlmReply.answer("Your name is " + name.content.substring("my name is ".length)) else LlmReply.answer("You did not tell me your name.") } lower.startsWith("my name is ") -> LlmReply.answer("Nice to meet you, " + text.substring("my name is ".length)) else -> LlmReply.answer("You said: $text") } } } } ``` Tools are beans too. A tool that changes the world asks for a human approval first: === "Java" ```java /** A function the model may ask the agent to run. */ public interface Tool { String name(); /** Tools that change the world wait for a human to approve the call. */ default boolean requiresApproval() { return false; } String invoke(String argument); } ``` === "Kotlin" ```kotlin /** A function the model may ask the agent to run. */ interface Tool { fun name(): String /** Tools that change the world wait for a human to approve the call. */ fun requiresApproval(): Boolean = false fun invoke(argument: String): String } ``` ## One sharded actor per agent Each agent id is a sharded entity. Its behavior is the agent's logic, `AgentBrain`, under a restart supervisor. === "Java" ```java /** * One sharded entity per agent id: the cluster keeps exactly one instance of each agent, on * some node, and routes every message for that id to it. * *

The agent's logic is {@link AgentBrain}, run under a restart supervisor. If it crashes, the * supervisor restarts it and it reloads its conversation from the snapshot store. */ @Component public class AgentActor implements SpringShardedActor { public static final ShardedEntityType TYPE_KEY = ShardedEntityType.of(Command.class, "Agent"); /** Commands may cross nodes, so they are JSON serializable. */ public interface Command extends JsonSerializable {} /** A user message. The reply is the agent's final answer for this turn. */ public static final class Chat extends AskCommand implements Command { public final String text; @JsonCreator public Chat(@JsonProperty("text") String text) { this.text = text; } } /** Reads the agent's state. Answered at once, even while an LLM call is pending. */ public static final class GetConversation extends AskCommand implements Command {} /** Makes the agent throw, to show supervision. */ public static final class SimulateCrash implements Command { @JsonCreator public SimulateCrash() {} } private final AgentBrain.Dependencies dependencies; public AgentActor( AgentRuntime runtime, LlmClient llm, ToolRegistry tools, AgentSnapshotStore snapshots, AgentProperties properties) { this.dependencies = new AgentBrain.Dependencies( llm, tools, snapshots, runtime.rateLimiter(), runtime.approvals(), properties.getApprovalTimeout(), properties.getMaxToolSteps()); } @Override public ShardedEntityType entityType() { return TYPE_KEY; } @Override public SpringActorBehavior create(SpringShardedActorContext ctx) { return AgentBrain.behavior(SpringActorBehavior.builder(Command.class, ctx), ctx.getEntityId(), dependencies); } } ``` === "Kotlin" ```kotlin /** * One sharded entity per agent id: the cluster keeps exactly one instance of each agent, on * some node, and routes every message for that id to it. * * The agent's logic is [AgentBrain], run under a restart supervisor. If it crashes, the * supervisor restarts it and it reloads its conversation from the snapshot store. */ @Component class AgentActor( runtime: AgentRuntime, llm: LlmClient, tools: ToolRegistry, snapshots: AgentSnapshotStore, properties: AgentProperties, ) : SpringShardedActor { companion object { val TYPE_KEY: ShardedEntityType = ShardedEntityType.of(Command::class.java, "Agent") } /** Commands may cross nodes, so they are JSON serializable. */ interface Command : JsonSerializable /** A user message. The reply is the agent's final answer for this turn. */ class Chat @JsonCreator constructor(@JsonProperty("text") val text: String) : AskCommand(), Command /** Reads the agent's state. Answered at once, even while an LLM call is pending. */ class GetConversation : AskCommand(), Command /** Makes the agent throw, to show supervision. */ class SimulateCrash @JsonCreator constructor() : Command private val dependencies = AgentBrain.Dependencies( llm, tools, snapshots, runtime.rateLimiter, runtime.approvals, properties.approvalTimeout, properties.maxToolSteps, ) override fun entityType(): ShardedEntityType = TYPE_KEY override fun create(ctx: SpringShardedActorContext): SpringActorBehavior = AgentBrain.behavior(actorBehavior(ctx), ctx.entityId, dependencies) } ``` Callers address agents by id and never need to know which node hosts them: === "Java" ```java /** Talks to agents by id. The agent may live on any node of the cluster. */ @Service public class AgentService { private final SpringActorSystem actorSystem; public AgentService(SpringActorSystem actorSystem) { this.actorSystem = actorSystem; } public CompletionStage chat(String agentId, String text, Duration timeout) { return agent(agentId) .ask(new AgentActor.Chat(text)) .withTimeout(timeout) .execute(); } public CompletionStage conversation(String agentId, Duration timeout) { return agent(agentId) .ask(new AgentActor.GetConversation()) .withTimeout(timeout) .execute(); } public void simulateCrash(String agentId) { agent(agentId).tell(new AgentActor.SimulateCrash()); } private SpringShardedActorHandle agent(String agentId) { return actorSystem.sharded(AgentActor.class).withId(agentId).get(); } } ``` === "Kotlin" ```kotlin /** Talks to agents by id. The agent may live on any node of the cluster. */ @Service class AgentService(private val actorSystem: SpringActorSystem) { suspend fun chat(agentId: String, text: String, timeout: Duration): AgentAnswer = agent(agentId).ask(AgentActor.Chat(text)).withTimeout(timeout).await() suspend fun conversation(agentId: String, timeout: Duration): ConversationView = agent(agentId).ask(AgentActor.GetConversation()).withTimeout(timeout).await() fun simulateCrash(agentId: String) { agent(agentId).tell(AgentActor.SimulateCrash()) } private fun agent(agentId: String): SpringShardedActorHandle = actorSystem.sharded().withId(agentId).get() } ``` !!! info "Single node by default" The example sets `spring.actor.cluster.join-self: true`, so one node forms its own cluster. For more nodes, remove it and list `spring.actor.cluster.seed-nodes` as in the [Sharded Actors](cluster/sharded-actors.md) guide. ## The agent loop without blocking A turn is: user message, rate-limit permit, model call, then either a final answer or a tool call followed by another model call. The model call returns a `CompletionStage`; `pipeToSelf` turns its result into a message, so the actor never waits on it. === "Java" ```java private void requestPermit() { status = Status.PERMIT; deps.rateLimiter().tell(RateLimiterActor.Acquire.replyingTo(permits)); } private SpringActorBehavior onPermit(PermitGranted granted) { if (status != Status.PERMIT) { return SpringActorBehavior.same(); } status = Status.LLM; ctx.getLog().debug("Agent {} calls the LLM", agentId); // The future completes on another thread; pipeToSelf turns it into a message, so // the actor never waits and never touches its state from that thread. ctx.pipeToSelf(deps.llm().complete(List.copyOf(conversation)), LlmResponded::new); return SpringActorBehavior.same(); } private SpringActorBehavior onLlmResponded(LlmResponded responded) { if (status != Status.LLM) { return SpringActorBehavior.same(); // a reply for an earlier incarnation } if (responded.error() != null) { finishTurn("Sorry, the model call failed: " + responded.error().getMessage()); return SpringActorBehavior.same(); } LlmReply reply = responded.reply(); if (!reply.isToolCall()) { finishTurn(reply.text()); return SpringActorBehavior.same(); } if (++toolSteps > deps.maxToolSteps()) { finishTurn("Stopped after " + deps.maxToolSteps() + " tool calls."); return SpringActorBehavior.same(); } append(ChatMessage.toolCall(reply.toolName(), reply.toolArgument())); Optional tool = deps.tools().find(reply.toolName()); if (tool.isEmpty()) { toolResult(reply, "unknown tool"); } else if (tool.get().requiresApproval()) { askForApproval(reply); } else { runTool(tool.get(), reply); } return SpringActorBehavior.same(); } ``` === "Kotlin" ```kotlin private fun requestPermit() { status = Status.PERMIT deps.rateLimiter.tell(RateLimiterActor.Acquire.replyingTo(permits)) } private fun onPermit(): SpringActorBehavior { if (status != Status.PERMIT) { return SpringActorBehavior.same() } status = Status.LLM ctx.log.debug("Agent {} calls the LLM", agentId) // The future completes on another thread; pipeToSelf turns it into a message, so // the actor never waits and never touches its state from that thread. ctx.pipeToSelf(deps.llm.complete(conversation.toList())) { reply, error -> LlmResponded(reply, error) } return SpringActorBehavior.same() } private fun onLlmResponded(responded: LlmResponded): SpringActorBehavior { if (status != Status.LLM) { return SpringActorBehavior.same() // a reply for an earlier incarnation } val reply = responded.reply if (responded.error != null || reply == null) { finishTurn("Sorry, the model call failed: ${responded.error?.message}") return SpringActorBehavior.same() } val toolName = reply.toolName val toolArgument = reply.toolArgument if (toolName == null || toolArgument == null) { finishTurn(reply.text.orEmpty()) return SpringActorBehavior.same() } if (++toolSteps > deps.maxToolSteps) { finishTurn("Stopped after ${deps.maxToolSteps} tool calls.") return SpringActorBehavior.same() } append(ChatMessage.toolCall(toolName, toolArgument)) val tool = deps.tools.find(toolName).orElse(null) when { tool == null -> toolResult(reply, "unknown tool") tool.requiresApproval() -> askForApproval(reply) else -> runTool(tool, reply) } return SpringActorBehavior.same() } ``` While a call is pending the agent still answers `GetConversation` at once, and a new `Chat` waits in a queue until the current turn ends. ## A rate limiter per node Model providers limit calls per second. Each node spawns one rate limiter actor and every agent on that node asks it for a permit before each call. It keeps a sliding one-second window, so no one-second span ever holds more than `agent.calls-per-second` calls. === "Java" ```java /** * One per node: hands out permits for LLM calls, at most {@code agent.calls-per-second} in any * one-second window. Requests over the limit wait in a queue; a timer wakes the actor when the * oldest permit leaves the window. * *

The starter has no rate limiter, so this is a plain actor with a timer from its behavior context. */ @Component public class RateLimiterActor implements SpringActor { public interface Command {} /** Ask for one permit. The reply comes when the call may start. */ public static final class Acquire extends AskCommand implements Command { @Nullable private final SpringActorRef adapter; public Acquire() { this(null); } private Acquire(@Nullable SpringActorRef adapter) { this.adapter = adapter; } /** For actors that want the permit as a message instead of a future. */ public static Acquire replyingTo(SpringActorRef replyTo) { return new Acquire(replyTo); } void grant(Permit permit) { if (adapter != null) { adapter.tell(permit); } else { reply(permit); } } } /** @param grantedAtNanos {@link System#nanoTime()} when the permit was granted */ public record Permit(long grantedAtNanos) {} private enum WakeUp implements Command { INSTANCE } private static final Duration WINDOW = Duration.ofSeconds(1); private final int callsPerSecond; public RateLimiterActor(AgentProperties properties) { this.callsPerSecond = properties.getCallsPerSecond(); } @Override public SpringActorBehavior create(SpringActorContext actorContext) { return SpringActorBehavior.builder(Command.class, actorContext) .withState(ctx -> new SlidingWindow(ctx, callsPerSecond, WINDOW.toNanos())) .onMessage(Acquire.class, SlidingWindow::onAcquire) .onMessage(WakeUp.class, (window, wakeUp) -> window.drain()) .build(); } private static final class SlidingWindow { private final SpringBehaviorContext ctx; private final int limit; private final long windowNanos; private final Deque granted = new ArrayDeque<>(); private final Deque waiting = new ArrayDeque<>(); SlidingWindow(SpringBehaviorContext ctx, int limit, long windowNanos) { this.ctx = ctx; this.limit = limit; this.windowNanos = windowNanos; } SpringActorBehavior onAcquire(Acquire acquire) { waiting.addLast(acquire); return drain(); } SpringActorBehavior drain() { long now = System.nanoTime(); while (!granted.isEmpty() && now - granted.peekFirst() >= windowNanos) { granted.removeFirst(); } while (!waiting.isEmpty() && granted.size() < limit) { granted.addLast(now); waiting.removeFirst().grant(new Permit(now)); } if (!waiting.isEmpty()) { long untilFree = windowNanos - (now - granted.peekFirst()); ctx.startSingleTimer(WakeUp.INSTANCE, WakeUp.INSTANCE, Duration.ofNanos(untilFree)); } return SpringActorBehavior.same(); } } } ``` === "Kotlin" ```kotlin /** * One per node: hands out permits for LLM calls, at most `agent.calls-per-second` in any * one-second window. Requests over the limit wait in a queue; a timer wakes the actor when the * oldest permit leaves the window. * * The starter has no rate limiter, so this is a plain actor with a timer from its behavior context. */ @Component class RateLimiterActor(properties: AgentProperties) : SpringActor { interface Command /** Ask for one permit. The reply comes when the call may start. */ class Acquire private constructor(private val adapter: SpringActorRef?) : AskCommand(), Command { constructor() : this(null) internal fun grant(permit: Permit) { if (adapter != null) adapter.tell(permit) else reply(permit) } companion object { /** For actors that want the permit as a message instead of a future. */ fun replyingTo(replyTo: SpringActorRef) = Acquire(replyTo) } } /** @param grantedAtNanos [System.nanoTime] when the permit was granted */ data class Permit(val grantedAtNanos: Long) private data object WakeUp : Command private val callsPerSecond = properties.callsPerSecond override fun create(actorContext: SpringActorContext): SpringActorBehavior = actorBehavior(actorContext) .withState { ctx -> SlidingWindow(ctx, callsPerSecond, 1.seconds.inWholeNanoseconds) } .onMessage(Acquire::class.java) { window, acquire -> window.onAcquire(acquire) } .onMessage(WakeUp::class.java) { window, _ -> window.drain() } .build() private class SlidingWindow( private val ctx: SpringBehaviorContext, private val limit: Int, private val windowNanos: Long, ) { private val granted = ArrayDeque() private val waiting = ArrayDeque() fun onAcquire(acquire: Acquire): SpringActorBehavior { waiting.addLast(acquire) return drain() } fun drain(): SpringActorBehavior { val now = System.nanoTime() while (granted.isNotEmpty() && now - granted.first() >= windowNanos) { granted.removeFirst() } while (waiting.isNotEmpty() && granted.size < limit) { granted.addLast(now) waiting.removeFirst().grant(Permit(now)) } if (waiting.isNotEmpty()) { val untilFree = windowNanos - (now - granted.first()) ctx.startSingleTimer(WakeUp, WakeUp, Duration.ofNanos(untilFree)) } return SpringActorBehavior.same() } } } ``` The node-local actors are spawned once, when Spring starts: === "Java" ```java /** * Node-local actors that every agent on this node shares: the LLM rate limiter and the approval * gateway. Each node spawns its own, so the rate limit is per node. */ @Component public class AgentRuntime { private final SpringActorHandle rateLimiter; private final SpringActorHandle approvals; // The actor beans are parameters so Spring registers them before they are spawned here. public AgentRuntime(SpringActorSystem actorSystem, RateLimiterActor rateLimiterActor, ApprovalActor approvalActor) { this.rateLimiter = actorSystem .actor(RateLimiterActor.class) .withId("llm-rate-limiter") .spawnAndWait(); this.approvals = actorSystem.actor(ApprovalActor.class).withId("approvals").spawnAndWait(); } ``` === "Kotlin" ```kotlin /** * Node-local actors that every agent on this node shares: the LLM rate limiter and the approval * gateway. Each node spawns its own, so the rate limit is per node. */ @Component class AgentRuntime( actorSystem: SpringActorSystem, // The actor beans are parameters so Spring registers them before they are spawned here. rateLimiterActor: RateLimiterActor, approvalActor: ApprovalActor, ) { val rateLimiter: SpringActorHandle = actorSystem.actor().withId("llm-rate-limiter").spawnAndWait() val approvals: SpringActorHandle = actorSystem.actor().withId("approvals").spawnAndWait() } ``` !!! note "Per node, not per cluster" With three nodes the cluster can make three times `agent.calls-per-second` calls. For a cluster-wide limit, run the limiter as a [cluster singleton](cluster/singletons.md) (`asClusterSingleton()`) instead. ## A human approval step When the model asks for a tool that needs approval, the agent asks the node's approval gateway with a timeout. The gateway holds the request until a human answers; if nobody answers in time, the ask fails and the agent tells the model the tool was not run. === "Java" ```java private void askForApproval(LlmReply call) { status = Status.APPROVAL; PendingApproval request = new PendingApproval(agentId + "-" + UUID.randomUUID(), agentId, call.toolName(), call.toolArgument()); Duration timeout = deps.approvalTimeout(); ctx.pipeToSelf( deps.approvals() .ask(new ApprovalActor.RequestApproval(request, timeout)) .withTimeout(timeout) .execute(), (ApprovalDecision decision, Throwable error) -> { if (error != null) { return new ApprovalResolved(call, false, "no human answer within " + timeout); } return new ApprovalResolved( call, decision.approved(), decision.approved() ? "approved" : "rejected by a human"); }); } private SpringActorBehavior onApprovalResolved(ApprovalResolved resolved) { if (status != Status.APPROVAL) { return SpringActorBehavior.same(); } LlmReply call = resolved.call(); Optional tool = deps.tools().find(call.toolName()); if (resolved.approved() && tool.isPresent()) { runTool(tool.get(), call); } else { toolResult(call, "not run: " + resolved.reason()); } return SpringActorBehavior.same(); } ``` === "Kotlin" ```kotlin private fun askForApproval(call: LlmReply) { status = Status.APPROVAL val request = PendingApproval("$agentId-${UUID.randomUUID()}", agentId, call.toolName!!, call.toolArgument!!) val timeout = deps.approvalTimeout ctx.pipeToSelf( deps.approvals .ask(ApprovalActor.RequestApproval(request, timeout)) .withTimeout(timeout) .execute(), ) { decision, error -> if (error != null || decision == null) { ApprovalResolved(call, false, "no human answer within $timeout") } else { ApprovalResolved(call, decision.approved, if (decision.approved) "approved" else "rejected by a human") } } } private fun onApprovalResolved(resolved: ApprovalResolved): SpringActorBehavior { if (status != Status.APPROVAL) { return SpringActorBehavior.same() } val call = resolved.call val tool = deps.tools.find(call.toolName!!).orElse(null) if (resolved.approved && tool != null) { runTool(tool, call) } else { toolResult(call, "not run: ${resolved.reason}") } return SpringActorBehavior.same() } ``` The human side, for a controller, a chat bot or a test: === "Java" ```java /** The human side of the approval step, for a controller, a Slack bot or a test. */ @Service public class ApprovalService { private static final Duration TIMEOUT = Duration.ofSeconds(3); private final AgentRuntime runtime; public ApprovalService(AgentRuntime runtime) { this.runtime = runtime; } public CompletionStage> pending() { return runtime.approvals() .ask(new ApprovalActor.ListPending()) .withTimeout(TIMEOUT) .execute(); } /** Completes with false if the request is unknown or its timeout has passed. */ public CompletionStage decide(String requestId, boolean approved) { return runtime.approvals() .ask(new ApprovalActor.Decide(requestId, approved)) .withTimeout(TIMEOUT) .execute(); } } ``` === "Kotlin" ```kotlin /** The human side of the approval step, for a controller, a Slack bot or a test. */ @Service class ApprovalService(private val runtime: AgentRuntime) { suspend fun pending(): List = runtime.approvals.ask(ApprovalActor.ListPending()).withTimeout(TIMEOUT).await() /** Returns false if the request is unknown or its timeout has passed. */ suspend fun decide(requestId: String, approved: Boolean): Boolean = runtime.approvals.ask(ApprovalActor.Decide(requestId, approved)).withTimeout(TIMEOUT).await() private companion object { val TIMEOUT: Duration = Duration.ofSeconds(3) } } ``` ## Supervision and restarts The agent's logic runs under a restart supervisor (`withSupervisionStrategy`). A restart creates the state again with `withState`, and the state loads the last snapshot: === "Java" ```java /** * Restart on failure, at most 10 times a minute. A restart creates the state again, so the * brain reloads its conversation from the last snapshot. After the limit the entity stops, * and sharding starts a fresh one on the next message. */ public static SpringActorBehavior behavior( SpringActorBehavior.Builder> builder, String agentId, Dependencies dependencies) { return builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, Duration.ofMinutes(1))) .withState(ctx -> new AgentBrain(ctx, agentId, dependencies)) .onMessage(AgentActor.Chat.class, AgentBrain::onChat) .onMessage(AgentActor.GetConversation.class, AgentBrain::onGetConversation) .onMessage(AgentActor.SimulateCrash.class, AgentBrain::onSimulateCrash) .onMessage(PermitGranted.class, AgentBrain::onPermit) .onMessage(LlmResponded.class, AgentBrain::onLlmResponded) .onMessage(ApprovalResolved.class, AgentBrain::onApprovalResolved) .build(); } private AgentBrain(SpringBehaviorContext ctx, String agentId, Dependencies dependencies) { this.ctx = ctx; this.agentId = agentId; this.deps = dependencies; this.permits = ctx.messageAdapter(RateLimiterActor.Permit.class, PermitGranted::new); dependencies.snapshots().load(agentId).ifPresent(snapshot -> conversation.addAll(snapshot.conversation())); } ``` === "Kotlin" ```kotlin companion object { /** * Restart on failure, at most 10 times a minute. A restart creates the state again, so the * brain reloads its conversation from the last snapshot. After the limit the entity stops, * and sharding starts a fresh one on the next message. */ fun behavior( builder: SpringActorBehavior.Builder>, agentId: String, dependencies: Dependencies, ): SpringActorBehavior = builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes.toJavaDuration())) .withState { ctx -> AgentBrain(ctx, agentId, dependencies) } .onMessage(AgentActor.Chat::class.java) { brain, msg -> brain.onChat(msg) } .onMessage(AgentActor.GetConversation::class.java) { brain, msg -> brain.onGetConversation(msg) } .onMessage(AgentActor.SimulateCrash::class.java) { brain, _ -> brain.onSimulateCrash() } .onMessage(PermitGranted::class.java) { brain, _ -> brain.onPermit() } .onMessage(LlmResponded::class.java) { brain, msg -> brain.onLlmResponded(msg) } .onMessage(ApprovalResolved::class.java) { brain, msg -> brain.onApprovalResolved(msg) } .build() } private val permits: SpringActorRef = ctx.messageAdapter(RateLimiterActor.Permit::class.java) { PermitGranted(it) } private val conversation = mutableListOf() init { deps.snapshots.load(agentId).ifPresent { conversation.addAll(it.conversation) } } ``` Every change to the conversation is saved before the agent moves on, so a new actor system finds the agent where it left off: === "Java" ```java /** Every change to the conversation is written before the agent moves on. */ private void append(ChatMessage message) { conversation.add(message); deps.snapshots().save(new AgentSnapshot(agentId, List.copyOf(conversation))); } ``` === "Kotlin" ```kotlin /** Every change to the conversation is written before the agent moves on. */ private fun append(message: ChatMessage) { conversation.add(message) deps.snapshots.save(AgentSnapshot(agentId, conversation.toList())) } ``` The store is an interface. The example writes one JSON file per agent; for a database, implement it with a JPA entity and repository like `ActorSnapshot` and `ActorSnapshotRepository` in the [persistence example](../examples/persistence.md) (see also [State in a Database](data/state-in-a-database.md)). === "Java" ```java /** * Saves and loads agent snapshots. The example writes JSON files; a JPA implementation with an * {@code ActorSnapshot} entity and repository, as in example/persistence, plugs in the same way. */ public interface AgentSnapshotStore { Optional load(String agentId); void save(AgentSnapshot snapshot); } ``` === "Kotlin" ```kotlin /** * Saves and loads agent snapshots. The example writes JSON files; a JPA implementation with an * `ActorSnapshot` entity and repository, as in example/persistence, plugs in the same way. */ interface AgentSnapshotStore { fun load(agentId: String): Optional fun save(snapshot: AgentSnapshot) } ``` ## Configuration | Property | Default | What | |---|---|---| | `agent.calls-per-second` | `20` | Model calls one node may start per second | | `agent.approval-timeout` | `30s` | How long an agent waits for a human | | `agent.max-tool-steps` | `5` | Tool calls per turn before the agent stops | | `agent.snapshot-dir` | `${java.io.tmpdir}/agent-snapshots` | Where snapshots are written | | `agent.fake-llm-latency` | `0` (`200ms` in application.yml) | Delay of each fake model reply | | `agent.demo` | `true` | Run one demo conversation on start-up | ## What the tests show | Test | Shows | |---|---| | `AgentConversationTest` | user message, model reply, tool call, tool result, final answer | | `ConcurrentAgentsTest` | 100 agents at once, each with its own id and its own history | | `RateLimiterTest` | no one-second window holds more permits than the limit | | `SlowLlmTest` | the agent answers other messages while a model call is pending | | `SupervisionTest` | a crashed agent restarts and reloads its conversation | | `ActorSystemRestartTest` | the conversation survives a restart of the whole actor system | | `HumanApprovalTest` | approve, reject, and a timeout when nobody answers | ## What the starter does not provide yet The example builds these itself: - **Rate limiting.** There is no rate limiter in the starter; the example's is an actor.