Skip to content
37 min readUpdated 24 Nov 2026

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#

An actor. Many senders put messages into one mailbox. The actor takes them out in order and runs receive() for one message at a time, so its private state never needs a lock. receive() changes the state and makes the calls, and other nodes see the result through ports and state flows.Chat screensend(Seen(chat))WebSocket sessionsend(Incoming(message))A timerschedule(window, Flush(chat))Another nodeask { reply -> Query(reply) }MAILBOX, FIRST IN FIRST OUTSeen("a")Seen("a")Seen("b")nextDefault capacity 64; a full mailboxmakes send() wait instead of dropping.Senders only ever touch the mailbox.receive(message)the only code thatchanges the statePrivate statepending = {a, b}its own ObjectStore,named after the actor's keyEffectsservice calls: markRead(chat)state flows that screens readreplies to ask()timers it schedules
Every sender puts messages into one mailbox. 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 Handling to 0.05.seconds, or move the second message to at(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.

ConceptRoleDesign 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.
MailboxPolicyCapacity and overflow.Bounded and suspending by default, so overload is visible.
ActorDirective, ActorSupervisorStrategyWhat happens after a failed message.Resume by default. Restart, Stop and Escalate are explicit.
ActorAddressgraphId/key, exposed on every ActorRef.Local today. The address shape is the hook a cluster layer would resolve.
ActorStatusCreated, Starting, Running, Stopping, Stopped or Failed(error), as a StateFlow.Observable without touching the mailbox.
ActorTimerHandleReturned 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.ActorHow 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) in receive() 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. SecurityNode copies every ByteArray it 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>, as CounterMessage.Get(val reply: Reply<Int>) does in the tests.
  • Results of background work are messages too. ChatOutbox has Posted, Landed, Failed and Finished for the outcomes of uploads it started, alongside Queue, Retry, Discard and Forward for requests from the screen.
  • One actor can own many entities. ChatOutbox wraps every message in ChatDelivery(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#

CallWhat it doesWhen the mailbox is fullAfter 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. complete and fail return false when the reply was already completed.
  • A reply can be completed later, from another message. Keep the Reply in a field and complete it when the answer is known. ChatOutbox.awaitIdle() uses the simplest form: it sends a Barrier(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 TimeoutCancellationException after 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.

OverflowWhen the mailbox is fullUse it forTrap
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_OLDESTThe oldest queued message is dropped.Streams where only the latest value matters: presence, typing, progress.A dropped ask waits for its whole timeout.
DROP_LATESTThe 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#

The status of an actor. Created moves to Starting when the node is attached or restored, and to Running once preStart() returns. Saving, destroying or a Stop directive move a running actor to Stopping, and to Stopped once postStop() returns; restoring the node starts it again. A Restart directive runs postStop() and preStart() on the same object. A preStart() or postStop() that throws, or an Escalate directive, leaves the actor Failed. On the right, the node lifecycle events and what each does to the message loop.ACTORSTATUS, A STATEFLOW ON EVERY ACTORREFCreatedconstructedStartingpreStart() runsRunningreceive() per messageStoppingpostStop() runsStoppedthe loop has endedFailed(error)keeps the errorattach, restorepreStart() donesave, destroy or StoppostStop() donerestore againRestart: postStop(), then preStart()preStart() threwEscalate, or postStop() threwWHAT DRIVES THE LOOPAttaching or Restoringstart the loop; nothing if it runsSavingcancel the loop; mailbox and timers stayDestroyingclose the mailbox and cancel the loopStop directiveclose the mailbox from inside the loop
The actor's lifecycle is the node's lifecycle. Every status change is visible on status.
Node lifecycleWhat the actor does
Attaching, RestoringStarts the loop and runs preStart(). Starting is idempotent, so a running loop is left alone.
SavingCancels the loop and leaves the mailbox open, so Saving then Restoring resumes with the queued messages. Timers keep running.
DestroyingCloses 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#

What happens when receive() throws. The ask that carried the message, if any, fails with the same error. Then onFailure(message, error) picks a directive; by default it asks graph.actorSupervisorStrategy, which returns Resume. Resume goes on to the next message with the state the failed message left. Restart runs postStop() and preStart() on the same object, keeping its fields and mailbox. Stop closes the mailbox, so later sends fail and queued messages may never run. Escalate ends the loop with the status Failed and hands the error to the node scope.receive(message)throws an errorIts ask failsa caller waiting in ask()gets the same erroronFailure(message, error)override it in one actor, or setgraph.actorSupervisorStrategyfor every actor in a graph;the default returns ResumeResumethe next message runs; fields keepwhatever the failed message leftRestartpostStop(), then preStart() on thesame object, fields and mailboxStopmailbox closed: later sends fail andqueued messages may never runEscalatethe loop ends with Failed(error);the node scope's handler gets itThe directive is applied before the next messageis taken, so no message overtakes a failure.
A failed message fails its ask, then one directive decides what happens to the actor.

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)
DirectiveWhat happens
ResumeThe loop takes the next message. Fields keep whatever the failed message left in them.
RestartThe 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.
StopThe 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.
EscalateThe 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> callWhat 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.
valuesA 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) and Graph.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.attach returns false.

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#

