Back to series
· 12 min read

Actor Model


I. What Is the Actor Model?

The Actor model (Actor Model) is a mathematical model and programming paradigm for describing concurrent computation. It abstracts the computational entities in a system into independent Actors, each of which has its own state, behavior, and message mailbox.

Actors do not directly access each other's internal state, nor do they collaborate through shared memory; instead, they communicate by sending messages.

After receiving a message, an Actor can perform the following operations:

  1. Create new Actors.
  2. Send messages to other Actors.
  3. Update its own internal state so as to handle subsequent messages.

The core idea of the Actor model is:

Replace shared memory with message passing, replace shared mutable data with isolated state, and achieve concurrency through asynchronous collaboration.

1.1 The Basic Components of an Actor

An Actor usually consists of three core parts:

Component Description
State Data private to the Actor, accessible and modifiable only by its own behavior
Behavior Defines how the Actor handles the messages it receives
Mailbox A queue holding messages sent to the Actor that are waiting to be processed

For example, a bank account Actor can maintain the account balance and handle deposit, withdrawal, and balance query messages.

AccountActor
├── State
│   └── balance = 1000
├── Behavior
│   ├── Deposit(amount)
│   ├── Withdraw(amount)
│   └── GetBalance()
└── Mailbox
    ├── Deposit(200)
    ├── Withdraw(100)
    └── GetBalance()

Other Actors should not modify balance directly; instead, they send messages to the account Actor, which handles the state change itself.

1.2 The Basic Communication Pattern of Actors

Actors collaborate by passing messages.

flowchart LR
    A["Actor A"] -->|"send message"| B["Actor B's Mailbox"]
    B --> C["Actor B processes the message"]
    C --> D["Update Actor B's state"]
    D -->|"optional: send a response"| A

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note that sending a message usually only means that the message has been submitted or dispatched; it does not mean that the target Actor has finished processing it.

Message communication in the Actor model is typically asynchronous: the sender does not have to wait for the receiver to finish processing.


II. The Core Mechanisms of the Actor Model

2.1 Message Passing

Message passing is the most important communication mechanism in the Actor model.

Actors do not call each other's internal methods directly; instead, they send messages, and the receiver decides how to handle them based on its own behavior.

For example:

OrderActor
    |
    | CreateOrder(order)
    v
InventoryActor
    |
    | ReserveStock(productId, quantity)
    v
PaymentActor
    |
    | Charge(orderId, amount)
    v
NotificationActor

The structure above expresses the collaborative relationships among different Actors.

In real systems, a message can contain:

  • The operation type.
  • Business parameters.
  • A request identifier.
  • A correlation ID.
  • Timeout information.
  • A reply target or response address.

Messages are best represented as immutable data structures, so that the sender cannot keep modifying the message content after it has been sent and thereby introduce state races.

For example:

public record DepositMessage(long amount) {}

public record WithdrawMessage(long amount) {}

public record BalanceQuery(String requestId) {}

Using immutable messages reduces the risk of data inconsistency when messages are passed across threads or processes.

2.2 Mailbox

Each Actor typically has its own mailbox.

The mailbox receives messages and, according to the scheduling policy defined by the runtime, hands them to the Actor for processing.

A typical mailbox processing flow:

