Lifecycle
Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup.
Lifecycle
Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state.
On Create (runs once per actor)
createStateonCreatecreateVarsonWake
On Destroy
onDestroy
On Wake (after sleep, restart, or crash)
createVarsonWake
On Sleep (after idle period)
onSleep
On Connect (per client)
onBeforeConnectcreateConnStateonConnect
On Disconnect (per client)
onDisconnect
Lifecycle Hooks
Actor lifecycle hooks are defined as functions in the actor configuration.
state
The state constant defines the initial state of the actor. See state documentation for more information.
createState
The createState function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See state documentation for more information.
vars
The vars constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for vars must be clonable via structuredClone. See ephemeral variables documentation for more information.
createVars
The createVars function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. The driverCtx parameter provides driver-specific context. See ephemeral variables documentation for more information.
onCreate
The onCreate hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state.
onDestroy
The onDestroy hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence.
onWake
This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async.
This is called after the actor has been initialized but before any connections are accepted.
Use this hook to set up any resources or start any background tasks, such as setInterval.
onSleep
This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations.
This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations.
Not supported on Cloudflare Workers.
onStateChange
Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates.
createConnState and connState
There are two ways to define the initial state for connections:
connState: Define a constant object that will be used as the initial state for all connectionscreateConnState: A function that dynamically creates initial connection state based on connection parameters. Can be async.
onBeforeConnect
The onBeforeConnect hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via params. This hook is used for connection validation and can throw errors to reject connections.
The onBeforeConnect hook does NOT return connection state - it's used solely for validation.
Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see Authentication for details.
onConnect
Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter.
Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect.
onDisconnect
Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources.
onRequest
The onRequest hook handles HTTP requests sent to your actor at /actors/{actorName}/http/* endpoints. Can be async. It receives the request context and a standard Request object, and should return a Response object or void to continue default routing.
See Request Handler for more details.
onWebSocket
The onWebSocket hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a WebSocket object. Use this to set up WebSocket event listeners and handle real-time communication.
See WebSocket Handler for more details.
onBeforeActionResponse
The onBeforeActionResponse hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output.
Options
The options object allows you to configure various timeouts and behaviors for your actor.
| Option | Default | Description |
|---|---|---|
createVarsTimeout | 5000ms | Timeout for createVars function |
createConnStateTimeout | 5000ms | Timeout for createConnState function |
onConnectTimeout | 5000ms | Timeout for onConnect hook |
onSleepTimeout | 5000ms | Timeout for onSleep hook |
onDestroyTimeout | 5000ms | Timeout for onDestroy hook |
stateSaveInterval | 10000ms | Interval for persisting state |
actionTimeout | 60000ms | Timeout for action execution |
waitUntilTimeout | 15000ms | Max time to wait for background promises during shutdown |
connectionLivenessTimeout | 2500ms | Timeout for connection liveness check |
connectionLivenessInterval | 5000ms | Interval for connection liveness check |
noSleep | false | Prevent actor from sleeping |
sleepTimeout | 30000ms | Time before actor sleeps due to inactivity |
canHibernateWebSocket | false | Whether WebSockets can hibernate (experimental) |
Advanced
Running Background Tasks
The c.runInBackground method allows you to execute promises asynchronously without blocking the actor's main execution flow. The actor is prevented from sleeping while the promise passed to runInBackground is still active. This is useful for fire-and-forget operations where you don't need to wait for completion.
Common use cases:
- Analytics and logging: Send events to external services without delaying responses
- State sync: Populate external databases or APIs with updates to actor state in the background
Actor Shutdown Abort Signal
The c.abortSignal provides an AbortSignal that fires when the actor is stopping. Use this to cancel ongoing operations when the actor sleeps or is destroyed.
See Canceling Long-Running Actions for manually canceling operations on-demand.
Using ActorContext Type Externally
When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions.
See Types for more details on using ActorContextOf.