> ## Documentation Index
> Fetch the complete documentation index at: https://docs.goakt.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Actor System

> Top-level runtime hosting actors, messaging, clustering, and lifecycle.

The **ActorSystem** is the top-level runtime that hosts actors and orchestrates messaging, clustering, remoting, and lifecycle. There is one ActorSystem per process. All actors, grains, and system services run within it.

## Role and responsibilities

| Responsibility           | Description                                                                                                                                    |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **Actor hosting**        | Spawns and supervises actors under the `/user` guardian. Manages the actor tree and parent-child relationships.                                |
| **Messaging**            | Routes messages locally or remotely. Serializes and deserializes when crossing node boundaries.                                                |
| **Clustering**           | When enabled, joins a cluster, discovers peers, and provides location-transparent actor resolution.                                            |
| **Remoting**             | When enabled, exposes a TCP server and client for cross-node communication.                                                                    |
| **Event stream**         | Publishes system and cluster events (ActorStarted, NodeJoined, Deadletter, etc.) to subscribers. See [Event Streams](/advanced/event-streams). |
| **PubSub**               | When `WithPubSub()` or cluster is enabled, a topic actor manages application-level topics. See [PubSub](/advanced/pubsub).                     |
| **Scheduling**           | Delivers one-time, recurring, and cron-scheduled messages to actors.                                                                           |
| **Coordinated shutdown** | Runs shutdown hooks, stops actors depth-first, and leaves the cluster gracefully.                                                              |

See [Architecture Overview](/architecture/overview) for the component diagram.

## Lifecycle

```
Start(ctx) → [running] → Stop(ctx) → [stopped]
```

* **NewActorSystem** — Applies options; does not start services.
* **Start** — Initializes remoting (if enabled), cluster (if enabled), scheduler, eviction, passivation, and system actors. Handle SIGTERM/SIGINT and call `Stop` for clean shutdown.
* **Stop** — Runs coordinated shutdown hooks, stops user actors, deactivates grains, shuts down system actors, leaves cluster, stops remoting. Does not exit the process; call `os.Exit` if needed.

Details: [Coordinated Shutdown](/advanced/coordinated-shutdown), [First Actor](/actor/first-actor).

## API surface

### Spawning

| Method                                                   | Use case                                                                                                                       |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `Spawn(ctx, name, actor, opts...)`                       | Create a named actor locally (or on a specific host with `WithHostAndPort`).                                                   |
| `SpawnOn(ctx, name, actor, opts...)`                     | Create actor on a cluster node (placement: RoundRobin, Random, Local, LeastLoad) or in another data center (`WithDataCenter`). |
| `SpawnFromFunc(ctx, receiveFunc, opts...)`               | Functional actor; no `Actor` implementation.                                                                                   |
| `SpawnNamedFromFunc(ctx, name, receiveFunc, opts...)`    | Named functional actor.                                                                                                        |
| `SpawnRouter(ctx, name, poolSize, routeesKind, opts...)` | Router with a pool of routees. Not cluster-relocatable.                                                                        |
| `SpawnSingleton(ctx, name, actor, opts...)`              | Cluster singleton; one instance across the cluster, hosted on the oldest node. See [Singletons](/actor/singletons).            |

See [Actor Lifecycle](/actor/lifecycle), [Routers](/actor/routers), [Singletons](/actor/singletons), [Clustering](/clustering/clustered).

### Resolution and inspection

| Method                   | Purpose                                                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------- |
| `ActorOf(ctx, name)`     | Resolve a PID by name. Local or remote; use `pid.IsLocal()` / `pid.IsRemote()` when it matters. |
| `ActorExists(ctx, name)` | Check if an actor exists locally or in the cluster.                                             |
| `Actors(ctx, timeout)`   | Enumerate all actors visible to this node. Use sparingly; cluster scan is costly.               |
| `NumActors()`            | Count of local actors only.                                                                     |
| `Partition(name)`        | Partition ID for a given actor name (cluster hashing).                                          |
| `InCluster()`            | Whether the system is running in cluster mode.                                                  |

See [PID](/actor/pid), [Location Transparency](/actor/location-transparency).

### Messaging from outside

From outside the actor system (e.g. `main`), use `system.NoSender()`:

* `NoSender().Tell(pid, msg)` — Fire-and-forget.
* `NoSender().Ask(ctx, pid, msg, timeout)` — Request-response; actor must call `ctx.Response(resp)`.

For processes that do not run an actor system (CLI, API server, batch job), use the [Client](/advanced/client) package to connect to the cluster and send messages by actor name.

See [Messaging](/actor/messaging).

### Scheduling