flowchart TB
    A["Sender submits message"] --> B["Message enters target mailbox"]
    B --> C["Mailbox waits for scheduling"]
    C --> D["Actor is scheduled to execute"]
    D --> E["Retrieve a message"]
    E --> F["Execute corresponding behavior"]
    F --> G["Processing complete"]
    G --> H{"Any messages left in mailbox?"}
    H -->|"Yes"| E
    H -->|"No"| I["Wait for next scheduling"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

A mailbox is not just an ordinary queue; it may also include:

  • Message ordering policies.
  • Priority policies.
  • Capacity limits.
  • Message filtering.
  • Scheduling and execution policies.
  • Overflow handling policies.

Mailbox implementations differ across Actor frameworks.

For example, some frameworks use FIFO mailboxes, some support priority mailboxes, and others allow custom mailbox implementations.

Note: FIFO order in a mailbox does not mean there is a global message order across all senders.

If multiple senders send messages concurrently, the order in which messages arrive at the mailbox may be affected by scheduling and network transmission.

2.3 Behavior

Behavior defines what operations an Actor should perform when it receives different messages.

For example, an account Actor:

public class AccountActor {

    private long balance = 1000;

    public void onMessage(Object message) {
        if (message instanceof DepositMessage m) {
            balance += m.amount();

        } else if (message instanceof WithdrawMessage m) {
            if (balance >= m.amount()) {
                balance -= m.amount();
            }

        } else if (message instanceof BalanceQuery) {
            System.out.println("Balance: " + balance);
        }
    }
}

This example demonstrates behavior logic, but it is not itself a complete Actor framework implementation.

A real Actor runtime also needs to handle:

  • Mailbox management.
  • Message scheduling.
  • Concurrent execution.
  • Actor lifecycle.
  • Exception isolation.
  • Message delivery and runtime management.

An Actor's state can only be modified by its own message-processing logic, which prevents multiple execution threads from directly competing for the same internal state.

2.4 State Isolation

In the traditional shared-memory concurrency model, multiple threads may access the same piece of data at the same time.

For example:

class Counter {
    int count = 0;

    void increment() {
        count++;
    }
}

If multiple threads execute increment() at the same time, a race condition may occur.

The Actor model usually encapsulates the counter as an independent Actor:

CounterActor
├── State
│   └── count = 0
└── Behavior
    └── Increment
        └── count = count + 1

Other Actors can only send an Increment message and cannot modify count directly.

Given that a single Actor's message-processing logic does not execute concurrently, state updates can proceed in message-processing order.

However, state isolation does not mean there are no concurrency issues in the entire system. Between multiple Actors, issues such as message ordering, business-level races, timeouts, and distributed consistency can still occur.


3. Actor Execution Model

3.1 A Single Actor Usually Processes Messages Serially

Many Actor implementations use single-threaded message-processing semantics: the same Actor processes only one message at a time.

Suppose there are three messages in the mailbox:

Message A
Message B
Message C

The processing procedure is usually:

flowchart TB
    A["Mailbox"] --> B["Message A"]
    B --> C["Execute A"]
    C --> D["A Processed"]
    D --> E["Message B"]
    E --> F["Execute B"]
    F --> G["B Processed"]
    G --> H["Message C"]
    H --> I["Execute C"]
    I --> J["C Processed"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This means:

  • State updates for the same Actor usually do not require extra locking.
  • Message processing logic for the same Actor has serial execution semantics.
  • Different Actors can process messages concurrently.
  • The number of Actors can be much larger than the number of actual worker threads.

The serialization here applies to message processing for the same Actor; it does not mean the entire system can only execute serially.

3.2 Different Actors Can Execute Concurrently

Suppose the system has three Actors:

  • OrderActor: processes orders.
  • InventoryActor: processes inventory.
  • PaymentActor: processes payments.

They can be scheduled concurrently by different worker threads.

flowchart TB
    A["Actor Runtime"] --> B["Scheduler"]
    B --> C["Worker 1"]
    B --> D["Worker 2"]
    B --> E["Worker 3"]
    C --> F["OrderActor"]
    D --> G["InventoryActor"]
    E --> H["PaymentActor"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

An actual Actor runtime usually reuses a thread pool or scheduler rather than creating an operating system thread for each Actor.

Therefore, the number of Actors can be very large, while the number of underlying worker threads is controlled by the runtime.

3.3 Actors Are Not Threads

This is a very important point when understanding the Actor model.

Comparison Dimension Actor Thread
Abstraction Level Concurrent computation entity Operating system or runtime execution unit
State Usually has private state Can access shared memory
Communication Mainly through message passing Through shared memory, messages, etc.
Scheduling Usually managed by Actor Runtime Scheduled by the operating system or runtime
Number Can be very large Usually limited by resources
Lifecycle Managed by the Actor system Managed by the thread runtime

An Actor does not necessarily correspond to one thread.

In many implementations, multiple Actors can share a worker thread pool, and the scheduler is responsible for assigning the message-processing tasks of different Actors to available threads.

3.4 Actor Scheduling Mechanism

Actor Runtime usually includes a Scheduler, which is responsible for managing executable Actors or message-processing tasks.

Typical scheduling process:

flowchart TB
    A["Message enters mailbox"] --> B["Actor marked as runnable"]
    B --> C["Scheduler gets a task to execute"]
    C --> D["Assign to Worker"]
    D --> E["Execute message processing logic"]
    E --> F{"Are there still messages in the mailbox?"}
    F -->|"Yes"| G["Re-enter scheduling queue"]
    F -->|"No"| H["Actor waits for new messages"]
    G --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The scheduler needs to consider:

  • Load balancing across worker threads.
  • Fairness in message processing.
  • The execution state of Actors.
  • Mailbox backlog.
  • Long-running message-processing tasks.

If an Actor's message-processing logic blocks for a long time, it may occupy a worker thread and affect the scheduling of other Actors.

Therefore, the Actor model does not mean that blocking operations can be ignored.


IV. Actor Model and Shared-Memory Concurrency Model

The Actor model and the traditional thread shared-memory model have obvious differences in state management and communication methods.

4.1 Shared-Memory Model

The shared-memory model allows multiple threads to access the same data.

For example:

class SharedCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

Here, synchronized ensures mutually exclusive access to the critical section.

However, as shared data and the number of threads increase, the system may experience:

  • Lock contention.
  • Deadlocks.
  • Overly coarse lock granularity.
  • State coupling.
  • Difficulty in concurrent debugging.

4.2 Actor Model

The Actor model encapsulates shared state in independent entities.

Multiple senders
    |
    v
CounterActor
    |
    +-- Mailbox
    |
    +-- State: count
    |
    +-- Behavior: Increment / GetCount

Senders can only request the Actor to modify or query its state through messages.

When the semantics of serial message processing for a single Actor are satisfied, there is no need to add traditional mutual exclusion locks for updates to that Actor's private state.

4.3 Comparison of the Two Models

Comparison Dimension Shared-Memory Model Actor Model
State management Multiple threads may share state Actors usually have private state
Communication method Shared variables, locks, condition variables, etc. Message passing
Synchronization mechanism Locks, atomic operations, barriers, etc. Mailboxes and message scheduling
Concurrency control Developers manage shared state The runtime provides some isolation guarantees
Data races Easily arise from shared access Private state can reduce this risk
Typical problems Deadlocks, race conditions, lock contention Message backlog, ordering, timeouts, failures
Applicable scenarios Fine-grained shared-data computation State isolation, asynchronous collaboration, and distributed systems

The two models are not completely mutually exclusive.

Real systems can use Actors, thread pools, atomic operations, database transactions, and shared memory at the same time.


V. Message Semantics in the Actor Model

Although message passing reduces the complexity caused by shared state, messages themselves also introduce new problems.

5.1 Sending a Message and Processing a Message Are Not the Same Thing

Suppose A sends a message to B:

A sends Request
    |
    v
B's Mailbox receives Request
    |
    v
B waits for scheduling
    |
    v
B processes Request
    |
    v
B returns Response

A successfully sent message does not mean successful business processing.

It is necessary to distinguish:

Stage Meaning
Send The sender submits a message
Receive The message enters the target mailbox or transport layer
Process The Actor begins executing the message logic
Complete Execution of the business operation corresponding to the message finishes
Persist The business result is reliably saved

Different Actor frameworks may define successful sending differently.

For example, a message may only have entered a local in-memory mailbox, without being persisted, and this does not mean the target Actor will necessarily finish processing it.

5.2 Message Delivery Semantics

Distributed Actor systems need to account for the possibility that messages may be lost, duplicated, or delayed.

Common message delivery semantics include:

Semantics Meaning Main Issue
At-most-once Delivered at most once May be lost
At-least-once Delivered at least once May be duplicated
Exactly-once The business effect occurs only once Requires additional mechanisms to guarantee

Particular attention should be paid to the following:

Exactly-once usually refers to exactly once at the level of business effects, not to a message being transmitted only once over the network.

For example, a payment service may retry the same payment request due to a network timeout.

Without idempotent handling, duplicate charges may occur.

Common solutions include:

  • Assigning a unique business ID to each request.
  • Recording request IDs that have already been processed.
  • Using an idempotency key.
  • Placing the business state and the deduplication record in the same transaction.
  • Reliably managing message consumption progress.

5.3 Message Ordering

Message ordering needs to be distinguished by scope:

  1. A single sender to a single receiver.
  2. Multiple senders to the same receiver.
  3. Global ordering across multiple Actors.

The fact that the same sender sends messages in order does not mean that all Actor frameworks can guarantee the receiver will process them strictly in that order.

When multiple senders send messages to the same Actor at the same time, there is usually no natural global ordering in the system.

If the business depends on ordering, it should be designed explicitly:

  • Message sequence numbers.
  • Version numbers.
  • A single message producer.
  • Ordered message channels.
  • State machine validation.
  • Ordering control based on business IDs.

5.4 Request-Response

Although the Actor model is based on asynchronous messages, this does not mean request-response interactions are impossible.

For example, a sender sends a query message to a target Actor and receives the result through a Future, a Promise, or a response Actor.

ClientActor
    |
    | GetBalance(requestId)
    v
AccountActor
    |
    | BalanceResult(requestId, balance)
    v
ClientActor

In real frameworks, the following mechanisms may be used:

  • Ask pattern: send a request and wait for a response.
  • Tell pattern: only send a message, without waiting for a result.
  • Future / Promise: obtain the result asynchronously.
  • ReplyTo: carry the response target in the message.

The Ask pattern usually requires setting a timeout.

If the target Actor does not respond, the caller must not wait indefinitely.


6. Actor Lifecycle and Supervision Mechanisms

An Actor is not just an object that processes messages; it also has a complete lifecycle.

6.1 Actor Lifecycle

Common lifecycle states include:

  • Created: created.
  • Started: started.
  • Running: running.
  • Stopped: stopped.
  • Failed: failed with an exception.

A typical lifecycle:

flowchart TB
    A["Create Actor"] --> B["Initialization"]
    B --> C["Start Running"]
    C --> D["Process Messages"]
    D --> E{"Exception occurred?"}
    E -->|"No"| D
    E -->|"Yes"| F["Enter Failure Handling"]
    F --> G{"Supervision Strategy"}
    G -->|"Restart"| H["Reinitialize"]
    H --> C
    G -->|"Stop"| I["Stop Actor"]
    G -->|"Escalate"| J["Hand Over to Parent Supervision"]
    J --> K["Parent Actor Handles It"]
    C --> L["Normal Stop"]
    L --> M["Release Resources"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style M fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The exact lifecycle states and callback methods are defined by the Actor framework, and different frameworks are not entirely consistent.

6.2 Supervision Mechanism (Supervision)

A common design in the Actor model is to form parent-child relationships between Actors.

A parent Actor can supervise the running state of its child Actors.

When a child Actor encounters an exception, the parent Actor decides how to handle it according to the supervision strategy.

Common strategies include:

Strategy Description
Resume Keep the Actor's current state and try to continue running
Restart Restart the Actor
Stop Stop the Actor
Escalate Hand the exception to the parent supervisor

For example:

RootActor
├── OrderActor
├── PaymentActor
└── InventoryActor

If an exception occurs in PaymentActor, RootActor or its direct supervisor can decide whether to restart, stop, or escalate it.

6.3 Restart Does Not Mean State Recovery

This is a problem that is very easy to overlook in the Actor supervision mechanism.

Restarting an Actor usually means reinitializing its runtime instance, but it does not necessarily restore the previous business state.

If an Actor's state is stored only in memory, it may be completely lost after a process crash.

Therefore, important state usually needs to be combined with:

  • Database persistence.
  • Event Sourcing.
  • Snapshots.
  • Message logs.
  • State recovery mechanisms.

The supervision mechanism mainly addresses runtime exception isolation and recovery; it does not automatically provide business data persistence.


7. Common Problems and Solutions in the Actor Model

7.1 Message Backlog (Mailbox Backlog)

If messages enter the mailbox faster than the Actor can process them, messages in the mailbox will continue to accumulate.

For example:

  • 10,000 messages enter per second.
  • The Actor can process only 5,000 messages per second.

The mailbox backlog will keep growing.

Common effects:

  • Increased memory usage.
  • Increased message processing latency.
  • Slower system response.
  • Eventually, memory exhaustion may occur.

Solutions:

  1. Use bounded mailboxes.
  2. Limit the send rate.
  3. Use backpressure.
  4. Split hot Actors.
  5. Optimize message processing logic.
  6. Monitor mailbox length and message wait time.

Note that a bounded mailbox must define an overflow strategy, such as rejecting, dropping, blocking, or transferring to a persistent queue.

7.2 Hot Actor (Hot Actor)

If a large number of requests are all sent to the same Actor, it may become a system bottleneck.

For example:

UserActor A ─┐
UserActor B ─┼──> GlobalCounterActor
UserActor C ─┤
UserActor D ─┘

All requests are concentrated into a single Actor, which causes message processing to be serialized.

Solutions:

  • Split one Actor into multiple shards.
  • Route by business keys such as user ID or order ID.
  • Use a distributed counter.
  • Aggregate results from multiple local states.
  • Separate read and write responsibilities.

For example, the global counter can be split into multiple local counters:

CounterGroup
├── CounterActor 1
├── CounterActor 2
├── CounterActor 3
└── CounterActor 4