Actor Model
Actors, mailboxes, and message passing.
What is an actor?
An actor is an isolated state machine with a mailbox. Each actor processes one handler at a time, including across suspension. Actors do not share mutable state; callers use typed actor handles to send requests or submit messages.
The compiler checks which values may cross that boundary, so mutable state stays with one actor instead of being protected by locks shared among callers. Read Actor Isolation and Message Passing for the boundary model in plain language.
Choose an actor's authority
Isolation gives each actor private state. To also check which services its code can acquire, use authority confinement: #[confined] asks the compiler to verify that boundary transitively.
Defining actors
Actors are declared with the actor keyword. Fields hold the actor's private state:
- Use
var, with a default, for fields a handler mutates, andletfor fields set once at spawn. - Refer to state by bare name; there is no
self. - Declare message handlers with
receive fn. Shared helper logic lives in top-level free functions. - Use
spawn Counterto start an instance with its default field values, orspawn Counter { count: 10 }to supply initial state.
fn validate(n: i64) -> bool {
n >= 0
}
actor Counter {
var count: i64 = 0;
receive fn increment(n: i64) {
if validate(n) { count = count + n; }
}
receive fn get_count() -> i64 {
count
}
}Actors can also declare a trait bound, allowing polymorphic behaviour:
trait Pingable {
fn label(p: Self) -> string;
}
actor Pinger: Pingable {
receive fn ping() -> string {
"pong"
}
}Messaging patterns
Named actors expose receive fn methods as direct method calls — no explicit message enums are needed. Every ordinary handler call waits for completion and reports its outcome:
- A handler without a return annotation replies with
Result<(), ActorError<E, Req>>. - A handler returning
Rreplies withResult<R, ActorError<E, Req>>. Match the reply, propagate it with?, or useexpectwhere failure should stop the caller. - Use
let task = fork actor.method(...)to start the call concurrently, thenawait taskfor its result.
In ActorError<E, Req>, E is the handler's declared fails type and Req is the type of an unaccepted request returned to the caller. Each is Never when that outcome cannot carry a value.
actor Counter {
var count: i64 = 0;
receive fn increment(n: i64) {
count = count + n;
}
receive fn get_count() -> i64 {
count
}
}
fn main() {
let c = spawn Counter { count: 0 };
c.increment(10).expect("actor stopped"); // waits for completion
let n = c.get_count(); // request-reply: Result<i64, ActorError>
match n {
.Ok(v) => println(v),
.Err(_) => println("ask failed"),
}
}Message values must satisfy Send, which the compiler derives and checks. Ordinary data crosses as an independent logical snapshot, so the sender may keep using its value. A sendable affine resource instead transfers its sole owner and cannot be reused by the sender. To pass an actor handle to another actor, pass its actor type T and call its handlers. The ownership guide explains the difference between ordinary and affine values.
actor Sink {
receive fn take(message: i64) {
println(message);
}
}
fn forward(message: i64, target: Sink) {
target.take(message).expect("actor stopped"); // waits until the target handles the message
}Lambda actors
A lambda actor is a lightweight, inline actor written as actor |params| { body }. It handles a single message type, captures variables from the enclosing scope, and is called the same way as a named actor.
fn main() {
let factor = 3;
let multiplier = actor |x: i64| -> i64 {
x * factor
};
println(multiplier(7).expect("actor stopped")); // 21
stop(multiplier);
stopped(multiplier);
}Multiplexed messaging
Hew provides two built-in concurrency expressions for coordinating multiple asynchronous operations: select and await fork (...). These are expressions — they produce values — and integrate with Hew's structured concurrency model.
actor StockApi {
receive fn get_price(sym: string) -> i64 { 100 }
}
actor PriceCache {
receive fn lookup(sym: string) -> i64 { 99 }
}
fn main() {
let stock_api = spawn StockApi;
let cache = spawn PriceCache;
let default_price: i64 = 0;
// select — first to reply wins, with pattern binding
let result = select {
price from stock_api.get_price("AAPL") => price handle e { default_price },
cached from cache.lookup("AAPL") => cached handle e { default_price },
after 5s => default_price,
};
println(result);
}actor Db {
receive fn get_users() -> i64 { 1 }
receive fn get_posts() -> i64 { 2 }
}
fn main() {
let db = spawn Db;
// Start both calls and collect their results in a tuple
let (users, posts) = await fork (
db.get_users(),
db.get_posts(),
);
println(users.expect("database actor stopped"));
println(posts.expect("database actor stopped"));
}Actor generators
A receive gen fn handler produces a stream. Its return annotation names the yielded item type. Consume it with an ordinary for loop; each pull waits for the producer automatically.
actor Counter {
receive gen fn count_up() -> i64 {
yield 0;
yield 1;
yield 2;
}
}
fn main() {
let counter = spawn Counter;
for value in counter.count_up() {
println(value);
}
}Task<T> and structured concurrency
A Task<T> represents a concurrent computation within an actor that will produce a value of type T. Tasks are cooperatively scheduled on the actor's single logical thread — no data races on actor state.
A scope block creates a structured-concurrency boundary inside an actor handler. Each let name = fork fn(); starts the expression as a child task bound to name : Task<T>. Inside the scope, let x = await name; suspends the handler until that task finishes and binds the result to x. The scope joins every child before it returns, so no task outlives the block.
The structured concurrency guide explains task ownership, deadlines, cooperative cancellation, and how task lifetime differs from actor lifetime.
fn fetch_first() -> i64 { 100 }
fn fetch_second() -> i64 { 200 }
actor Fetcher {
receive fn fetch_pair() -> i64 {
var first_val = 0;
var second_val = 0;
scope {
let first = fork fetch_first();
let second = fork fetch_second();
// await is a statement expression — bind results to new lets,
// then store into outer vars
let f = await first;
let s = await second;
first_val = f;
second_val = s;
};
first_val + second_val
}
}Cooperative cancellation
Concurrency in Hew is cooperative: a long-running computation yields to the scheduler at loop headers and call sites (the compiler inserts cooperate points), so other tasks and actors keep making progress. Cancellation follows the structure of the scope, so you do not manage cancel flags by hand:
- Child failure cancels sibling tasks in the same scope.
- A scope never returns until every child has finished or been cancelled.
cooperatepoints (inserted automatically) are where cancellation takes effect.
Actor lifecycle
spawn constructs an actor and its mailbox. A handler call waits for that turn, not for the actor's entire lifetime. Use stop(actor) to request graceful shutdown and stopped(actor) to wait for terminal hooks, state cleanup, and owned resource release. terminate(actor) requests cancellation.
#[on(start)]runs after spawn and after a supervised restart.#[on(stop)]runs during graceful shutdown.#[on(crash)]can inspect a supervised failure and request restart or give up.
See Actor Lifecycle and Supervision for the complete source-level path and the distinction between stable supervised roles and actor incarnations. Runtime scheduler states are implementation detail, not a synchronization API.
Lifecycle hooks
Hooks are plain fns with no parameters, marked with an #[on(...)] attribute. Fields are in scope by bare name.
actor Counter {
var value: i64 = 0;
#[on(start)] fn boot() {
println(f"Counter started at {value}");
value += 10;
}
#[on(stop)] fn done() {
println("Counter stopping");
}
receive fn tick() {
value += 1;
println(value);
}
}Supervision
A supervisor owns child actors and restarts them when they fail. Its strategy (one_for_one, one_for_all, or rest_for_one) decides which children restart, and its restart budget escalates repeated failures to the parent supervisor.
The supervision guide covers declaring supervisors, restart classifications, reaching supervised children by name, and nested supervisor trees.
Backpressure
An actor without a mailbox declaration has unbounded capacity. Declare a bound when the service needs an explicit admission limit; mailbox 1024; waits for space by default.
A bounded declaration can choose what happens to one-way submissions when the mailbox is full:
- block: Sender waits (cancellable) until space is available
- drop_new: The new message is discarded
- drop_old: The oldest message is evicted to make room
- fail: An error is returned to the sender
- coalesce(key): Replaces an existing message with the same key
Completion calls and stream starts wait for space; they are never discarded or superseded. The backpressure comparison shows these policies in a complete example.