2 min read

Actor Model

The Actor Model is a conceptual model to deal with concurrent computation. It treats "actors" as the universal primitives of concurrent computation. In response to a message that it receives, an actor can: make local decisions, create more actors, send more messages, and determine how to respond to the next message received.

1. Core Concepts

  • Actor: The fundamental unit of computation. It encapsulates state and behavior.
  • Mailbox: Each actor has a mailbox (queue) where incoming messages are stored until the actor processes them.
  • Message Passing: Actors communicate only by sending asynchronous messages. They never share memory.

2. "No Shared State"

Unlike traditional threading models where threads share memory (leading to locks, race conditions, and deadlocks), actors are completely isolated.

  • State is private to the actor.
  • To change an actor's state, you must send it a message.
  • The actor processes messages one at a time (single-threaded within the actor), eliminating the need for locks.

3. Fault Tolerance (Let it Crash)

The Actor Model (popularized by Erlang) introduces a unique approach to error handling: "Let it Crash".

  • Supervision Hierarchies: Actors form a tree structure. Parents supervise their children.
  • Recovery: If a child actor crashes, the parent decides what to do (Restart, Resume, Stop, or Escalate).
  • Self-Healing: Systems can automatically recover from failures without human intervention.

4. Implementations

Erlang / Elixir (OTP)

The most famous implementation. Erlang was built for telecom systems requiring 99.9999999% reliability.

  • Lightweight: You can run millions of actors (processes) on a single machine.

Akka (Java / Scala)

A toolkit and runtime for building highly concurrent, distributed, and resilient message-driven applications on the JVM.

Microsoft Orleans / Akka.NET

Implementations for the .NET ecosystem. Orleans introduces "Virtual Actors" (Grains) that are automatically activated/deactivated.

5. Example (Conceptual)

# Pseudo-code
class BankAccountActor:
    def __init__(self):
        self.balance = 0

    def receive(self, message):
        if message.type == "DEPOSIT":
            self.balance += message.amount
        elif message.type == "WITHDRAW":
            if self.balance >= message.amount:
                self.balance -= message.amount
            else:
                print("Insufficient funds")
        elif message.type == "GET_BALANCE":
            sender.send(self.balance)

programming/distributed-systems programming/microservices-architecture programming/asynchronous-programming programming/reactive-programming