A PersistentActorNode. Callers such as a scheduled tick or a Worker route call a transition, which is an Activity port. Each call locks and loads the state through the ActorStore node, checks that the current state is one the transition may start from, runs the transition code with its activities and stages, checks that the new state is one it may end in, and records the states before and after on the activity span. States and transitions are declared up front, so Hangar can draw them; BestBuds allows every transition from any state to any state today.CALLERSFormationTickweekly.wake(WeeklyWake(…))A Worker routeCircleLifecycles.answer(…)Every call is one message.The store decides whichcall goes first.PERSISTENTACTORNODE, A WORKFLOWtransition("wake", effect)an Activity port with a span1lock and load the state2check: state is in from3run execute(input, state)4check: new state is in to5record before and afterActorStore nodea child node of kind Store;its transact() serializes:a Mutex in WeeklyRuns, arow lock in Circle lifecycleActivities and stageschild nodes with ports,each with an Effect andits own spanA state outside from or to throws, and theactivity span records the failure.DECLARED UP FRONTCircle lifecycle statesabsentroundsprivate-picksresolvedwrappedrequeuedIts four messagesadvanceanswerpicksengageEach is allowed from any stateto any state today.
A 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:

  1. transact(input) on the store locks and loads the state.
  2. The current state must be in the transition's from set.
  3. The transition's code runs, calling activities and stages.
  4. The new state must be in its to set.
  5. 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.

ActorNodePersistentActorNode
OrderingIts in-memory mailboxWhatever its store's transact() locks
Where it can runOne processAnywhere the store reaches, including many Worker instances
StateFields and the actor's ObjectStoreLoaded by the store for each call
InputA sealed message typeNamed transitions with a typed input
Timersschedule and everyNone; a schedule or a route calls it
In HangarAn actor nodeAn 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's sys:get_state and of an Akka TestProbe: it reads the state through the mailbox.
  • Set Feature.Database to a test ObjectDatabase before testing an actor with state.
  • Drive the lifecycle directly with actor.transition(Lifecycle.Saving) and actor.transition(Lifecycle.Restoring).
  • Virtual time from runTest moves timers: advanceTimeBy fires a schedule without 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#

PatternHowWhere
DebounceA pending set and one timer per keyChatReadReceipts
BarrierAn ask that completes when it reaches the front of the mailboxChatOutbox.awaitIdle()
Work beside the actorLaunch the slow call and send its result back as a messageChatOutbox uploads
FacadeA provided interface whose methods askSecurityNode, CommandQueueActor
One actor per entityA key per entity id, created on first useactorKey("room/$id")
OutboxSave the intent before the effect and resend it after a restartChatOutbox with keepUnsent
Idempotent transitionLoad "already done" in the store and skip the workWeeklyFormation with formed(scheduleKey)
Replaceable timerKeep each handle in a map under your own keyTimers

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#

