# Actor

## Overview

The fundamental building blocks of GoAkt are actors.

* Have a *unique name across the entire system even in cluster mode*. One a name is given to an actor, it is immutable and it is globally unique.
* They are independent, isolated unit of computation with their own state.
* They can be *long-lived* actors or be *passivated* after some period of time that is configured during their creation. Use this feature with care when dealing with persistent actors (actors that require their state to be persisted).
* They are automatically thread-safe without having to use locks or any other shared-memory synchronisation mechanisms.
* They can be stateful and stateless depending upon the system to build.
* Every actor in GoAkt:
  * has a process id [**`PID`**](https://github.com/Tochemey/goakt/blob/main/actor/pid.go). Via the process id any allowable action can be executed by the actor.
  * has a lifecycle via the following methods: **`PreStart`**, **`PostStop`**.
    * **`PreStart`** hook is used to initialise actor state. It is like the actor constructor.
    * **`PostStop`** hook is used to clean up resources used by the Actor. It is like the actor destructor. It means it can live and die like any other process.
  * handles and responds to messages via the method **`Receive`**. While handling messages it can:
  * create other (child) actors via their process id **`PID`** **`SpawnChild`** method
  * send messages to other actors locally or remotely via their process id `PID` `Ask`, **`RemoteAsk`**(request/response fashion) and **`Tell`**, **`RemoteTell`**(fire-and-forget fashion) methods
  * stop (child) actors via their process id **`PID`**
  * watch/unwatch (child) actors via their process id **`PID`** **`Watch`** and **`UnWatch`** methods
  * supervise the failure behavior of (child) actors.
  * remotely lookup for an actor on another node via their process id **`PID`** **`RemoteLookup`**. This allows it to send messages remotely via **`RemoteAsk`** or **`RemoteTell`** methods
  * stash/unstash messages. See [Stashing](/goakt/features/actor/stashing.md)
  * can adopt various form using the **`Behavior`** feature. See [Behaviors](/goakt/features/actor/behaviors.md)
  * can be restarted (respawned)
  * can be gracefully stopped (killed). Every message in the mailbox prior to stoppage will be processed within a configurable time period.

## PID

* Acts as a unique, immutable identifier for each actor within the system. See [`PID`](https://github.com/Tochemey/goakt/blob/main/actor/pid.go) for more information.
* Serves as the primary handle for sending messages to the actor, ensuring location transparency.
* Encapsulates the actor’s address and operational semantics (e.g., supervision and lifecycle management).
* Enables message delivery by directing both asynchronous (“tell”) and synchronous (“ask”) interactions.
* Facilitates supervision, where parent actors can monitor, restart, or stop child actors using their PIDs.
* Supports remote messaging by incorporating network location data, making inter-node communication seamless.
* Combines actor reference, mailbox, metrics, and synchronization primitives.
* Provides a rich API with methods like **`Tell`**, **`Ask`**, **`RemoteTell`**, and **`RemoteAsk`** to cover different messaging patterns.
* Integrates with the actor’s mailbox and supervision framework, enabling effective lifecycle management and monitoring.

## Address

In GoAkt, each actor is assigned a unique address that serves as its identifier in the system. This address is essential for enabling remote communication between actors, ensuring that messages are routed correctly and efficiently. Whenever an actor engages in remoting activities—such as sending or receiving messages across nodes—its address acts as the definitive reference point, guaranteeing reliable delivery and interaction.

## Get Started

To create an Actor one needs to ***first*** create the actor definition by implementing the Actor interface:

```go
type Actor interface {
    // PreStart is called once before the actor starts processing messages.
    //
    // Use this method to initialize dependencies such as database clients,
    // caches, or external service connections and persistent state recovery. If PreStart returns an error,
    // the actor will not be started, and the failure will be handled by its supervisor.
    PreStart(ctx *Context) error
    
    // Receive handles all messages sent to the actor's mailbox.
    //
    // This is the heart of the actor's behavior. Messages can include user-defined
    // commands/events as well as internal system messages such as PostStart or lifecycle signals.
    //
    // Actors can reply to messages using async messaging patterns or configure replies inline
    // where supported. Avoid heavy synchronous workflows as they may degrade throughput in high-load scenarios.
    //
    // Tip: Use pattern matching or typed message handlers to organize complex message workflows.
    Receive(ctx *ReceiveContext)
    
    // PostStop is called when the actor is about to shut down.
    //
    // This lifecycle hook is invoked after the actor has finished processing all messages
    // in its mailbox and is guaranteed to run before the actor is fully terminated.
    //
    // Use this method to perform final cleanup actions such as:
    //   - Releasing resources (e.g., database connections, goroutines, open files)
    //   - Flushing logs or metrics
    //   - Notifying other systems of termination (e.g., via events or pub/sub)
    //
    // This method is especially important passivated actors, as it is also
    // called during passivation when an idle actor is stopped to free up resources.
    //
    // Note: If PostStop returns an error, the error is logged but does not prevent the actor
    // from being stopped. Keep PostStop logic fast and resilient to avoid delaying system shutdowns.
    PostStop(ctx *Context) error
}
```

Once the actor definition is set you can use any of the following methods of the [**`ActorSystem`**](https://github.com/Tochemey/goakt/blob/main/actor/actor_system.go)  interface:

* **`Spawn`**  creates an actor on the given local node. This method is not cluster-aware.
* **`SpawnOn`**  starts an actor either locally or remotely depending on the options provided as argument. This method is cluster-aware.
* **`SpawnSingleton`**   refers to [Cluster Singleton](/goakt/features/cluster/cluster-singleton.md) for more information


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tochemey.gitbook.io/goakt/features/actor.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
