Actor Model Pattern: Concurrency Without Shared State
Isolate state in actors that communicate only via messages. Each actor processes one message at a time, eliminating shared-state concurrency bugs by design.
Overview
Everyone who’s written threaded code knows the drill: shared state plus locks equals a bug waiting to happen. Miss a lock somewhere, get a race condition. Grab two locks in the wrong order, get a deadlock. The Actor Model sidesteps the whole problem by not sharing anything — each actor keeps its own private state, talks to the others only by passing messages, and handles those messages one at a time. Nothing shared means nothing to lock.
When to Use
- Your mutable state gets hammered by concurrent threads and locks keep biting you
- Fault tolerance matters: one actor crashing shouldn’t take the rest down
- The domain already looks like independent entities passing messages — chat users, devices, orders
- Location transparency pays off: the same actor code can run on one box or a fleet
Skip it for simple CRUD or stateless parallel work — actors add mailbox and serialization overhead that a thread pool or async/await handles more cheaply. And if your domain genuinely needs shared mutable state (a game loop’s physics world, a cache), actors force it into message-passing awkwardness where a lock would be honest.
Solution
Python (asyncio + message passing)
import asyncio
class Actor:
def __init__(self, name):
self.name = name
self.inbox = asyncio.Queue(maxsize=100) # bounded mailbox: senders fail or block when full
self.state = {}
async def run(self):
while True:
message = await self.inbox.get()
if message.get("type") == "stop":
print(f"[{self.name}] Stopping")
break
await self.handle(message)
async def handle(self, message):
msg_type = message.get("type")
if msg_type == "deposit":
amount = message["amount"]
self.state["balance"] = self.state.get("balance", 0) + amount
print(f"[{self.name}] Balance: {self.state['balance']}")
elif msg_type == "withdraw":
amount = message["amount"]
if self.state.get("balance", 0) >= amount:
self.state["balance"] -= amount
print(f"[{self.name}] Withdrew {amount}, balance: {self.state['balance']}")
else:
print(f"[{self.name}] Insufficient funds")
def send(self, message):
self.inbox.put_nowait(message)
async def main():
account = Actor("account-1")
task = asyncio.create_task(account.run())
# Send messages: no locks needed, actor processes one at a time
account.send({"type": "deposit", "amount": 100})
account.send({"type": "deposit", "amount": 50})
account.send({"type": "withdraw", "amount": 30})
account.send({"type": "withdraw", "amount": 200}) # Insufficient
account.send({"type": "stop"})
await task
asyncio.run(main())
JavaScript (worker threads as actors)
import { Worker, isMainThread, parentPort } from "worker_threads";
import { fileURLToPath } from "url";
// actor.js — runs in a Worker thread with isolated state
if (!isMainThread) {
const state = { balance: 0 };
parentPort.on("message", (message) => {
if (message.type === "stop") {
parentPort.close();
return;
}
if (message.type === "deposit") {
state.balance += message.amount;
parentPort.postMessage({
type: "result",
balance: state.balance,
});
} else if (message.type === "withdraw") {
if (state.balance >= message.amount) {
state.balance -= message.amount;
parentPort.postMessage({
type: "result",
balance: state.balance,
});
} else {
parentPort.postMessage({
type: "error",
message: "Insufficient funds",
});
}
}
});
}
// main.js
if (isMainThread) {
const __filename = fileURLToPath(import.meta.url);
const actor = new Worker(__filename);
actor.on("message", (msg) => {
if (msg.type === "result") {
console.log(`Balance: ${msg.balance}`);
} else if (msg.type === "error") {
console.log(`Error: ${msg.message}`);
}
});
// Send messages: no locks needed, actor processes one at a time
actor.postMessage({ type: "deposit", amount: 100 });
actor.postMessage({ type: "deposit", amount: 50 });
actor.postMessage({ type: "withdraw", amount: 30 });
actor.postMessage({ type: "withdraw", amount: 200 }); // Insufficient
actor.postMessage({ type: "stop" });
}
Java (Akka-style actor)
import java.util.concurrent.*;
public class ActorModelExample {
// Actor base: processes messages from a single-threaded queue
static abstract class Actor {
private final BlockingQueue<Object> mailbox = new LinkedBlockingQueue<>(1000); // bounded mailbox
private final String name;
private volatile boolean running = true;
public Actor(String name) {
this.name = name;
}
public void start() {
new Thread(() -> {
while (running) {
try {
Object message = mailbox.take();
if (message instanceof StopSignal) {
running = false;
break;
}
onMessage(message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
System.out.println("[" + name + "] Stopped");
}, "actor-" + name).start();
}
public void tell(Object message) {
mailbox.offer(message);
}
protected abstract void onMessage(Object message);
}
// Bank account actor with private state
static class AccountActor extends Actor {
private int balance = 0;
public AccountActor(String name) {
super(name);
}
@Override
protected void onMessage(Object message) {
if (message instanceof Deposit dep) {
balance += dep.amount();
System.out.println("[account] Balance: " + balance);
} else if (message instanceof Withdraw w) {
if (balance >= w.amount()) {
balance -= w.amount();
System.out.println("[account] Withdrew " + w.amount() + ", balance: " + balance);
} else {
System.out.println("[account] Insufficient funds");
}
}
}
}
record Deposit(int amount) {}
record Withdraw(int amount) {}
record StopSignal() {}
public static void main(String[] args) throws Exception {
AccountActor account = new AccountActor("account-1");
account.start();
// Send messages: no locks needed, actor processes one at a time
account.tell(new Deposit(100));
account.tell(new Deposit(50));
account.tell(new Withdraw(30));
account.tell(new Withdraw(200)); // Insufficient
Thread.sleep(100);
account.tell(new StopSignal());
}
}
Explanation
An actor boils down to three things:
- Private state — only the actor itself reads or writes it; nothing else gets near it.
- A mailbox — the queue where incoming messages wait their turn, delivered async.
- One-at-a-time processing — the actor chews through its mailbox in order, so its state never faces two writers at once.
Messages land in mailboxes, not in the actor’s hands — the sender fires and forgets. Need an answer back? Attach a reply-to address and it arrives as just another message.
Sequential processing kills races inside the actor; private state kills shared-state bugs across the board. The price: every read and write is a message round-trip instead of a method call — slower per operation, safer per system.
Two ordering subtleties worth internalizing early. First, the model only guarantees ordering per sender-receiver pair: two messages from A to B arrive in send order, but A’s and C’s messages to B can interleave in any order. Second, undeliverable messages don’t vanish — most frameworks route them to a dead-letter channel, and ignoring that channel is the actor model’s version of swallowing an exception.
Variants
| Variant | Implementation | Use Case | Tradeoff |
|---|---|---|---|
| Akka | JVM (Scala/Java) | Enterprise, distributed systems | Heavy framework, JVM-only |
| Erlang/OTP | BEAM VM | Telecom, high-availability | Erlang language |
| asyncio actors | Python asyncio | Single-process concurrency | Single-threaded, no true parallelism |
| Worker threads | Node.js | CPU-bound isolation | Limited message types |
| Proto Actor | Go, .NET | Cross-platform actors | Smaller ecosystem |
What Works
- Keep actors small and focused: one responsibility per actor
- Make messages immutable: prevent the sender from modifying a message after sending
- Use supervisor actors to monitor and restart failed actors (Erlang’s “let it crash” philosophy)
- Design messages as typed records or classes for clarity
- Avoid blocking operations inside an actor: if you need to call a slow API, spawn a temporary worker
- Monitor mailbox depth: a growing mailbox means the actor can’t keep up
- Use actor hierarchies: supervisors manage child actors and handle their failures
Common Mistakes
- Sharing mutable state outside the actor: If external code modifies the actor’s state, the isolation guarantee breaks. Every read and write goes through a message.
- Blocking inside the actor: A blocking call (synchronous I/O, long computation) stalls the whole mailbox. Offload to a worker.
- Synchronous request-reply: Actors are built for async messaging. Bolt a synchronous call on top and you’ve rebuilt the deadlock the model was meant to kill.
- Too many fine-grained actors: Each actor carries overhead (mailbox, scheduling). A swarm of tiny actors just burns memory and scheduler time — group related state into one.
- Ignoring failures: When an actor dies, everything queued in its mailbox dies with it.
- Fat messages: Shipping big objects between actors — worse across a network — costs real time. Send IDs or references instead.
Troubleshooting
- Actor mailbox grows unbounded: apply backpressure, bounded queues, and load shedding — an unbounded mailbox is a slow memory leak.
- Messages arrive out of order: actors guarantee per-sender ordering only; use sequence numbers or a coordination actor when cross-sender order matters.
- Actor becomes a bottleneck: one mailbox, one actor — partition the work (actor-per-key, actor-per-tenant) instead of scaling the actor.
- Dead actor loses state: actors restart empty; persist what matters externally before processing, not after.
Supervision and Fault Tolerance
The actor model’s real selling point isn’t concurrency — it’s fault isolation. In Erlang/OTP and Akka, actors sit in a supervision tree: a parent watches its children and decides what happens when one goes down.
The strategies are deliberately simple: restart the child (most common — the child comes back with fresh state), resume it (skip the failed message, keep the state), stop it (when it can’t recover), or escalate to the parent’s supervisor (when the child can’t decide). “Let it crash” is the entire strategy, not a slogan: rather than defensive code for every imaginable failure, you let the actor die and the supervisor brings back a known-good state.
The catch: restart gives you a fresh actor, not a recovered one. Anything that must survive a crash lives outside the actor — a database, an event log, a persistent queue — so the restarted actor can rebuild from it.
Backpressure and Bounded Mailboxes
An actor that can’t keep up accumulates messages — and an unbounded mailbox turns a slow consumer into an OOM kill. Production actor systems bound the mailbox and decide what happens when it fills:
- Block the sender — natural backpressure; the producer slows to the consumer’s rate.
- Drop new messages — acceptable for telemetry, terrible for orders.
- Drop oldest — keeps only the freshest state for metrics-type messages.
- Reject the send — the producer gets an error back and chooses whether to retry or alert.
There’s no universal right answer; there’s a universal wrong one: ignoring the question until the mailbox eats the heap.
Actors vs. the Alternatives
| Approach | Shared state | Fault isolation | Complexity | When it wins |
|---|---|---|---|---|
| Threads + locks | Shared, locked | None — a bug takes the process | Low until contention | Stateless parallel work |
| async/await | Shared event loop | Task crashes, loop survives | Low | I/O-bound without stateful entities |
| Actor model | Isolated per actor | Supervisor trees | Higher | Stateful, fault-tolerant, distributed |
The honest trade-off: actors buy isolation and fault tolerance at the price of message-serialization overhead and a programming model that fights you when the problem really is “shared state, just lock it.” For stateless throughput, a thread pool wins; for a system of stateful entities that must not die together, actors are the honest abstraction. For a wider map of these options, the concurrency patterns guide walks through all of them — and if your problem is really pipelined hand-off between threads, CSP channels solve it with even less machinery.
Where the Model Ships for Real
The actor model isn’t academic — it runs production systems at scale:
- Erlang/OTP — the original; WhatsApp’s billion-user messaging runs on it.
- Akka (JVM) — the mainstream implementation; supervision trees, clustering, location transparency.
- Microsoft Orleans (.NET) — “virtual actors” that activate on demand and garbage-collect when idle; powers Halo’s backend.
- Elixir — modern syntax on the Erlang VM (BEAM); Phoenix’s real-time channels are actors.
- Celluloid (Ruby), Proto.Actor (Go/.NET) — lighter-weight ports of the same idea (Celluloid is unmaintained these days, but it’s still the clearest Ruby expression of the model).
Each ships the same core — isolated state, mailboxes, supervision — with different trade-offs around distribution and persistence.
Further Reading
- Akka Documentation — the reference actor implementation for the JVM
- Erlang/OTP Design Principles — supervision trees from the origin
- Hewitt, Bishop & Steiger (1973) — the original actor model paper
- Microsoft Orleans — virtual actors for .NET
Frequently Asked Questions
How is the actor model different from thread pools?
Thread pools run threads over shared state, so locks are on you. Actors flip it: state is private and coordination happens through messages. Pools win on stateless parallel work; actors win when the work is stateful entities that need isolation.
Can actors run on different machines?
Yes. Frameworks like Akka and Erlang/OTP give you location transparency: you send a message to an actor address and the runtime routes it, on the same box or across the network. The sender neither knows nor needs to know where that actor actually lives.
What happens if an actor crashes?
In Erlang/OTP and Akka, a supervisor spots the failure and restarts the child. It comes back with a clean slate — anything that must survive goes to a database or event log before processing, not after.
Is the actor model faster than shared memory?
When contention is low, shared memory wins on raw speed — a direct field write beats a mailbox round-trip every time. Under heavy contention the balance flips: actors skip the lock queues and the parked threads entirely.
Should I use actors for everything?
No. Actors cost overhead (message serialization, mailbox management). For embarrassingly parallel work with no state, a thread pool or async/await does the job with less machinery. Reach for actors when the workload is stateful entities that can't afford to die together.
Related Resources
Thread Pool Pattern
Reuse a fixed set of threads for short-lived tasks instead of creating a new thread per task. Reduces overhead and bounds resource usage under load.
PatternProducer-Consumer Pattern
Decouple production and consumption with a shared queue. Producers generate items at their own pace; consumers process them through a buffer.
PatternLock-Free Queue Pattern
Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.
GuideConcurrency Patterns Guide
Production-ready concurrency patterns: thread pools, async/await, producer-consumer, semaphores, actors, circuit breakers in Python, Java, JS, Go, Elixir.
RecipeCoordinate Concurrent Tasks with CSP Channels
Structure concurrent programs with channels, select, and goroutines — safe message passing without shared mutable state in Go, Rust, and JS.