How to Implement an Actor Model in TypeScript
Build actors with private state, a mailbox and message passing so shared mutable state becomes a queue of messages instead of a race.
On this page
Introduction
Most concurrency bugs come from two pieces of code touching the same state at the same time. The actor model removes the shared state: each actor owns its state privately and is the only thing that touches it, and actors communicate by sending messages that are processed one at a time from a mailbox. Because an actor processes exactly one message at a time, its state transitions are serialised, and you get correctness by construction instead of by locking. This tutorial builds a small, typed actor runtime in TypeScript.
The Actor Contract
An actor has a private state, a mailbox that holds incoming messages, and a single-threaded processing loop that takes one message at a time and returns a new state. Nobody outside the actor reads or writes its state; the only way to affect it is to send a message. This is the whole model, and it is what removes data races.
Messages are typed, which means the set of legal interactions is a discriminated union the compiler checks. An actor that only accepts Deposit and Withdraw cannot be made to do anything else, and a handler that forgets a message type fails to type-check. The type is the protocol.
type Message =
| { type: 'Deposit'; amount: number }
| { type: 'Withdraw'; amount: number; reply: (ok: boolean) => void }
| { type: 'GetBalance'; reply: (balance: number) => void };
interface AccountState { balance: number; }
function reduce(state: AccountState, msg: Message): AccountState {
switch (msg.type) {
case 'Deposit':
return { balance: state.balance + msg.amount };
case 'Withdraw': {
const ok = state.balance >= msg.amount;
msg.reply(ok);
return ok ? { balance: state.balance - msg.amount } : state;
}
case 'GetBalance':
msg.reply(state.balance);
return state;
}
}
The Mailbox and Serialised Processing
The mailbox is a queue, and the actor drains it one message at a time. Two messages never run concurrently inside one actor, so the reduce function can assume it has exclusive access to the state. Messages sent while the actor is busy are queued, not dropped, unless the mailbox is bounded and full, in which case the sender is told.
Because processing is serialised, the state can be mutated in place safely, or modelled as an immutable value returned from each handler. The immutable form is easier to test and to reason about: the handler is a pure function from (state, message) to state plus side effects, which is exactly the shape a unit test wants.
class Actor<S, M> {
private queue: M[] = [];
private running = false;
constructor(private state: S, private reduce: (s: S, m: M) => S) {}
send(msg: M): void {
this.queue.push(msg);
void this.drain(); // schedule if idle
}
private async drain(): Promise<void> {
if (this.running) return; // already draining
this.running = true;
try {
while (this.queue.length > 0) {
const msg = this.queue.shift()!;
this.state = this.reduce(this.state, msg); // exclusive access
}
} finally {
this.running = false;
}
}
}
Request-Reply with Promises
Fire-and-forget messages are easy; request-reply needs a way to return a result to the sender. The pattern is a message that carries a reply callback or a promise’s resolve function. The actor calls the reply when it processes the message, and the sender awaits it. The reply must be called even on failure, or the sender’s promise hangs forever.
Because replies are asynchronous, the sender must not assume ordering with its own subsequent messages. If a caller sends a Withdraw and then reads the balance, the read may be processed before the withdraw completes if it was sent on a different path. Model the operations that need ordering as a single message, or await the reply before sending the next.
function ask<S, M extends { reply: (v: T) => void }, T>(
actor: Actor<S, M>,
build: (reply: (v: T) => void) => M,
): Promise<T> {
return new Promise<T>((resolve) => msgs.push(build(resolve)));
}
// usage
const ok = await ask(account, (reply) => ({ type: 'Withdraw', amount: 50, reply }));
if (!ok) throw new Error('insufficient funds');
Supervision and Failure Isolation
An actor that throws while handling a message should not corrupt its state or stop the whole system. Catch the error inside the drain loop, decide whether the message is retryable, and either skip it, apply a compensation, or escalate to a supervisor. State should be updated only after the handler succeeds, or rolled back on failure.
Supervision is the actor model’s answer to fault tolerance: a parent watches its children and restarts them on failure. Implement it as a policy per actor, with a bounded restart count and backoff, so a permanently broken actor is quarantined instead of restart-looping forever and consuming resources.
private async drain(): Promise<void> {
if (this.running) return;
this.running = true;
while (this.queue.length > 0) {
const msg = this.queue.shift()!;
const snapshot = this.state; // for rollback on failure
try {
this.state = this.reduce(this.state, msg);
} catch (err) {
this.state = snapshot; // keep state consistent
this.onError?.(err, msg); // note/ escalate/ quarantine
}
}
this.running = false;
}
Where the Model Fits
Actors shine when a resource has a natural owner and a stream of updates: a session, a connection, a game room, a rate-limit bucket, a per-tenant quota. They are a poor fit for stateless request handling, where the overhead of a mailbox buys nothing, and for bulk data processing, where throughput matters more than isolation and a queue of workers is simpler.
In a single-threaded runtime the actor model is mostly about correctness under async interleaving rather than true parallelism. The serialised mailbox removes the interleaving that causes races. When you need parallelism as well, run actors on worker threads and send messages across the boundary, keeping the same one-message-at-a-time contract per actor.
# good fits for actors
session store one owner per session, serialised updates
connection registry one owner per connection, ordered events
rate-limit buckets per-key state, no locks
game/room state ordered messages per room
# poor fits
stateless HTTP handlers (no shared state to protect)
bulk ETL (throughput-bound, workers + queue is simpler)
Common Pitfalls and Conclusion
Do not let message handlers block the loop; a slow handler stalls the actor’s mailbox and every sender waiting on it. Keep handlers fast and offload blocking work. Do not expose the actor’s state for direct access, or you reintroduce the shared state you removed. Do not forget to always call the reply. And do not assume cross-actor message ordering; only order within one actor is guaranteed.
The actor model trades shared mutable state for message queues, and in exchange you get serialised state transitions and failures that are isolated to one actor. Define a typed message protocol, drain a mailbox one message at a time, support request-reply with promises, and supervise failures with bounded restarts. It is a small amount of machinery that makes a whole class of concurrency bugs impossible to write.
Sources: The Actor Model (Hewitt, Bishop, Steiger), Akka: Actors, Erlang: Processes.
FAQ
- Is the actor model the same as using a mutex?
- Both serialise access to state, but a mutex lets any code acquire the lock and must be used correctly everywhere, while an actor makes the state private and reachable only through its mailbox, so the serialisation is enforced by the design rather than by discipline.
- How do I get a result back from an actor?
- Encode a reply in the message, typically a promise resolve function, and have the actor call it when it processes the message. Always call the reply on both success and failure so the sender never hangs.
Report a problem with this articleOpens a pre-filled issue on GitHub.