Conceptcore
Actor model
Also called actors, actor-oriented programming, mailboxes, message passing concurrency, let it crash, supervision trees.
The actor model builds a concurrent program from actors that each own private state and a mailbox, handle one message at a time, and interact only by sending messages.
- Applies to
- core-languages
Idea
The actor model builds a concurrent program from actors: independent units that each have private state and a mailbox, and that interact only by sending messages to each other. An actor handles one message at a time. To handle it, an actor can change its own state, send messages to actors it knows, and create new actors. It cannot read or write the state of another actor. Carl Hewitt, Peter Bishop and Richard Steiger introduced the model in 1973 and claimed that all computation can be "defined in terms of one kind of behavior: sending messages to actors."1 The example below is a counter actor in Python. Four threads send it 4000 messages at the same time, and no lock protects the count:
import queue
import threading
class Actor:
def __init__(self):
self.mailbox = queue.Queue()
self.thread = threading.Thread(target=self._loop)
self.thread.start()
def send(self, message):
self.mailbox.put(message)
def _loop(self):
while (message := self.mailbox.get()) is not None:
self.receive(message)
def stop(self):
self.send(None)
self.thread.join()
class Counter(Actor):
def __init__(self):
self.count = 0 # private state: only the actor's own thread uses it
super().__init__()
def receive(self, message):
match message:
case ("add", n):
self.count += n
case ("get", reply_to):
reply_to.put(self.count)
counter = Counter()
clients = [threading.Thread(target=lambda: [counter.send(("add", 1)) for _ in range(1000)]) for _ in range(4)]
for c in clients:
c.start()
for c in clients:
c.join()
reply = queue.Queue()
counter.send(("get", reply))
print("count:", reply.get())
counter.stop()
count: 4000
The count is correct because only the actor's own thread reads and writes self.count. The mailbox is the only shared object, and it is a thread-safe queue. The clients do not call a method on the counter. They put a message in its mailbox and continue. To read the count, a client sends a get message with a place for the answer, and waits for the reply.
How it works
Mailboxes and asynchronous sends. Each actor has an address and a mailbox. A send puts a message in the mailbox of the receiver and returns at once. The sender does not wait for the receiver to handle the message, and the receiver handles its messages one after another. The order of messages between one sender and one receiver is kept in most implementations, but there is no order between messages from different senders.
The three actions. The Akka documentation lists what an actor can do when it receives a message: "send a finite number of messages to Actors it knows", "create a finite number of new Actors" and "designate the behavior to be applied to the next message".2 The last action is how an actor changes state. In Erlang, an actor is a function that loops with its state as an argument, and it calls itself with new state after each message. In object-oriented libraries, an actor is an object whose fields only its own handler can change.
Isolation. Actors share nothing. Joe Armstrong, a designer of Erlang, wrote that processes "should share no data, and only communicate by message passing", because as soon as two processes share memory, "a software error in one of the processes will corrupt the shared resource."3 Erlang copies each message into the heap of the receiver. Languages without this guarantee rely on a rule: send only immutable data, or data that the sender will not touch again. Rust checks the rule with the Send trait. Python and Java do not check it, and the wrong block in the Python file shows a message that changes after the send.
Addresses and location. An actor knows other actors only by their addresses. An address can come from the creation of the actor, from a message, or from a registry of names. Because all interaction is by message, an address can refer to an actor on another machine with no change to the code that sends to it. Erlang and Akka use this to spread a system over many machines.
Supervision. Actor systems handle failure by structure. A supervisor is an actor that starts other actors, watches them, and restarts them when they crash. Armstrong called the style "let it crash": "in the event of an error, then the program should just crash", and another process fixes the problem.3 A crashed actor loses only its own state, which a restart rebuilds from a known start. The Python file shows a supervisor that restarts a worker after bad input.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Library | |
| C | Absent | |
| C# | Library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | As JavaScript; worker threads in Node.js and web workers in browsers are actors that communicate by copied messages. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Library | Kotlinx.coroutines has channels and an actor builder, and Akka and Pekko run on the JVM; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL has transactions and locks for concurrency, not actors. |
| Bash | Idiom | A background process that reads commands from a named pipe and keeps its own variables acts as an actor. |
| PowerShell | Absent | Jobs and runspaces run script blocks in parallel, but have no mailboxes; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no concurrency; scripts in the page use web workers. |
| CSS | Does not apply | CSS has no concurrency. |
| Regular expressions | Does not apply | Regular expressions have no concurrency. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | a thread with a queue.Queue mailbox |
| JavaScript | stdlib | worker threads and web workers with postMessage |
| TypeScript | stdlib | as JavaScript |
| Java | library | BlockingQueue and virtual threads; Akka, Pekko |
| Kotlin | library | the coroutines actor builder; Akka, Pekko |
| C# | library | System.Threading.Channels; Orleans, Akka.NET |
| Go | idiom | a goroutine that owns its state and reads a channel |
| Rust | idiom | a thread with an mpsc channel; Send checks messages; Actix, Ractor |
| C | absent | threads with a hand-made mailbox |
| C++ | idiom | std::jthread, a queue of std::variant; CAF |
| Bash | idiom | a background process that reads a named pipe |
| PowerShell | absent | jobs and runspaces, no mailboxes |
| SQL | n/a | transactions, not actors |
| Regex | n/a | no concurrency |
| HTML | n/a | no concurrency |
| CSS | n/a | no concurrency |
No core language has actors in its syntax. The languages built on the model are Erlang and Elixir, which run on the BEAM virtual machine, and Pony. The Erlang documentation says that its processes "are lightweight (grow and shrink dynamically) with a small memory footprint, fast to create and terminate, and the scheduling overhead is low."4 A BEAM system can run millions of them, each with its own heap and garbage collection.
In the core languages, an actor is a pattern: a thread, goroutine or task with private state and a queue. The examples on this page all have the same shape: a bank account that many clients deposit into at the same time, with the balance owned by one thread and read with a reply message. JavaScript workers are the closest to Erlang processes in isolation, because each has its own heap and the runtime copies each message. Rust is the only core language whose compiler rejects a message that would share memory unsafely, as the second block of the Rust file shows. Go's goroutines and channels come from a different model, communicating sequential processes, in which channels are the named things and not the processes. See channels.
import queue
import threading
def spawn(behavior, state, supervisor):
mailbox = queue.Queue()
def loop():
s = state
while (msg := mailbox.get()) is not None:
if msg[0] == "get":
msg[1].put(s)
continue
try:
s = behavior(s, msg[1])
except Exception as e:
supervisor.put(("crashed", repr(e)))
return
threading.Thread(target=loop, daemon=True).start()
return mailbox
def add(total, text):
return total + int(text)
events = queue.Queue()
worker = spawn(add, 0, events)
for text in ["1", "2", "x"]:
worker.put(("num", text))
kind, reason = events.get() # the supervisor waits for the crash
print(kind, reason)
worker = spawn(add, 0, events) # restart with fresh state
print("restarted with fresh state")
worker.put(("num", "3"))
reply = queue.Queue()
worker.put(("get", reply))
print("total:", reply.get())
crashed ValueError("invalid literal for int() with base 10: 'x'")
restarted with fresh state
total: 3
This code runs but gives a wrong answer on purpose.
import queue
import threading
inbox = queue.Queue()
seen = []
def actor():
seen.append(list(inbox.get()))
order = ["tea"]
inbox.put(order) # sends a reference, not a copy
order.append("cake") # the sender changes the message after it was sent
t = threading.Thread(target=actor)
t.start()
t.join()
print(seen)
[['tea', 'cake']]
- Verdict: idiom. Python has no actors in the standard library, but a thread with a
queue.Queueas its mailbox is an actor. The supervisor in the first block does not try to handle the bad input. It lets the worker crash, and starts a new one with clean state, which is the Erlang way. - In the wrong block, the message is a list, and the queue passes a reference to it. The sender changes the list after the send, and the actor sees the change. Actors must not share mutable data. Send immutable values, such as tuples and frozen data classes, or send a copy.
#include <condition_variable>
#include <future>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <variant>
#include <vector>
struct Deposit { int amount; };
struct Withdraw { int amount; };
struct Balance { std::promise<int> reply; };
struct Stop {};
using Msg = std::variant<Deposit, Withdraw, Balance, Stop>;
class Account {
public:
Account() : thread_([this] { loop(); }) {}
~Account() { send(Stop{}); }
void send(Msg m) {
{ std::lock_guard g(mu_); box_.push(std::move(m)); }
cv_.notify_one();
}
private:
void loop() {
for (;;) {
Msg m;
{
std::unique_lock g(mu_);
cv_.wait(g, [this] { return !box_.empty(); });
m = std::move(box_.front());
box_.pop();
}
if (std::holds_alternative<Stop>(m)) return;
if (auto* d = std::get_if<Deposit>(&m)) balance_ += d->amount;
if (auto* w = std::get_if<Withdraw>(&m); w && w->amount <= balance_) balance_ -= w->amount;
if (auto* b = std::get_if<Balance>(&m)) b->reply.set_value(balance_);
}
}
int balance_ = 0; // only the actor's thread uses this member
std::mutex mu_;
std::condition_variable cv_;
std::queue<Msg> box_;
std::jthread thread_; // declared last, so it starts after the other members exist
};
int main() {
Account account;
{
std::vector<std::jthread> clients;
for (int i = 0; i < 4; i++)
clients.emplace_back([&] { for (int j = 0; j < 25; j++) account.send(Deposit{10}); });
}
account.send(Withdraw{1});
std::promise<int> p;
auto f = p.get_future();
account.send(Balance{std::move(p)});
std::cout << "balance " << f.get() << "\n";
}
balance 999
- Verdict: idiom. The standard library has threads, mutexes, condition variables,
std::variantfor messages andstd::promisefor replies, but no actor type. The C++ Actor Framework (CAF) is a full actor library. - The order of the members matters.
thread_startsloopas soon as it is built, so it must be the last member. The destructor sendsStop, and then the destructor ofstd::jthreadjoins the thread.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
sealed interface Msg permits Deposit, Withdraw, Balance, Stop {}
record Deposit(int amount) implements Msg {}
record Withdraw(int amount) implements Msg {}
record Balance(CompletableFuture<Integer> reply) implements Msg {}
record Stop() implements Msg {}
static class Account implements Runnable {
final BlockingQueue<Msg> mailbox = new LinkedBlockingQueue<>();
private int balance; // only the actor's thread uses this field
public void run() {
try {
while (true) {
switch (mailbox.take()) {
case Deposit d -> balance += d.amount();
case Withdraw w -> {
if (w.amount() <= balance) balance -= w.amount();
}
case Balance b -> b.reply().complete(balance);
case Stop s -> {
return;
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws Exception {
Account account = new Account();
Thread actor = Thread.ofVirtual().start(account);
try (var clients = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100; i++) {
clients.submit(() -> account.mailbox.add(new Deposit(10)));
}
}
account.mailbox.add(new Withdraw(1));
var reply = new CompletableFuture<Integer>();
account.mailbox.add(new Balance(reply));
System.out.println("balance " + reply.get());
account.mailbox.add(new Stop());
actor.join();
}
}
balance 999
- Verdict: library. The JDK has the parts: threads,
BlockingQueuefor a mailbox, records and sealed interfaces for messages, andCompletableFuturefor replies. Akka and its fork Apache Pekko give full actor systems with supervision and distribution. - One hundred tasks deposit at the same time, but no lock protects
balance. The mailbox puts the messages in one line, and one thread handles them.
#include <pthread.h>
#include <stdio.h>
enum op { DEPOSIT, WITHDRAW, STOP };
struct msg { enum op op; int amount; };
#define CAP 256
static struct msg box[CAP];
static int head, tail;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t ready = PTHREAD_COND_INITIALIZER;
static void post(struct msg m)
{
pthread_mutex_lock(&lock);
box[tail++ % CAP] = m;
pthread_cond_signal(&ready);
pthread_mutex_unlock(&lock);
}
static struct msg take(void)
{
pthread_mutex_lock(&lock);
while (head == tail)
pthread_cond_wait(&ready, &lock);
struct msg m = box[head++ % CAP];
pthread_mutex_unlock(&lock);
return m;
}
static void *account(void *arg)
{
int balance = 0; /* only this thread uses balance */
for (;;) {
struct msg m = take();
if (m.op == DEPOSIT)
balance += m.amount;
else if (m.op == WITHDRAW && m.amount <= balance)
balance -= m.amount;
else if (m.op == STOP)
break;
}
*(int *)arg = balance;
return NULL;
}
static void *client(void *arg)
{
(void)arg;
for (int i = 0; i < 25; i++)
post((struct msg){ DEPOSIT, 10 });
return NULL;
}
int main(void)
{
int result;
pthread_t actor, clients[4];
pthread_create(&actor, NULL, account, &result);
for (int i = 0; i < 4; i++)
pthread_create(&clients[i], NULL, client, NULL);
for (int i = 0; i < 4; i++)
pthread_join(clients[i], NULL);
post((struct msg){ WITHDRAW, 1 });
post((struct msg){ STOP, 0 });
pthread_join(actor, NULL);
printf("balance %d\n", result);
return 0;
}
balance 999
- Verdict: absent. C has threads in
<threads.h>and POSIX threads, but no message queues between them. The mailbox here is a ring buffer with a mutex and a condition variable. The mutex is inside the mailbox only. The state of the actor needs no lock, because one thread owns it. The ring buffer does not check for overflow, so it is safe only while fewer than 256 messages wait at once, as in this example.
using System.Threading.Channels;
var account = new Account();
await Parallel.ForAsync(0, 100, async (i, ct) => await account.Send(new Deposit(10)));
await account.Send(new Withdraw(1));
Console.WriteLine($"balance {await account.Ask()}");
abstract record Msg;
record Deposit(int Amount) : Msg;
record Withdraw(int Amount) : Msg;
record GetBalance(TaskCompletionSource<int> Reply) : Msg;
class Account
{
readonly Channel<Msg> mailbox = Channel.CreateUnbounded<Msg>(new UnboundedChannelOptions { SingleReader = true });
int balance; // only the loop uses this field
public Account() => Task.Run(Loop);
public ValueTask Send(Msg m) => mailbox.Writer.WriteAsync(m);
public async Task<int> Ask()
{
var reply = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
await Send(new GetBalance(reply));
return await reply.Task;
}
async Task Loop()
{
await foreach (var m in mailbox.Reader.ReadAllAsync())
{
switch (m)
{
case Deposit d: balance += d.Amount; break;
case Withdraw w when w.Amount <= balance: balance -= w.Amount; break;
case GetBalance g: g.Reply.SetResult(balance); break;
}
}
}
}
balance 999
- Verdict: library.
System.Threading.Channelsgives a mailbox, and one task that reads it is an actor. Microsoft Orleans gives virtual actors, called grains, that the runtime creates, places on servers and restores on demand. Akka.NET ports Akka to .NET.
import { Worker, isMainThread, parentPort } from "node:worker_threads";
if (isMainThread) {
const account = new Worker(new URL(import.meta.url));
account.on("message", (msg) => {
console.log(msg);
if (msg.startsWith("balance")) account.terminate();
});
const order = { op: "deposit", amount: 100 };
account.postMessage(order);
order.amount = 1_000_000; // changes only the sender's copy
account.postMessage({ op: "withdraw", amount: 30 });
account.postMessage({ op: "withdraw", amount: 500 });
account.postMessage({ op: "balance" });
} else {
let balance = 0; // only this worker can reach this variable
parentPort.on("message", ({ op, amount }) => {
if (op === "deposit") balance += amount;
else if (op === "withdraw") {
if (amount > balance) parentPort.postMessage(`refused withdraw ${amount}`);
else balance -= amount;
} else parentPort.postMessage(`balance ${balance}`);
});
}
refused withdraw 500
balance 70
- Verdict: stdlib. A worker thread is an actor: it has its own heap and event loop, and the only way to reach it is
postMessage. Messages are copied with the structured clone algorithm, so the change toorderafter the send does not reach the worker.
package main
import (
"fmt"
"sync"
)
type msg struct {
op string
amount int
reply chan int
}
func account(mailbox <-chan msg) {
balance := 0 // only this goroutine uses balance
for m := range mailbox {
switch m.op {
case "deposit":
balance += m.amount
case "withdraw":
if m.amount <= balance {
balance -= m.amount
}
case "balance":
m.reply <- balance
}
}
}
func main() {
mailbox := make(chan msg, 16)
go account(mailbox)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mailbox <- msg{op: "deposit", amount: 10}
}()
}
wg.Wait()
mailbox <- msg{op: "withdraw", amount: 1}
reply := make(chan int)
mailbox <- msg{op: "balance", reply: reply}
fmt.Println("balance", <-reply)
close(mailbox)
}
balance 999
- Verdict: idiom. A goroutine that owns its state and reads a channel is an actor. Go's model is CSP, not actors: channels are values that any goroutine can use, and an unbuffered send waits for the receiver. A buffered channel gives a mailbox. Go does not stop goroutines from sharing memory, so the rule that only the actor uses
balanceis a convention.
use std::sync::mpsc::{channel, Sender};
use std::thread;
enum Msg {
Deposit(u32),
Withdraw(u32),
Balance(Sender<u32>),
}
fn spawn_account() -> (Sender<Msg>, thread::JoinHandle<()>) {
let (tx, rx) = channel();
let handle = thread::spawn(move || {
let mut balance = 0;
for msg in rx {
match msg {
Msg::Deposit(n) => balance += n,
Msg::Withdraw(n) if n <= balance => balance -= n,
Msg::Withdraw(_) => {}
Msg::Balance(reply) => reply.send(balance).unwrap(),
}
}
});
(tx, handle)
}
fn main() {
let (account, handle) = spawn_account();
let clients: Vec<_> = (0..4)
.map(|_| {
let account = account.clone();
thread::spawn(move || {
for _ in 0..25 {
account.send(Msg::Deposit(10)).unwrap();
}
})
})
.collect();
for c in clients {
c.join().unwrap();
}
account.send(Msg::Withdraw(1)).unwrap();
let (reply_tx, reply_rx) = channel();
account.send(Msg::Balance(reply_tx)).unwrap();
println!("balance {}", reply_rx.recv().unwrap());
drop(account);
handle.join().unwrap();
}
balance 999
This code does not compile, on purpose.
use std::rc::Rc;
use std::sync::mpsc::channel;
use std::thread;
fn main() {
let (tx, rx) = channel::<Rc<Vec<i32>>>();
thread::spawn(move || {
let shared = rx.recv().unwrap();
println!("{}", shared.len());
});
tx.send(Rc::new(vec![1, 2, 3])).unwrap();
}
- Verdict: idiom. The standard library has threads and channels but no actor type. The type system enforces the main rule of actors: a message must be
Send, so a value that would let two threads share memory without synchronization cannot be sent. The second block fails with error E0277, becauseRcis notSend. Crates such as Actix, Ractor and Kameo give actor systems on top of async runtimes. - When the last
Senderis dropped, theforloop in the actor ends, and the thread returns. Thedrop(account)inmainstops the actor.
Variations and related ideas
- CSP. In communicating sequential processes, processes send to channels, not to each other, and a send can wait until the receiver is ready. Go and Clojure's core.async use it. See channels.
- Active objects. An object whose method calls are turned into messages to its own thread, and whose results come back as futures. See futures.
- Virtual actors. In Orleans, actors always exist in concept. The runtime creates one when a message arrives and removes it when it is idle, and it stores its state.
- Event loops. Each actor runs a small event loop over its mailbox. See event-driven programming.
- Object-oriented programming. Alan Kay's idea of objects that send messages is close to actors, and Hewitt cited Smalltalk as an influence. See object-oriented programming.
- Message queues and microservices. Services that interact through a broker such as Kafka or RabbitMQ apply the same rules at the scale of a network.
Pitfalls
- Shared mutable messages. Sending a reference to mutable data breaks isolation. The wrong block in the Python file shows a message that the sender changes after the send.
- Deadlock by request and reply. Actor A sends a request to B and waits for the reply, while B sends a request to A and waits. Neither handles its mailbox. Avoid blocking waits inside handlers, or use timeouts. See deadlock.
- Unbounded mailboxes. A fast sender can fill the mailbox of a slow actor until memory runs out. Use bounded mailboxes and back-pressure, or drop messages on purpose.
- Lost messages. A message to an actor that has crashed or stopped is lost, and the sender is not told. Use replies, timeouts and monitors when delivery matters.
- A single actor as a bottleneck. All work for one actor runs on one thread. A popular actor limits the throughput of the whole system. Split its state over many actors.
- Hidden ordering assumptions. Messages from different senders arrive in no fixed order. A protocol that needs an order must enforce it with replies or sequence numbers.
Cost
A send costs a queue operation and, where messages are copied, a copy of the data. Erlang processes start with a few hundred words of memory, so a system can create one for each connection or request. Actors on threads cost a thread each, and libraries such as Akka run many actors on a small pool of threads, with each actor scheduled only when its mailbox has messages. An actor removes the cost of locks from its own state, but the mailbox itself needs synchronization, and an exchange of a request and a reply costs at least two queue operations and two thread wakeups. The model gains most when the state is naturally split among many actors, so that the work spreads over all cores without contention.
History
Carl Hewitt, Peter Bishop and Richard Steiger proposed actors at the International Joint Conference on Artificial Intelligence in 1973, as a single concept for the PLANNER language project at MIT.1 Irene Greif gave the model an operational semantics in 1975, and Gul Agha's thesis of 1985 developed it as a basis for concurrent programming. Joe Armstrong, Robert Virding and Mike Williams built Erlang at Ericsson from 1986 for telephone switches, with isolated processes, messages and supervision, and Ericsson released it as open source in 1998. Armstrong's thesis of 2003 described the design as concurrency oriented programming.3 Scala included an actor library from 2006, Akka followed in 2009, and Microsoft Research released Orleans in 2015. Elixir brought a new syntax to the BEAM in 2012.
References
- A Universal Modular ACTOR Formalism for Artificial Intelligence, Carl Hewitt, Peter Bishop and Richard Steiger, IJCAI 1973, introduction
- What is an Actor?, Akka documentation, What is an Actor?
- Making reliable distributed systems in the presence of software errors, Joe Armstrong, PhD thesis, 2003, 2.4 Concurrency oriented programming; 4.4 Let it crash
- Processes, Erlang System Documentation, Processes
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag K75AMM Edit this page History Report an error Markdown