Reaktor Actor Model
An actor is a graph node that owns state which many things change at once. ActorNode lives in its own module, reaktor-actor in the Origin plane, under the package dev.shibasis.reaktor.actor. ActorKey is its identity, ActorRef is the handle callers send messages through, and each actor owns an exclusive ObjectStore. The graph runs and supervises it like any other node. BestBuds chat runs on it in production, and the Hangar workbench and the device security node in reaktor-security use it too.
PersistentActorNode is the durable variant. It declares its states and transitions up front, and its store decides the order of transitions, so it works across Worker instances. BestBuds Workers run Circle formation, Circle lifecycles, document verification, account purges and database backups through it.
Actors that span machines, and running an actor as a Cloudflare Durable Object, are designs. Nothing in reaktor-cloudflare maps an ActorKey onto a Durable Object yet. Lessons from Akka and Erlang/OTP maps the ideas of those two ecosystems onto Reaktor actors: what exists, what to use where Reaktor has no equivalent, and what is missing.
Overview#
receive() handles them one at a time, so it is the only code that changes the actor's state.An actor is a node that owns state which many things change at once. In BestBuds chat, the screen, the chat socket, uploads, retries and timers all change the same outgoing messages. The actor does not guard that state with locks. Every change arrives as a message in its mailbox, and the actor handles the messages one at a time, in the order they arrived. Code outside the actor can send messages, and it cannot reach the state in any other way.
The mailbox holds up to 64 messages by default. When it is full, send() waits for room, so a burst of events slows the senders down and no message is dropped. A message that fails does not stop the actor. The failure goes to the graph's supervisor strategy, which resumes the actor by default.
Try it#
The box below drives the read-receipt actor from BestBuds chat, which Writing an actor shows in full. Each Seen(chat) adds the chat to a pending set and, if the chat was not pending yet, schedules a Flush(chat) after NudgeWindow. Each Flush(chat) removes the chat and sends one receipt with markRead. Handling is how long receive() takes for one message.
Each line at(seconds) { send(...) } is a message the screen sends at that time. The timeline shows when each message was sent, when receive() handled it, the timers it set and the receipts it sent.
- With One mailbox, the second
Seen("general")waits until the first one is handled. It then finds the chat already pending and does nothing, so "general" gets one receipt. - Choose No mailbox to handle each message as soon as it arrives, as plain concurrent code would. The first two
Seen("general")messages overlap, both find the chat missing from the pending set, and the chat is marked read twice. - Set
Handlingto0.05.seconds, or move the second message toat(0.5), and the race goes away even without the mailbox. Races like this one depend on timing, so they can pass on a fast test machine and still happen on a slow phone.
val NudgeWindow = 2.seconds
val Handling = 0.3.seconds
at(0.0) { send(Seen("general")) }
at(0.1) { send(Seen("general")) }
at(0.2) { send(Seen("design")) }
at(0.6) { send(Seen("general")) }
at(3.2) { send(Seen("general")) }
Principles#
The actor model follows the same standard as the route-binding improvement from dispatch(Push(edge, payload)) to edge.push(payload): maximum power behind a small, expressive API. An actor is a node with a mailbox, lifecycle hooks, state helpers and a provider port registered from its key. There is no second runtime to learn.
state has one owner
events go to the owner
the owner serializes mutation
the owner emits state
views render state
services transport data
ports expose capabilities
What actors are for#
- Mutable state with concurrent event sources.
- WebSocket sessions, active rooms, retries, timers, and ordered side effects.
- Backend entities where one logical identity owns state.
- Workflow and session coordinators that need supervision.
What actors are not for#
- Pure repositories.
- Stateless service clients.
- Screen-only Compose state.
- Adding another DI, graph, or service framework.
Core model#
The public set is small. Everything else is an adapter, a helper or a pattern built from these pieces.
| Concept | Role | Design constraint |
|---|---|---|
ActorKey<M> | Logical identity and message type. | The key is the durable identity. Activation is just a node instance. |
ActorRef<M> | The handle with send, trySend and ask. | No public mutable actor state bypasses the mailbox. |
Reply<R> | The bridge an ask waits on. | A typed reply travels inside the message. There is no global callback registry. |
ActorNode<M> | A node with a mailbox, lifecycle, store, timers and receive. | The subclass owns the behavior. Callers talk through messages, or through methods that enqueue messages. |
MailboxPolicy | Capacity and overflow. | Bounded and suspending by default, so overload is visible. |
ActorDirective, ActorSupervisorStrategy | What happens after a failed message. | Resume by default. Restart, Stop and Escalate are explicit. |
ActorAddress | graphId/key, exposed on every ActorRef. | Local today. The address shape is the hook a cluster layer would resolve. |
ActorStatus | Created, Starting, Running, Stopping, Stopped or Failed(error), as a StateFlow. | Observable without touching the mailbox. |
ActorTimerHandle | Returned by schedule and every. | cancel() stops that timer. |
PersistentActorNode<In, State> | A durable state machine: a workflow node with declared states, transitions and a state store. | Its store, a node in its child graph, decides the order of transitions. |
NodeKind.Actor | How Hangar, the blueprint editor and the kernel recognize actors. | Both actor types report it, and so do Durable Object bindings. |
ask defaults to a 30-second timeout, and the mailbox defaults to MailboxPolicy(capacity = 64, overflow = BufferOverflow.SUSPEND).
The critical contract#
ActorRef.send(message)
-> mailbox accepts the message
-> actor loop receives messages FIFO
-> receive(message) mutates owned state
-> state flows, object state, services, and ports observe the result
Writing an actor#
Actor code reads like normal Reaktor code. The key is the only actor-specific identifier.
This is the read-receipt actor in BestBuds chat. It collects the chats a user has seen and sends one receipt per chat after a short delay.
internal sealed interface ChatRead {
data class Seen(val chat: String) : ChatRead
data class Flush(val chat: String) : ChatRead
}
internal val chatReadKey = actorKey<ChatRead>("chat/read-receipts")
internal class ChatReadReceipts(graph: Graph) : ActorNode<ChatRead>(graph, chatReadKey) {
private val markRead by consumes(MessagingApi().markRead)
private val pending = mutableSetOf<String>()
override suspend fun receive(message: ChatRead) {
when (message) {
is ChatRead.Seen -> if (pending.add(message.chat)) schedule(NudgeWindow, ChatRead.Flush(message.chat))
is ChatRead.Flush -> {
pending.remove(message.chat)
markRead.attempt(message.chat)
}
}
}
}
Graph declaration#
The chat graph provides each actor under its key:
provideActor(chatReadKey) { ChatReadReceipts(it) }
provideActor(chatOutboxKey) { ChatOutbox(it, me) }
Node consumption#
Another node consumes the actor by its key and sends it messages:
internal val reads: ConsumerPort<ChatReadReceipts> by actorConsumes(chatReadKey)
reads { trySend(ChatRead.Seen(chatId)) }
BestBuds imports provides and consumes from dev.shibasis.reaktor.actor as provideActor and actorConsumes, so they do not clash with the port functions of the same names.
Designing messages#
The message type is the actor's protocol, and every caller depends on it, so it deserves the same care as a service contract.
- One sealed interface per actor.
when (message)inreceive()then covers every case, and the compiler reports a message nobody handles. - Immutable data classes. A message is read by the actor after the sender has moved on. Copy mutable payloads before sending them.
SecurityNodecopies everyByteArrayit puts in a message, so a caller that reuses its buffer cannot change a message already in the mailbox. - The reply travels in the request. A message that expects an answer carries a
Reply<R>, asCounterMessage.Get(val reply: Reply<Int>)does in the tests. - Results of background work are messages too.
ChatOutboxhasPosted,Landed,FailedandFinishedfor the outcomes of uploads it started, alongsideQueue,Retry,DiscardandForwardfor requests from the screen. - One actor can own many entities.
ChatOutboxwraps every message inChatDelivery(chat, message), so one actor handles the outbox of every chat in order. - Private messages behind a public interface. When callers only need a few operations, keep the message classes private and give callers an interface whose methods enqueue messages, as Hiding the mailbox shows.
internal sealed interface OutboxMessage {
data class Queue(val pending: PendingMessage) : OutboxMessage
data class Retry(val id: String) : OutboxMessage
data class Posted(val pending: PendingMessage, val id: String) : OutboxMessage
data class Landed(val pending: PendingMessage, val message: ChatMessage) : OutboxMessage
data class Failed(val pending: PendingMessage, val problem: String) : OutboxMessage
data class Barrier(val reply: Reply<Unit>) : OutboxMessage
}
internal data class ChatDelivery(val chat: String, val message: OutboxMessage)
internal val chatOutboxKey = actorKey<ChatDelivery>("chat/outbox")
The block above is a shortened OutboxMessage; the real one also has Discard, Forward, Progress and Finished.
Sending, asking and replying#
| Call | What it does | When the mailbox is full | After the mailbox is closed |
|---|---|---|---|
send(message) | Puts the message in the mailbox. | Waits for room. | Throws ClosedSendChannelException. |
send { build() } | The same, with a builder. | Waits for room. | Throws. |
trySend(message) | Puts the message in if there is room, and returns whether it did. | Returns false. | Returns false. |
ask(timeout) { reply -> Get(reply) } | Sends a message that carries a Reply<R> and waits for the answer. | Waits for room first. The timeout starts once the message is in the mailbox. | Throws. |
askResult { reply -> Get(reply) } | An ask whose reply is a Result<R>, so a refused operation comes back as a failed Result while a timeout still throws. | As ask. | As ask. |
The table describes the default SUSPEND mailbox. With DROP_OLDEST or DROP_LATEST, send never waits and trySend always reports success, even for a message that was dropped.
The rules for replies:
- Complete a reply once.
completeandfailreturnfalsewhen the reply was already completed. - A reply can be completed later, from another message. Keep the
Replyin a field and complete it when the answer is known.ChatOutbox.awaitIdle()uses the simplest form: it sends aBarrier(reply), and because the mailbox is first in, first out, the barrier is handled only after every message queued before it. - When
receive()throws, the actor fails the waiting ask with the same error before the supervisor strategy runs. - When nobody completes the reply, the caller gets a
TimeoutCancellationExceptionafter the timeout.
Prefer send. An ask holds its caller until the actor reaches the message, so a chain of asks between actors adds up every wait, and a cycle of asks waits until the timeouts fire. Akka's advice to prefer tell over ask, and OTP's habit of using cast unless an answer is needed, both apply. Keep asks at the edges: screens that need a result, facades, and tests.
Mailbox and back-pressure#
MailboxPolicy(capacity, overflow) sets the mailbox when the actor is constructed. The default, 64 messages with BufferOverflow.SUSPEND, makes senders wait when the actor falls behind. That slows producers down to the actor's pace, which is back-pressure: the queue stays bounded and no message is lost.
| Overflow | When the mailbox is full | Use it for | Trap |
|---|---|---|---|
SUSPEND (default) | send waits; trySend returns false. | Commands that must not be lost. | Code that must not wait, such as a click handler, has to use trySend or launch the send. |
DROP_OLDEST | The oldest queued message is dropped. | Streams where only the latest value matters: presence, typing, progress. | A dropped ask waits for its whole timeout. |
DROP_LATEST | The new message is dropped. | Sampling a burst. | The sender is told it succeeded. |
Erlang processes have unbounded mailboxes, and a mailbox that grows faster than its process drains it is a classic way for an Erlang node to run out of memory. Designing for Scalability with Erlang/OTP treats load regulation and back-pressure as part of scaling out for that reason, and Fred Hébert's essay Handling Overload lays out the choices: make producers wait, drop work, or refuse it at the edge. Akka's default mailbox is unbounded too, and bounded mailboxes are configured per actor. Reaktor bounds every mailbox by default, so overload shows up as senders that wait.
Decide where to shed load before it reaches the actor. A search screen can keep only the latest query, and a Worker route can answer 429. A capacity of Channel.UNLIMITED is possible, and it removes the back-pressure along with the limit.
How receive runs#
Every actor runs on its graph's dispatcher limited to a parallelism of one (dispatcher.limitedParallelism(1)), and the loop takes the next message only after receive() returns. Two receive() calls never overlap, even when receive() suspends on a network call: the next message waits until it returns.
The actor's other coroutines, its timers and the jobs it launches in coroutineScope, run on the same dispatcher. They can run while receive() is suspended, between its suspension points, so they must not change the actor's state themselves. To change it, they send the actor a message.
That is how ChatOutbox keeps uploads from blocking the queue. The upload runs as a job beside the actor, and each outcome comes back as a message. A shortened version:
override suspend fun receive(delivery: ChatDelivery) {
when (val message = delivery.message) {
is OutboxMessage.Queue -> {
timeline { update(delivery.chat) { it.copy(pending = it.pending + message.pending) } }
uploads[delivery.chat to message.pending.id] = coroutineScope.launch {
val landed = upload(delivery.chat, message.pending)
send(ChatDelivery(delivery.chat, OutboxMessage.Landed(message.pending, landed)))
}
}
is OutboxMessage.Landed -> timeline { update(delivery.chat) { it.copy(pending = it.pending - message.pending) } }
}
}
Akka calls this pattern pipeToSelf, and an OTP gen_server gets the same effect by receiving the result of a spawned worker in handle_info. The slow work runs beside the actor, the mailbox keeps moving, and the state still changes in one place.
A call that blocks a thread, such as file IO on the JVM, stops the actor and ties up a thread of the graph's dispatcher for as long as it runs. Move it to an IO dispatcher inside a launched job.
Timers#
schedule(delay, message) sends one message after a delay, and every(interval) { message } sends one after every interval. Both return an ActorTimerHandle. A timer delivers an ordinary message through the mailbox, so a timer never races with receive().
The read-receipt actor debounces with schedule: the first Seen for a chat schedules one Flush, and later Seen messages for that chat do nothing until it fires.
To restart a timer, remember which one is current. A cancelled timer may already have put its message in the mailbox, so cancel() alone cannot stop that message from arriving. Give each timer message a token and ignore the ones that are no longer current:
private val typing = mutableMapOf<String, Long>()
private var tokens = 0L
private var heartbeat: ActorTimerHandle? = null
override suspend fun preStart() {
heartbeat = every(30.seconds) { RoomMsg.Heartbeat }
}
override suspend fun postStop() {
heartbeat?.cancel()
}
override suspend fun receive(message: RoomMsg) {
when (message) {
is RoomMsg.Typing -> {
val token = ++tokens
typing[message.user] = token
schedule(5.seconds, RoomMsg.StoppedTyping(message.user, token))
}
is RoomMsg.StoppedTyping -> if (typing[message.user] == message.token) typing.remove(message.user)
RoomMsg.Heartbeat -> beat()
}
}
Akka's TimerScheduler builds this in: starting a timer with a key cancels the previous timer with that key, and Akka guarantees that the previous timer's message is not received even if it was already queued. gen_statem cancels a state timeout by itself when the state changes. Reaktor returns a handle, so the actor checks the token itself.
Timers belong to the node's scope. Saving the node pauses the loop and leaves its timers running, so messages from timers that come due during a pause wait in the mailbox and run after the restore. preStart() runs again on every restore, so a timer started there must be cancelled in postStop(), as above, or it runs twice. Destroying the node cancels its scope and every timer with it.
Lifecycle and status#
status.| Node lifecycle | What the actor does |
|---|---|
Attaching, Restoring | Starts the loop and runs preStart(). Starting is idempotent, so a running loop is left alone. |
Saving | Cancels the loop and leaves the mailbox open, so Saving then Restoring resumes with the queued messages. Timers keep running. |
Destroying | Closes the mailbox and cancels the loop. Closing the node then closes its ports and its scope. |
preStart() runs every time the loop starts, and postStop() every time it stops, including each save and restore. Open sockets and start timers in preStart(); close and cancel them in postStop().
status is a StateFlow<ActorStatus>, so any node or screen can watch an actor without sending it a message. Failed keeps its error, and the stop that follows a failure does not overwrite it.
Supervision#
A failed message does not kill the actor by default. The waiting ask fails, onFailure runs, and the default directive is Resume. That suits app actors, where one bad user event should not destroy an open chat session.
Set a strategy for every actor in a graph, or override onFailure in one actor:
graph.actorSupervisorStrategy = ActorSupervisorStrategy { _, _, error ->
when (error) {
is SerializationException -> ActorDirective.Resume
is IllegalStateException -> ActorDirective.Restart
else -> ActorDirective.Escalate
}
}
override suspend fun onFailure(message: RoomMsg, error: Throwable): ActorDirective =
if (message is RoomMsg.Join) ActorDirective.Restart else super.onFailure(message, error)
| Directive | What happens |
|---|---|
Resume | The loop takes the next message. Fields keep whatever the failed message left in them. |
Restart | The status moves through Stopping and Starting: postStop() runs, then preStart(), on the same object. The fields and the mailbox stay, so preStart() must reset what a restart should reset. |
Stop | The mailbox closes, so later sends fail, and the loop ends. Messages still queued may never run, and an ask among them waits for its timeout. |
Escalate | The error leaves the loop. The status becomes Failed(error), and the node scope's exception handler receives the error, which logs it unless the graph supplied its own handler. The node's scope is a supervisor scope, so its timers and the graph keep running. |
Erlang's practice, often summed up as "let it crash", is to let a process that hits an unexpected error die, and to let its supervisor start a fresh process from known-good state. Recovery code is replaced by restart, and restart always means clean state. Akka works the same way: restarting a typed actor builds a new behavior, so state held in the old one is gone, and Akka Typed stops a failing actor unless a supervisor strategy says otherwise. A Reaktor Restart keeps the object, so the "clean state" half of the idea is your job: reset fields in preStart() and reload what must survive from the actor's store.
Three things an OTP supervisor gives that Reaktor does not have yet: a restart limit (at most a number of restarts in a time window, after which the supervisor itself gives up and fails upward), strategies that restart siblings together (one_for_all, rest_for_one), and a supervision tree in which failures climb from child to parent. A graph supervises its actors one at a time today. Next work proposes the first two.
State#
In-memory fields suit fast runtime state: sockets, pending reactions, timers and caches. A decision that must survive an app restart is written to the actor's store.
Every actor has one exclusive object store derived from its key, named actors/ followed by the key's name (characters other than letters, digits, ., _, - and : become _). state<T>(name) opens a named record in it. An actor that needs several pieces of state opens one named record for each in the same store.
class RoomActor(graph: Graph, id: String) : ActorNode<RoomMsg>(graph, actorKey("room/$id")) {
private val summary = state<RoomSummary>("summary")
private val members = state<RoomMembers>("members")
override suspend fun receive(message: RoomMsg) {
when (message) {
is RoomMsg.Join -> members.updateOrCreate({ RoomMembers() }) { it + message.userId }
}
}
}
ObjectState<T> call | What it does |
|---|---|
get() | Loads the value once, then serves it from memory and the store cache. |
set(value) | Writes the value. |
update { } | Reads the latest value, transforms it and writes it; fails when the record is missing. |
updateOrCreate(create) { } | The same, starting from create() when the record is missing. |
values | A Flow of the value that follows every write to the record, for screens. |
delete() | Removes the record. |
Feature.Database must be set before an actor opens its store; otherwise the first state() call fails with a message naming the actor. A record that cannot be decoded is set aside under a quarantine name and read as missing, so a default written back over it cannot destroy the original bytes.
Write the decision before acting on it. ChatOutbox saves the unsent messages of a chat (keepUnsent) before it delivers them, so a restarted app can send them again. Reaktor stores the current value of each record. Event sourcing in the style of Akka Persistence, where an actor stores events and rebuilds its state by replaying them, is not built.
Identity, lookup and wiring#
ActorKey derives everything else from the actor's name. Its node id is a stable UUID computed from reaktor.actor: and the name, and its store name is actors/ and the name. The same name therefore gives the same node id and the same store on every run, which is why a renamed key orphans the actor's stored state. ActorAddress(graphId, key) prints as graphId/key.
provides(key) { create }returns the actor already attached under that key, or creates one and attaches it. It rejects an actor built for a different key.consumes(key)registers a typed consumer port named after the key, with the concrete actor type taken from the property.Graph.findActorNode(key)andGraph.findActor(key)look an actor up by its node id and check that the node is an actor with that key and type.- A second actor with the same key cannot attach:
graph.attachreturnsfalse.
Keys can name entities: actorKey<RoomMsg>("room/$id") gives every room its own actor, mailbox and store, created on first use. The key plays the part of a registered name in Erlang and of a Receptionist ServiceKey in Akka: callers find an actor by a name they can compute, and the graph is the registry. That registry covers one graph in one process.
Because the backing node store preserves Collection, code that iterates graph.nodes keeps working, and actors appear in it like any other node.
Hiding the mailbox behind an interface#
Most callers want a few operations and no knowledge of the message types. SecurityNode, the device security actor in reaktor-security, provides a plain suspend interface whose methods ask, and keeps every message class private:
sealed interface SecurityCommand
private data class DeviceCommand(val reply: Reply<DeviceCryptoIdentity>) : SecurityCommand
private data class KeyRingCommand(val reply: Reply<SealedSecret>) : SecurityCommand
class SecurityNode(graph: Graph, private val telemetry: SpanSink? = null) : ActorNode<SecurityCommand>(graph, actorKey("security/device")) {
val security by provides<ReaktorSecurity>(object : ReaktorSecurity {
override suspend fun device(): DeviceCryptoIdentity = ask { DeviceCommand(it) }
override suspend fun sealedKeyRing(): SealedSecret = ask { KeyRingCommand(it) }
})
}
The block above is shortened; the real interface also seals, opens and reconciles conversations, and receive() wraps every message in a telemetry span. Callers consume ReaktorSecurity like any other port and never see the mailbox, yet every operation still runs one at a time. Hangar's CommandQueueActor does the same with methods such as suspend fun applyAll() = ask { CommandQueueMsg.ApplyAll(it) }.
An Erlang gen_server module does the same thing: it exports plain functions that wrap gen_server:call and gen_server:cast, so callers never build its messages.
Durable state machines#
PersistentActorNode has no mailbox of its own. Its store's transact() decides which call goes first.PersistentActorNode<In, State> is a Workflow node of kind Actor with three declarations: its states, its transitions (each a message name with the states it may start from and end in), and a function that names the current state. Its state store is a node in its child graph. transition(name, effect) { input, state -> } returns an Activity, a typed port with its own span, and each call runs five steps:
transact(input)on the store locks and loads the state.- The current state must be in the transition's
fromset. - The transition's code runs, calling activities and stages.
- The new state must be in its
toset. - The states before and after, and whether the call completed, are recorded as decisions on the activity span.
The store plays the part of the mailbox. A Mutex orders calls inside one isolate. A database row lock orders them across every Worker instance and machine, which is why the Circle lifecycle runs each transition inside a transaction that starts with SELECT id FROM campaigns WHERE chat_id = … FOR UPDATE.
class WeeklyRuns(graph: Graph) : ActorStore<WeeklyWake, WeeklyRun>(graph, "circle_formation_runs") {
private val ledger by consumes<FormationLedger>()
private val mailbox = Mutex()
override suspend fun <Out> transact(input: WeeklyWake, execute: suspend (WeeklyRun) -> Out): Out = mailbox.withLock {
execute(WeeklyRun(ledger.suspended { formed(input.scheduleKey) }))
}
}
class WeeklyFormation(graph: Graph) : PersistentActorNode<WeeklyWake, WeeklyRun>(
graph, "circle-formation/weekly", "Weekly Circle formation", setOf("pending", "committed"),
listOf(ActorTransition("wake", setOf("pending", "committed"), setOf("pending", "committed"))),
{ run -> if (run.committed) "committed" else "pending" }, ::WeeklyRuns,
) {
val wake = transition<Unit>("wake", Effect.ProductionReversibleWrite) { week, state ->
if (!state.committed && due(week)) {
commit(FormationCommit(preview(FormationPreview(), week.scheduleKey), week.configuration))
state.committed = true
}
}
}
The block above is shortened from BestBuds. The store loads whether this week's run has already committed (formed(scheduleKey)), so a second wake for the same week does nothing. That makes the transition idempotent, which is what a retried or repeated message needs. stage(name, effect) names the steps inside a transition; the Circle lifecycle has open-rounds, reveal-answers, mutual-connections and wrap-and-requeue.
ActorNode | PersistentActorNode | |
|---|---|---|
| Ordering | Its in-memory mailbox | Whatever its store's transact() locks |
| Where it can run | One process | Anywhere the store reaches, including many Worker instances |
| State | Fields and the actor's ObjectStore | Loaded by the store for each call |
| Input | A sealed message type | Named transitions with a typed input |
| Timers | schedule and every | None; a schedule or a route calls it |
| In Hangar | An actor node | An actor node that carries its states and transitions |
In OTP terms this is a gen_statem whose mailbox is a database row. In Akka terms it is closest to a durable state actor. Akka saves that state through a persistence plugin, and here the actor's store writes it directly. Every BestBuds lifecycle declares each transition from any state to any state today, so the from and to checks only catch states nobody declared. Narrowing each transition to the states it really belongs to would turn the checks into real guards.
Testing actors#
The framework's own tests show the pattern. Run the graph on a StandardTestDispatcher so scheduling and timers are deterministic, provide the actor, send messages, and read the result with an ask:
@Test
fun actorProcessesMessagesSequentiallyAndRepliesThroughAsk() = runTest {
val graph = Graph(dispatcher = StandardTestDispatcher(testScheduler), dependencyAdapter = ActorTestDependencyAdapter())
try {
val actor = graph.provides(CounterKey, ::CounterActor)
actor.send(CounterMessage.Add(1))
actor.send(CounterMessage.Add(2))
actor.send(CounterMessage.Add(3))
assertEquals(6, actor.ask { reply -> CounterMessage.Get(reply) })
} finally {
graph.close()
}
}
- An ask is a barrier. It returns only after every message sent before it, which is why the test needs no sleeps.
- A
Get(reply)message plays the part of OTP'ssys:get_stateand of an AkkaTestProbe: it reads the state through the mailbox. - Set
Feature.Databaseto a testObjectDatabasebefore testing an actor with state. - Drive the lifecycle directly with
actor.transition(Lifecycle.Saving)andactor.transition(Lifecycle.Restoring). - Virtual time from
runTestmoves timers:advanceTimeByfires aschedulewithout waiting.
ActorNodeIntegrationTest covers ordering, failures, port wiring, exclusive stores and save and restore. PersistentActorNodeTest covers the durable variant, and BestBuds' ChatRuntimeGraphTest checks that the chat graph keeps its actors across chat navigation.
Patterns#
| Pattern | How | Where |
|---|---|---|
| Debounce | A pending set and one timer per key | ChatReadReceipts |
| Barrier | An ask that completes when it reaches the front of the mailbox | ChatOutbox.awaitIdle() |
| Work beside the actor | Launch the slow call and send its result back as a message | ChatOutbox uploads |
| Facade | A provided interface whose methods ask | SecurityNode, CommandQueueActor |
| One actor per entity | A key per entity id, created on first use | actorKey("room/$id") |
| Outbox | Save the intent before the effect and resend it after a restart | ChatOutbox with keepUnsent |
| Idempotent transition | Load "already done" in the store and skip the work | WeeklyFormation with formed(scheduleKey) |
| Replaceable timer | Keep each handle in a map under your own key | Timers |
Lessons from Akka and Erlang/OTP#
Two books describe large systems built from actors. Akka in Action (Manning; the second edition, by Francisco Lopez-Sancho Abraham, covers Akka Typed) follows actors on the JVM from one process to a cluster. Designing for Scalability with Erlang/OTP (Francesco Cesarini and Steve Vinoski, O'Reilly) shows how OTP's behaviours and supervisors keep Erlang systems running through failures and growth. Reaktor actors share their core: private state, one mailbox, messages as the only way in, and a supervisor that decides what a failure means. The tables below place each idea from the books next to what Reaktor has today.
Messaging#
| Idea | Akka | Erlang/OTP | Reaktor today |
|---|---|---|---|
| Send without waiting | tell (!) | gen_server:cast, ! | send, trySend |
| Ask with a deadline | ask with a timeout; the reply goes to a replyTo ref | gen_server:call, 5 seconds by default | ask, 30 seconds by default; askResult |
| Answer later | Keep replyTo and answer from a later message | Return noreply and answer with gen_server:reply | Keep the Reply and complete it from a later message |
| Result of slow work | context.pipeToSelf | A spawned worker reports to handle_info | Launch a job in coroutineScope and send the result |
| Typed protocol | Behavior[Command] with sealed traits | Tuples, checked by convention and Dialyzer | ActorKey<M> with a sealed interface |
| Hiding the protocol | Message adapters | API functions in the gen_server module | A provided interface whose methods ask |
| Messages that arrive too early | StashBuffer | Selective receive | Missing; keep them in a field until the actor is ready |
| Ordering | Per sender and receiver pair | Per sender and receiver pair | One first-in, first-out mailbox per actor |
Failure and supervision#
| Idea | Akka | Erlang/OTP | Reaktor today |
|---|---|---|---|
| Default on failure | Akka Typed stops the actor | The supervisor restarts the process as its child spec says | Resume |
| Restart | A new behavior with fresh state | A new process; init/1 runs again | postStop() then preStart() on the same object |
| Restart limit | restart.withLimit(maxNrOfRetries, withinTimeRange) | Intensity and period: too many restarts in a window and the supervisor fails too | Missing |
| Backoff | restartWithBackoff | Not in the standard supervisor | Missing |
| Siblings | Each parent decides for its children | one_for_one, one_for_all, rest_for_one | Missing; each actor is supervised alone |
| Supervision tree | The actor hierarchy | Supervisors of supervisors, with the error kernel at the top | The graph supervises its actors; child graphs nest, and failures do not climb them |
| Watching another actor | context.watch and Terminated | monitor, link and 'DOWN' messages | Collect its status flow; nothing is delivered automatically |
| Lifecycle hooks | PreRestart and PostStop signals | init/1 and terminate/2 | preStart() and postStop() |
State and persistence#
| Idea | Akka | Erlang/OTP | Reaktor today |
|---|---|---|---|
| State machines | Return a different behavior per state | gen_statem with states, events, state timeouts and postponed events | PersistentActorNode; in an ActorNode, a sealed state field |
| Timers | TimerScheduler with keyed single and periodic timers | erlang:send_after; gen_statem timeouts | schedule and every, with handles |
| Durable state | Akka Persistence: event sourcing, snapshots and durable state | ETS, DETS and Mnesia | state<T>(name) in the actor's ObjectStore |
| Recovery | Load the latest snapshot and replay the events after it | init/1 reloads what it needs | preStart() reads the store; PersistentActorNode loads on every call |
| Exactly-once effects | Deduplicate by id; reliable delivery | Idempotent handlers by convention | Idempotent transitions such as formed(scheduleKey); an outbox |
Scaling out#
| Idea | Akka | Erlang/OTP | Reaktor today |
|---|---|---|---|
| Finding an actor | The Receptionist and a ServiceKey | Registered names, global and pg | ActorKey lookups inside one graph |
| One actor per entity across machines | Cluster Sharding, with passivation of idle entities | Process groups (pg), with sharding built by the application | Design: one Durable Object per key |
| Exactly one instance | Cluster Singleton | A global registration | Design: one Durable Object name |
| Replicated state without an owner | Distributed Data, built on CRDTs | Riak's CRDT library, riak_dt | Design: CRDTs |
| Pools of workers | Pool and group routers | Worker pools | Missing; a facade over several keyed actors |
| Delivery | At most once by default; Reliable Delivery adds acknowledgements | At most once; acknowledgements by hand | In order and without loss while the process lives; durable delivery through an outbox or a PersistentActorNode |
Designing for scale#
The later chapters of both books turn from single actors to systems. Their advice, applied to Reaktor:
- One actor per entity. Key actors by what they own, a room, a chat or a Circle, so the load spreads over many small mailboxes and each key can move to its own machine later. An actor per feature becomes the bottleneck that sharding exists to remove.
- Keep the error kernel small. OTP puts the state that must never be lost near the top of the supervision tree and lets everything below it crash. In Reaktor, keep that state in stores and in
PersistentActorNodetransitions, so any actor can restart without losing it. - Bound every queue and choose what happens at the limit. Wait, drop or refuse. Decide it per message type, and shed load at the edge before it reaches a mailbox.
- Make messages idempotent. Retries, redelivery after a restart and impatient users all repeat messages. Give commands an id, record what was done, and skip repeats, as
WeeklyFormationdoes with its schedule key. - Avoid chains of asks. Each ask waits for another mailbox, and a cycle of asks deadlocks until the timeouts fire. Send, and let the answer come back as a message.
- Choose consistency per piece of state. Give state with invariants one owner, an actor or a Durable Object. Let state that must keep working offline merge as a CRDT. Keep invariants across entities in database transactions, as the data layer describes.
- Measure overload before it happens. Mailbox depth, time spent waiting in the mailbox, handling time and restarts tell you which actor is falling behind. Erlang in Anger is a field guide to reading these signals on a live system. Reaktor does not expose mailbox depth yet.
- Let the platform place keys. On Cloudflare a Durable Object per key gives each entity single-threaded execution, its own storage and alarms, and a machine chosen by the platform. That is the job Akka's sharding and Orleans' virtual actors do for a cluster.
BestBuds and Hangar actors#
| Actor | Type | What it owns |
|---|---|---|
ChatOutbox (chat/outbox) | ActorNode | Every outgoing chat message: queueing, upload progress, posting, retries, discards and forwards |
ChatReadReceipts (chat/read-receipts) | ActorNode | The chats with unsent read receipts, each flushed by a timer |
SecurityNode (security/device) | ActorNode | The device's encryption state and keys, behind ReaktorSecurity |
CommandQueueActor, ShellActor | ActorNode | The Hangar workbench's command queue, and its selection, layout and environment |
WeeklyFormation (circle-formation/weekly) | PersistentActorNode | The weekly Circle formation run |
| Circle lifecycle | PersistentActorNode | A Circle's phases, locked per campaign row |
| Verification lifecycle | PersistentActorNode | A user's document verification status |
| Account purge, database backup | PersistentActorNode | Purge and backup runs |
BestBuds chat receives events from many sources at once: the screen, the chat socket, uploads, retries and timers. ChatOutbox handles every outgoing message one at a time, in order, and awaitIdle() sends a barrier through the mailbox so a caller can wait until every queued message has been handled. ChatReadReceipts keeps the set of chats with unsent receipts, so scrolling through many messages sends one receipt per chat. The rest of chat state, such as the timeline and the pages already loaded, lives in ordinary nodes that the actors consume.
Cloudflare alignment#
Cloudflare Durable Objects are the backend reference point. Cloudflare describes Durable Objects as stateful serverless units with compute and storage, and its Actors package wraps Durable Objects with actor-oriented helpers.
ActorKey.name
-> Durable Object namespace id/name
-> one backend actor instance
-> actor-owned storage
-> HTTP/RPC/WebSocket/alarm messages
The path to that mapping:
- Local app actor: graph node plus mailbox. Built.
- Worker actor: a Durable Object wrapper with the same receive discipline. Designed.
- Storage: the
ObjectStoreabstraction over local databases or Durable Object storage. Designed. - Timers: coroutine timers locally, Durable Object alarms in the backend adapter. Designed.
reaktor-cloudflare ships the raw Durable Object bindings (DurableObjects.kt, PartyServer, blockConcurrencyWhile, WebSocket hibernation), and BestBuds drives them directly for chat rooms and notification dispatch. DurableObjectIngress draws a Durable Object as a node of kind Actor, and Durable Object bindings appear as actors in Hangar's deployment views, but neither carries messages. The missing piece is the adapter that turns a binding into an ActorRef. Until it exists, a PersistentActorNode with a database row lock is how Workers get one transition at a time per entity. The data layer treats a Durable Object as one consistency profile among several.
Location-transparent remoting is out of scope for the actor core. Running an actor as a Durable Object is a backend adapter, and an ActorRef that hides whether a call crosses the network would hide the failures and latency that callers need to design for.
Actors and CRDTs#
An actor gives a piece of state one owner, and every change waits its turn in that owner's mailbox. That keeps invariants, and it needs the owner to be reachable. A CRDT lets several replicas accept writes on their own, offline included, and merge later without conflicts, at the price of every invariant the merge cannot keep. The two combine: in the proposed design an actor owns each local replica, so local edits and remote changes still apply one at a time. CRDTs describes it.
Invariants#
- There is no
ActorSystem,ActorGraphorActorRepository. The durable variant,PersistentActorNode, is a workflow node in the same graph. - Actor identity is the key. Activation is a graph node instance.
- The raw mailbox channel is private.
- Every external mutation enters through
send,trySendorask, including socket and timer events. - Actor state helpers use the actor-owned
ObjectStore. - Services remain transport endpoints. Repositories remain data access. Actors own serialized mutable behavior.
- Methods on concrete actors are acceptable only when they enqueue messages and leave the state to
receive(). - The graph's node collection remains the source of truth for actors and other nodes.
What actors improve#
| Usual approach | What goes wrong | The actor approach |
|---|---|---|
| Shared state guarded by locks | Every caller has to take the lock correctly. A missed lock is a race that tests rarely catch, and a lock held across a suspending call can block other work for a long time. | Only receive() touches the state, one message at a time, so there is nothing to lock. |
| State kept in a screen or its view model | Events from sockets, timers and other screens have to be routed through the screen, and the state disappears when the screen closes. | The actor is a graph node with its own lifecycle. Any node can send it messages, and it outlives a single screen. |
| Callbacks that change state when slow work finishes | Callbacks fire on other threads, in any order, and change state while other code reads it. | Slow work runs beside the actor and reports back as messages, which receive() handles in order. |
| Unbounded queues between producers and consumers | Under load the queue grows until the process runs out of memory, and nothing slows the producers. | Every mailbox is bounded, and a full one makes senders wait. |
| A separate actor framework | A second runtime brings its own actor system, its own lifecycle and its own way to find actors. | ActorNode is an ordinary node. It is wired with ports, supervised by its graph and drawn in Hangar like any other node. |
Limitations#
- Actors are local. An actor lives in one process. Actors that span machines, and the bridge to Durable Objects, are designs, as Cloudflare alignment explains.
- One slow message delays the rest. The mailbox handles one message at a time, so long work such as an upload should run beside
receive()and report back as messages, asChatOutboxdoes. - An actor must not wait for itself. An actor that asks itself, or two actors that ask each other at the same time, wait until the timeout, because neither mailbox can move on.
- An ask's timeout starts after its message is in the mailbox. When the mailbox is full,
askfirst waits for room with no time limit. - Dropping mailboxes drop asks silently. With
DROP_OLDESTorDROP_LATEST, a dropped ask waits for its whole timeout, andtrySendreports success for a message it dropped. - Saving cancels the message in flight. A message that is being handled when the node saves is cancelled. Its ask fails with a cancellation,
onFailuresees the cancellation as an ordinary failure, and when messages are queued, each one that suspends can be cancelled the same way before the loop stops. - Restart keeps the object. Fields survive a
Restart, sopreStart()has to reset them. - After
Escalatethe mailbox stays open. Sends succeed until it is full and then wait, asks time out, and the loop does not restart until the node is saved and restored. - After
Stop, queued messages may never run. - Timers outlive pauses. They keep running while the node is saved, and
preStart()runs on every restore, so cancel timers inpostStop(). - Fields do not survive a process restart. A decision that must survive has to be written to the actor's store.
- No supervision tree, restart limit, watch or mailbox metrics. Each actor is supervised alone, and nothing reports mailbox depth.
- Keys carry no tenant. Actors of different tenants share one key space, which Next work proposes to change.
- Durable lifecycles allow every transition. BestBuds declares each
PersistentActorNodetransition from any state to any state.
Next work#
Hardening the actor core:
- Rethrow cancellation in the loop's failure handler and check for it before taking the next message, so a save never cancels queued messages or reports a cancellation as a failure.
- Start an ask's timeout before its message enters the mailbox, so a full mailbox cannot hold an ask forever.
- Add a restart limit in the style of OTP, at most N restarts in a window before the failure escalates, and a backoff option in the style of Akka's
restartWithBackoff. - Add a watch: let an actor receive a message when another actor fails or stops, built on
status. - Report mailbox depth, time in the mailbox and handling time as telemetry for each actor.
- Decide what
Escalateleaves behind: close the mailbox so senders fail fast, or let a parent restart the actor. - Add keyed timers that replace an earlier timer with the same key and stop when the loop stops.
- Cover restart, stop, escalation and ask timeouts with checks.
- Node ids and store names come from
stableActorUuidandstableActorStoreNameonActorKey. Keep them stable across renames, because a changed key silently orphans an actor's store. - Actor keys carry no tenant. Adding a tenant to
ActorKeywould keep each tenant's actors apart by construction. The change is cheap now and expensive once actors span machines. - Narrow the
fromandtosets of BestBuds'PersistentActorNodetransitions to the states each message belongs to.
The Cloudflare adapter:
- Create a Durable Object wrapper that deserializes requests into actor messages.
- Back actor
state()with Durable Object storage or a SQLite-backedObjectStore. - Map actor timers to Durable Object alarms.
- Generate handler surfaces for typed ask and send endpoints.
Where the code lives#
| Area | Files |
|---|---|
| Actor primitive | reaktor-actor/src/commonMain/.../actor/ActorNode.kt |
| Durable state machines | reaktor-actor/src/commonMain/.../actor/PersistentActorNode.kt, on Workflow.kt and Stage.kt in reaktor-graph-runtime |
| Graph supervision | reaktor-actor/src/commonMain/.../actor/ActorNode.kt (Graph.actorSupervisorStrategy, kept in a graph attachment) |
| Stored actors | reaktor-db/src/commonMain/.../node/StoredActorNode.kt |
| Node scope and dispatcher | reaktor-graph-runtime/.../core/node/Node.kt, reaktor-core/.../capabilities/ConcurrencyCapability.kt |
| Actor state | reaktor-db/src/commonMain/.../core/ObjectState.kt |
| Concurrent node collection | reaktor-graph-port/src/commonMain/.../graph/PortGraph.kt |
| Durable Objects in the graph | reaktor-cloudflare/src/jsMain/.../GraphIngress.kt (DurableObjectIngress) |
| BestBuds chat | ChatOutbox.kt and ChatNodes.kt (ChatReadReceipts) in bestbuds/modules/app/src/commonMain/.../features/messaging/ |
| BestBuds durable lifecycles | WeeklyFormation.kt, and CirclesWorker.kt, VerificationLifecycle.kt, AccountPurgeWorker.kt and ArchiverWorker.kt under bestbuds/modules/app/src/jsMain/.../cloudflare/ |
| Device security | reaktor-security/src/commonMain/.../SecurityNode.kt |
| Hangar workbench | hangar/core/src/commonMain/.../workbench/data/actors/ |
| Tests | reaktor-db/src/commonTest/.../ActorNodeIntegrationTest.kt, reaktor-actor/src/commonTest/.../PersistentActorNodeTest.kt, BestBuds ChatRuntimeGraphTest.kt |
Sources#
Books:
- Francisco Lopez-Sancho Abraham, Akka in Action, second edition, Manning, 2023. Akka Typed from single actors to clusters, persistence and sharding. The first edition, by Raymond Roestenburg, Rob Bakker and Rob Williams, covers classic Akka.
- Francesco Cesarini and Steve Vinoski, Designing for Scalability with Erlang/OTP, O'Reilly, 2016. OTP behaviours, supervision trees, load regulation and distributed architecture.
- Fred Hébert, Erlang in Anger, a free guide to running Erlang systems in production, and Learn You Some Erlang, whose supervisors chapter explains restart strategies and limits.
- Gul Agha, Actors: A Model of Concurrent Computation in Distributed Systems, MIT Press, 1986.
Papers:
- Carl Hewitt, Peter Bishop and Richard Steiger, A Universal Modular ACTOR Formalism for Artificial Intelligence, IJCAI, 1973. The paper that introduced actors.
- Joe Armstrong, Making reliable distributed systems in the presence of software errors, PhD thesis, KTH, 2003. The reasoning behind Erlang's processes and supervisors.
- Philip Bernstein, Sergey Bykov, Alan Geller, Gabriel Kliot and Jorgen Thelin, Orleans: Distributed Virtual Actors for Programmability and Scalability, Microsoft Research, 2014. Actors that exist logically and are activated on demand, the model Durable Objects resemble.
Documentation and essays:
- Erlang/OTP: Design Principles, Supervisor Behaviour, gen_server Behaviour and gen_statem Behaviour.
- Akka: Actors, Fault Tolerance, Interaction Patterns, Stash, Persistence, Cluster Sharding and Message Delivery Reliability.
- Fred Hébert, The Zen of Erlang, on what "let it crash" means in practice, and Handling Overload, on back-pressure and load shedding.
- Kotlin: Channels and
BufferOverflow, the primitives under the mailbox. - Cloudflare: Durable Objects, What are Durable Objects? and the Actors repository.
Related docs#
- Graph - How nodes, ports and graphs fit together, and how an actor is wired like any other node.
- CRDTs - Replicated state that merges without an owner, and how a replica actor would hold it.
- Data layer - Consistency profiles, including serialized entity authority and convergent replicated state.
- Work - Use before changing background scheduling, worker contracts, WorkRequest/WorkConstraints, BestBuds workers, edge/web scheduling, work telemetry, or graph projection for work.
- Service Layer - Use before adding service APIs, splitting reaktor-service out of reaktor-graph, wiring handlers to Spring/Workers, or making modules graph-projectable without hard graph dependencies.
- Security - The device security design that
SecurityNodeimplements.