website/src/content/docs/actors/crash-course.mdx
index.ts
<CodeSnippet file="examples/docs/actors-crash-course/minimal-project.ts" />Use the client SDK that matches your app:
Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits.
<Tabs> <Tab title="Static Initial State"> <CodeSnippet file="examples/docs/actors-crash-course/state-static.ts" /> </Tab> <Tab title="Dynamic Initial State"> <CodeSnippet file="examples/docs/actors-crash-course/state-dynamic.ts" /> </Tab> </Tabs>Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing:
<CodeSnippet file="examples/docs/actors-crash-course/keys.ts" />Don't build keys with string interpolation like "org:${userId}" when userId contains user data. Use arrays instead to prevent key injection attacks.
Pass initialization data when creating actors. Input is only available in createState and onCreate, so store it in state if you need it later.
Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc).
<Tabs> <Tab title="Static Initial Vars"> <CodeSnippet file="examples/docs/actors-crash-course/vars-static.ts" /> </Tab> <Tab title="Dynamic Initial Vars"> <CodeSnippet file="examples/docs/actors-crash-course/vars-dynamic.ts" /> </Tab> </Tabs>Actions are the primary way clients and other actors communicate with an actor.
<CodeSnippet file="examples/docs/actors-crash-course/actions.ts" />Events enable real-time communication from actors to connected clients.
<CodeSnippet file="examples/docs/actors-crash-course/events.ts" />Access the current connection via c.conn or all connected clients via c.conns. Use c.conn.id or c.conn.state to securely identify who is calling an action. c.conn is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via connState or createConnState, which receives parameters passed by the client on connect.
Use queues to process durable messages in order inside a run loop.
Use workflows when your run logic needs durable, replayable multi-step execution.
Actors can call other actors using c.client().
Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes.
<CodeSnippet file="examples/docs/actors-crash-course/scheduling.ts" />Permanently delete an actor and its state using c.destroy().
Actors support hooks for initialization, background processing, connections, networking, and state changes. Use run for long-lived background loops, and use c.aborted or c.abortSignal for graceful shutdown.
When writing helper functions outside the actor definition, use *ContextOf<typeof myActor> to extract the correct context type. Helpers like ActionContextOf, CreateContextOf, ConnContextOf, and ConnInitContextOf are exported from "rivetkit". Do not manually define your own context interface. Always derive it from the actor definition.
Use UserError to throw errors that are safely returned to clients. Pass metadata to include structured data. Other errors are converted to generic "internal error" for security.
For custom protocols or integrating libraries that need direct access to HTTP Request/Response or WebSocket connections, use onRequest and onWebSocket.
HTTP Handler Documentation · WebSocket Handler Documentation
Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard.
import { actor } from "rivetkit";
const chatRoom = actor({
options: {
name: "Chat Room",
icon: "💬", // or FontAwesome: "comments", "chart-line", etc.
},
// ...
});
Find the full client guides here:
Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns:
Create one actor per user, document, or room. Use compound keys to scope entities:
<CodeGroup> <CodeSnippet file="examples/docs/actors-crash-course/actor-per-entity/client.ts" title="client.ts" /> <CodeSnippet file="examples/docs/actors-crash-course/actor-per-entity/index.ts" title="index.ts" /> </CodeGroup>Data actors handle core logic (chat rooms, game sessions, user data). Coordinator actors track and manage collections of data actors—think of them as an index.
<CodeGroup> <CodeSnippet file="examples/docs/actors-crash-course/coordinator/index.ts" title="index.ts" /> <CodeSnippet file="examples/docs/actors-crash-course/coordinator/client.ts" title="client.ts" /> </CodeGroup>Use a run loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks.
Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up.
<CodeSnippet file="examples/docs/actors-crash-course/workflow-loop.ts" />onBeforeConnect or createConnState and throw an error to reject unauthorized connections.c.conn.state to securely identify users in actions rather than trusting action parameters.onBeforeConnect.Authentication Documentation · CORS Documentation
When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to configure versioning before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit.
Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity.
Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work.