IdeaAkkaErlang/OTPReaktor today
Send without waitingtell (!)gen_server:cast, !send, trySend
Ask with a deadlineask with a timeout; the reply goes to a replyTo refgen_server:call, 5 seconds by defaultask, 30 seconds by default; askResult
Answer laterKeep replyTo and answer from a later messageReturn noreply and answer with gen_server:replyKeep the Reply and complete it from a later message
Result of slow workcontext.pipeToSelfA spawned worker reports to handle_infoLaunch a job in coroutineScope and send the result
Typed protocolBehavior[Command] with sealed traitsTuples, checked by convention and DialyzerActorKey<M> with a sealed interface
Hiding the protocolMessage adaptersAPI functions in the gen_server moduleA provided interface whose methods ask
Messages that arrive too earlyStashBufferSelective receiveMissing; keep them in a field until the actor is ready
OrderingPer sender and receiver pairPer sender and receiver pairOne first-in, first-out mailbox per actor

Failure and supervision#

IdeaAkkaErlang/OTPReaktor today
Default on failureAkka Typed stops the actorThe supervisor restarts the process as its child spec saysResume
RestartA new behavior with fresh stateA new process; init/1 runs againpostStop() then preStart() on the same object
Restart limitrestart.withLimit(maxNrOfRetries, withinTimeRange)Intensity and period: too many restarts in a window and the supervisor fails tooMissing
BackoffrestartWithBackoffNot in the standard supervisorMissing
SiblingsEach parent decides for its childrenone_for_one, one_for_all, rest_for_oneMissing; each actor is supervised alone
Supervision treeThe actor hierarchySupervisors of supervisors, with the error kernel at the topThe graph supervises its actors; child graphs nest, and failures do not climb them
Watching another actorcontext.watch and Terminatedmonitor, link and 'DOWN' messagesCollect its status flow; nothing is delivered automatically
Lifecycle hooksPreRestart and PostStop signalsinit/1 and terminate/2preStart() and postStop()

State and persistence#

IdeaAkkaErlang/OTPReaktor today
State machinesReturn a different behavior per stategen_statem with states, events, state timeouts and postponed eventsPersistentActorNode; in an ActorNode, a sealed state field
TimersTimerScheduler with keyed single and periodic timerserlang:send_after; gen_statem timeoutsschedule and every, with handles
Durable stateAkka Persistence: event sourcing, snapshots and durable stateETS, DETS and Mnesiastate<T>(name) in the actor's ObjectStore
RecoveryLoad the latest snapshot and replay the events after itinit/1 reloads what it needspreStart() reads the store; PersistentActorNode loads on every call
Exactly-once effectsDeduplicate by id; reliable deliveryIdempotent handlers by conventionIdempotent transitions such as formed(scheduleKey); an outbox

Scaling out#

Scaling out by key. Today every keyed actor lives in one graph in one process, and a facade picks the actor for an entity id. In the design, the same key names a Durable Object, so Cloudflare runs one single-threaded instance per key, each with its own storage and alarms. Akka Cluster Sharding, Orleans and Erlang process registries place actors by key in the same way.TODAY: KEYED ACTORS IN ONE GRAPHFacade: actorKey("room/$id")provides(key) creates it on first useroom/1mailboxroom/2mailboxroom/3mailboxAll in one process: placement costsnothing, and one machine is the limit.DESIGN: ONE DURABLE OBJECT PER KEYWorker: idFromName("room/$id")Cloudflare routes each call for a keyroom/1own storageand alarmsroom/2own storageand alarmsroom/3own storageand alarmsEach object is single-threaded, andthe platform picks its machine.THE SAME IDEA ELSEWHEREAkka Cluster Shardingentity id → shard → cluster nodeOrleans virtual actorsactivated on the first callErlang/OTPregistered names and pg groups
One actor per key scales by moving keys between machines. Reaktor does that inside one process today.
IdeaAkkaErlang/OTPReaktor today
Finding an actorThe Receptionist and a ServiceKeyRegistered names, global and pgActorKey lookups inside one graph
One actor per entity across machinesCluster Sharding, with passivation of idle entitiesProcess groups (pg), with sharding built by the applicationDesign: one Durable Object per key
Exactly one instanceCluster SingletonA global registrationDesign: one Durable Object name
Replicated state without an ownerDistributed Data, built on CRDTsRiak's CRDT library, riak_dtDesign: CRDTs
Pools of workersPool and group routersWorker poolsMissing; a facade over several keyed actors
DeliveryAt most once by default; Reliable Delivery adds acknowledgementsAt most once; acknowledgements by handIn 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:

  1. 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.
  2. 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 PersistentActorNode transitions, so any actor can restart without losing it.
  3. 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.
  4. 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 WeeklyFormation does with its schedule key.
  5. 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.
  6. 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.
  7. 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.
  8. 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#