| Method                                                   | Purpose                           |
| -------------------------------------------------------- | --------------------------------- |
| `ScheduleOnce(ctx, msg, pid, delay, opts...)`            | One-time delivery after `delay`.  |
| `Schedule(ctx, msg, pid, interval, opts...)`             | Recurring delivery at `interval`. |
| `ScheduleWithCron(ctx, msg, pid, cronExpr, opts...)`     | Cron-based delivery.              |
| `CancelSchedule(reference)`                              | Cancel by reference.              |
| `PauseSchedule(reference)` / `ResumeSchedule(reference)` | Pause or resume a scheduled task. |

Use `WithReference(id)` when scheduling if you need to cancel, pause, or resume. See [Scheduling](/actor/scheduling).

### Events and observability

| Method                    | Purpose                                                                                                                  |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `Subscribe()`             | Create an event-stream subscriber for system/cluster events. Returns `eventstream.Subscriber`; iterate via `Iterator()`. |
| `Unsubscribe(subscriber)` | Release subscriber; call to avoid leaks.                                                                                 |
| `TopicActor()`            | Topic actor PID for PubSub (when `WithPubSub()` or cluster is enabled). Send Subscribe, Unsubscribe, Publish.            |
| `Metric(ctx)`             | Node-level metrics (actor count, mailbox sizes, throughput, uptime).                                                     |

See [Event Streams](/advanced/event-streams), [PubSub](/advanced/pubsub), [Observability](/advanced/observability).

### Cluster and lifecycle control

| Method               | Purpose                                                      |
| -------------------- | ------------------------------------------------------------ |
| `Kill(ctx, name)`    | Stop an actor by name (local or remote).                     |
| `ReSpawn(ctx, name)` | Restart an actor; children are recreated with initial state. |
| `Name()`             | Actor system name.                                           |

### Dependency injection

| Method                    | Purpose                                                                                                                                                                                    |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Inject(dependencies...)` | Register dependency types with the actor system after startup. Enables restoration during cluster topology changes and when creating actors on remote hosts. Must be called after `Start`. |

## Configuration options

Options are passed to `NewActorSystem(name, opts...)`. Each option is documented in the source; this table groups them by concern.

| Option                                     | Purpose                                                                                           |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| **Core**                                   |                                                                                                   |
| `WithLogger(logger)`                       | Custom logger. `WithLoggingDisabled()` for no-op.                                                 |
| `WithActorInitTimeout(d)`                  | Actor startup timeout.                                                                            |
| `WithActorInitMaxRetries(n)`               | Retries for actor init.                                                                           |
| `WithShutdownTimeout(d)`                   | Total shutdown timeout (default: 3 min).                                                          |
| `WithAskTimeout(d)`                        | System-wide timeout for internal Ask round-trips (default: 5s).                                   |
| `WithDefaultSupervisor(supervisor)`        | Fallback supervisor for actors without explicit config.                                           |
| **Remoting & cluster**                     |                                                                                                   |
| `WithRemote(config)`                       | Enable remoting. See [Remoting](/advanced/remoting).                                              |
| `WithCluster(config)`                      | Enable clustering. See [Clustered](/clustering/clustered).                                        |
| `WithTLS(info)`                            | TLS for remoting.                                                                                 |
| `WithoutRelocation()`                      | Disable actor relocation on node departure.                                                       |
| **Extensions & capabilities**              |                                                                                                   |
| `WithExtensions(ext...)`                   | System-wide extensions. See [Extensions and Dependencies](/advanced/extensions-and-dependencies). |
| `WithPubSub()`                             | Enable topic-based pub/sub.                                                                       |
| `WithMetrics()`                            | OpenTelemetry metrics. See [Observability](/advanced/observability).                              |
| **Shutdown & eviction**                    |                                                                                                   |
| `WithCoordinatedShutdown(hooks...)`        | Shutdown hooks. See [Coordinated Shutdown](/advanced/coordinated-shutdown).                       |
| `WithEvictionStrategy(strategy, interval)` | Passivation when actor count exceeds limit.                                                       |
| **Advanced**                               |                                                                                                   |
| `WithPartitionHasher(hasher)`              | Custom partition hasher for cluster placement.                                                    |

## Component relationships

The ActorSystem composes:

* **Remoting** — TCP server/client; used when `WithRemote` is set.
* **Cluster** — Membership, discovery, Olric DMap; used when `WithCluster` is set.
* **Event stream** — In-process pub/sub; always present; topic actors when `WithPubSub` is set.
* **Scheduler** — For `ScheduleOnce`, `Schedule`, `ScheduleWithCron`.
* **Extensions** — Accessed via `ctx.Extension(id)` from actors.

Actors obtain the system via `ctx.ActorSystem()` (or `ReceiveContext`, `GrainContext`). Use it to spawn children, resolve actors, schedule, or access extensions. Do not store the ActorSystem in actor state; always obtain it from context.

## Further reading

* [First Actor](/actor/first-actor) — Minimal flow
* [Actor Model](/actor/actor-model) — Actor interface and hierarchy
* [Clustering](/clustering/standalone) — Standalone vs clustered vs multi-DC
* [Reference: Interfaces](/reference/interfaces) — Interface definitions
