# 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