ActorTypeWhat it owns
ChatOutbox (chat/outbox)ActorNodeEvery outgoing chat message: queueing, upload progress, posting, retries, discards and forwards
ChatReadReceipts (chat/read-receipts)ActorNodeThe chats with unsent read receipts, each flushed by a timer
SecurityNode (security/device)ActorNodeThe device's encryption state and keys, behind ReaktorSecurity
CommandQueueActor, ShellActorActorNodeThe Hangar workbench's command queue, and its selection, layout and environment
WeeklyFormation (circle-formation/weekly)PersistentActorNodeThe weekly Circle formation run
Circle lifecyclePersistentActorNodeA Circle's phases, locked per campaign row
Verification lifecyclePersistentActorNodeA user's document verification status
Account purge, database backupPersistentActorNodePurge 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 ObjectStore abstraction 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, ActorGraph or ActorRepository. 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, trySend or ask, 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 approachWhat goes wrongThe actor approach
Shared state guarded by locksEvery 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 modelEvents 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 finishesCallbacks 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 consumersUnder 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 frameworkA 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, as ChatOutbox does.
  • 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, ask first waits for room with no time limit.
  • Dropping mailboxes drop asks silently. With DROP_OLDEST or DROP_LATEST, a dropped ask waits for its whole timeout, and trySend reports 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, onFailure sees 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, so preStart() has to reset them.
  • After Escalate the 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 in postStop().
  • 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 PersistentActorNode transition 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 Escalate leaves 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 stableActorUuid and stableActorStoreName on ActorKey. Keep them stable across renames, because a changed key silently orphans an actor's store.
  • Actor keys carry no tenant. Adding a tenant to ActorKey would keep each tenant's actors apart by construction. The change is cheap now and expensive once actors span machines.
  • Narrow the from and to sets of BestBuds' PersistentActorNode transitions 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-backed ObjectStore.
  • Map actor timers to Durable Object alarms.
  • Generate handler surfaces for typed ask and send endpoints.

Where the code lives#

AreaFiles
Actor primitivereaktor-actor/src/commonMain/.../actor/ActorNode.kt
Durable state machinesreaktor-actor/src/commonMain/.../actor/PersistentActorNode.kt, on Workflow.kt and Stage.kt in reaktor-graph-runtime
Graph supervisionreaktor-actor/src/commonMain/.../actor/ActorNode.kt (Graph.actorSupervisorStrategy, kept in a graph attachment)
Stored actorsreaktor-db/src/commonMain/.../node/StoredActorNode.kt
Node scope and dispatcherreaktor-graph-runtime/.../core/node/Node.kt, reaktor-core/.../capabilities/ConcurrencyCapability.kt
Actor statereaktor-db/src/commonMain/.../core/ObjectState.kt
Concurrent node collectionreaktor-graph-port/src/commonMain/.../graph/PortGraph.kt
Durable Objects in the graphreaktor-cloudflare/src/jsMain/.../GraphIngress.kt (DurableObjectIngress)
BestBuds chatChatOutbox.kt and ChatNodes.kt (ChatReadReceipts) in bestbuds/modules/app/src/commonMain/.../features/messaging/
BestBuds durable lifecyclesWeeklyFormation.kt, and CirclesWorker.kt, VerificationLifecycle.kt, AccountPurgeWorker.kt and ArchiverWorker.kt under bestbuds/modules/app/src/jsMain/.../cloudflare/
Device securityreaktor-security/src/commonMain/.../SecurityNode.kt
Hangar workbenchhangar/core/src/commonMain/.../workbench/data/actors/
Testsreaktor-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:

Documentation and essays:

  • 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 SecurityNode implements.