# Crash Course

## Features

- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts.
- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts.
- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events.
- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts.
- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations.

## When to Use Rivet Actors

- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration.
- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat.
- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control.
- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL.
- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout.

## Minimal Project

### Backend

**index.ts**

examples/docs/actors-crash-course/minimal-project.ts:

```ts
import { actor, event, setup } from "rivetkit";

const counter = actor({
	state: { count: 0 },
	events: {
		count: event<number>(),
	},
	actions: {
		increment: (c, amount: number) => {
			c.state.count += amount;
			c.broadcast("count", c.state.count);
			return c.state.count;
		},
	},
});

export const registry = setup({
	use: { counter },
});

registry.start();
```

### Client Docs

Use the client SDK that matches your app:

- [JavaScript Client](/actors/docs/clients/javascript)
- [React Client](/actors/docs/clients/react)
- [Swift Client](/actors/docs/clients/swift)

## Actor Quick Reference

### In-Memory State

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.

### Static Initial State

examples/docs/actors-crash-course/state-static.ts:

```ts
import { actor } from "rivetkit";

const counter = actor({
state: { count: 0 },
actions: {
increment: (c) => c.state.count += 1,
},
});
```

### Dynamic Initial State

examples/docs/actors-crash-course/state-dynamic.ts:

```ts
import { actor } from "rivetkit";

interface CounterState {
  count: number;
}

const counter = actor({
  createState: (c, input: { start?: number }): CounterState => ({
    count: input.start ?? 0,
  }),
  actions: {
    increment: (c) => c.state.count += 1,
  },
});
```

[Documentation](/actors/docs/state)

### Keys

Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing:

examples/docs/actors-crash-course/keys.ts:

```ts
import { actor, setup } from "rivetkit";
import { createClient } from "rivetkit/client";

const chatRoom = actor({
	state: { messages: [] as string[] },
	actions: {
		getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }),
	},
});

const registry = setup({ use: { chatRoom } });
const client = createClient<typeof registry>("http://localhost:6420");

// Compound key: [org, room]
client.chatRoom.getOrCreate(["org-acme", "general"]);

// Access key inside actor via c.key
```

Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks.

[Documentation](/actors/docs/keys)

### Input

Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later.

examples/docs/actors-crash-course/input.ts:

```ts
import { actor, setup } from "rivetkit";
import { createClient } from "rivetkit/client";

const game = actor({
	state: { mode: "" },
	createState: (c, input: { mode: string }) => ({
		mode: input.mode, // Store input in state for later access
	}),
	actions: {
		getMode: (c) => c.state.mode,
	},
});

const registry = setup({ use: { game } });
const client = createClient<typeof registry>("http://localhost:6420");

// Client usage
const gameHandle = client.game.getOrCreate(["game-1"], {
	createWithInput: { mode: "ranked" },
});
```

[Documentation](/actors/docs/input)

### Temporary Variables

Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc).

### Static Initial Vars

examples/docs/actors-crash-course/vars-static.ts:

```ts
import { actor } from "rivetkit";

const counter = actor({
state: { count: 0 },
vars: { lastAccess: 0 },
actions: {
increment: (c) => {
c.vars.lastAccess = Date.now();
return c.state.count += 1;
},
},
});
```

### Dynamic Initial Vars

examples/docs/actors-crash-course/vars-dynamic.ts:

```ts
import { actor } from "rivetkit";

const counter = actor({
  state: { count: 0 },
  createVars: () => ({
    emitter: new EventTarget(),
  }),
  actions: {
    increment: (c) => {
      c.vars.emitter.dispatchEvent(new Event("change"));
      return c.state.count += 1;
    },
  },
});
```

[Documentation](/actors/docs/state)

### Actions

Actions are the primary way clients and other actors communicate with an actor.

examples/docs/actors-crash-course/actions.ts:

```ts
import { actor } from "rivetkit";

const counter = actor({
	state: { count: 0 },
	actions: {
		increment: (c, amount: number) => (c.state.count += amount),
		getCount: (c) => c.state.count,
	},
});
```

Actions can be nested to group related behavior. For example, `handle.users.add("Ada")` calls the low-level action name `users.add`.

[Documentation](/actors/docs/actions)

### Events & Broadcasts

Events enable real-time communication from actors to connected clients.

examples/docs/actors-crash-course/events.ts:

```ts
import { actor, event } from "rivetkit";

const chatRoom = actor({
	state: { messages: [] as string[] },
	events: {
		newMessage: event<{ text: string }>(),
	},
	actions: {
		sendMessage: (c, text: string) => {
			// Broadcast to ALL connected clients
			c.broadcast("newMessage", { text });
		},
	},
});
```

[Documentation](/actors/docs/events)

### Connections

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.

### Static Connection Initial State

examples/docs/actors-crash-course/conn-static.ts:

```ts
import { actor } from "rivetkit";

const chatRoom = actor({
state: {},
connState: { visitorId: 0 },
onConnect: (c, conn) => {
conn.state.visitorId = Math.random();
},
actions: {
whoAmI: (c) => c.conn.state.visitorId,
},
});
```

### Dynamic Connection Initial State

examples/docs/actors-crash-course/conn-dynamic.ts:

```ts
import { actor } from "rivetkit";

const chatRoom = actor({
  state: {},
  // params passed from client
  createConnState: (c, params: { userId: string }) => ({
    userId: params.userId,
  }),
  actions: {
    // Access current connection's state and params
    whoAmI: (c) => ({
      state: c.conn.state,
      params: c.conn.params,
    }),
    // Iterate all connections with c.conns
    notifyOthers: (c, text: string) => {
      for (const conn of c.conns.values()) {
        if (conn !== c.conn) conn.send("notification", { text });
      }
    },
  },
});
```

[Documentation](/actors/docs/connections)

### Queues

Use queues to process durable messages in order inside a `run` loop.

examples/docs/actors-crash-course/queues.ts:

```ts
import { actor, queue } from "rivetkit";

const counter = actor({
	state: { value: 0 },
	queues: {
		increment: queue<{ amount: number }>(),
	},
	run: async (c) => {
		for await (const message of c.queue.iter()) {
			c.state.value += message.body.amount;
		}
	},
});
```

[Documentation](/actors/docs/queues)

### Workflows

Use workflows when your `run` logic needs durable, replayable multi-step execution.

examples/docs/actors-crash-course/workflows.ts:

```ts
import { actor, queue } from "rivetkit";
import { workflow } from "rivetkit/workflow";

const worker = actor({
	state: { processed: 0 },
	queues: {
		tasks: queue<{ url: string }>(),
	},
	run: workflow(async (ctx) => {
		await ctx.loop("task-loop", async (loopCtx) => {
			const message = await loopCtx.queue.next("wait-task");

			await loopCtx.step("process-task", async (loopCtx) => {
				await processTask(message.body.url);
				loopCtx.state.processed += 1;
			});
		});
	}),
});

async function processTask(url: string): Promise<void> {
	const res = await fetch(url, { method: "POST" });
	if (!res.ok) throw new Error(`Task failed: ${res.status}`);
}
```

[Documentation](/workflows/docs)

### Actor-to-Actor Communication

Actors can call other actors using `c.client()`.

examples/docs/actors-crash-course/actor-to-actor.ts:

```ts
import { actor, setup } from "rivetkit";

const inventory = actor({
	state: { stock: 100 },
	actions: {
		reserve: (c, amount: number) => {
			c.state.stock -= amount;
		},
	},
});

const order = actor({
	state: {},
	actions: {
		process: async (c) => {
			const client = c.client<typeof registry>();
			await client.inventory.getOrCreate(["main"]).reserve(1);
		},
	},
});

const registry = setup({ use: { inventory, order } });
```

[Documentation](/actors/docs/communicating-between-actors)

### Schedule & Cron

Run one-shot actions after a delay or at a specific time. Use named cron jobs for calendar schedules and fixed intervals. Both persist across sleep, restarts, upgrades, and crashes.

examples/docs/actors-crash-course/scheduling.ts:

```ts
import { actor, event } from "rivetkit";

const reminder = actor({
  state: { message: "Time to check your tasks." },
  events: {
    reminder: event<{ message: string }>(),
  },
  onCreate: async (c) => {
    // Install initial schedules once, when this actor is first created.
    await c.schedule.after(30_000, "sendReminder");

    await c.cron.every({
      name: "reminder-check",
      interval: 60_000,
      action: "sendReminder",
    });
  },
  actions: {
    sendReminder: (c) => {
      c.broadcast("reminder", { message: c.state.message });
    },
  },
});
```

[Documentation](/actors/docs/schedule)

### Destroying Actors

Permanently delete an actor and its state using `c.destroy()`.

examples/docs/actors-crash-course/destroying.ts:

```ts
import { actor } from "rivetkit";

const userAccount = actor({
	state: { email: "", name: "" },
	onDestroy: (c) => {
		console.log(`Account ${c.state.email} deleted`);
	},
	actions: {
		deleteAccount: (c) => {
			c.destroy();
		},
	},
});
```

[Documentation](/actors/docs/destroy)

### Lifecycle Hooks

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.

examples/docs/actors-crash-course/lifecycle.ts:

```ts
import { actor, event, queue } from "rivetkit";

interface RoomState {
	users: Record<string, boolean>;
	name?: string;
}

interface RoomInput {
	roomName: string;
}

interface ConnState {
	userId: string;
	joinedAt: number;
}

const chatRoom = actor({
	events: {
		stateChanged: event<RoomState>(),
	},
	queues: {
		work: queue<{ task: string }>(),
	},

	// State & vars initialization
	createState: (c, input: RoomInput): RoomState => ({
		users: {},
		name: input.roomName,
	}),
	createVars: () => ({ startTime: Date.now() }),

	// Actor lifecycle
	onCreate: (c) => console.log("created", c.key),
	onDestroy: (c) => console.log("destroyed"),
	onWake: (c) => console.log("actor started"),
	onSleep: (c) => console.log("actor sleeping"),
	run: async (c) => {
		for await (const message of c.queue.iter()) {
			console.log("processing", message.body.task);
		}
	},
	onStateChange: (c, newState) => c.broadcast("stateChanged", newState),

	// Connection lifecycle
	createConnState: (c, params): ConnState => ({
		userId: (params as { userId: string }).userId,
		joinedAt: Date.now(),
	}),
	onBeforeConnect: (c, params) => {
		/* validate auth */
	},
	onConnect: (c, conn) => console.log("connected:", (conn.state as ConnState).userId),
	onDisconnect: (c, conn) => console.log("disconnected:", (conn.state as ConnState).userId),

	// Networking
	onRequest: (c, req) => new Response(JSON.stringify(c.state)),
	onWebSocket: (c, socket) => socket.addEventListener("message", console.log),

	// Response transformation
	onBeforeActionResponse: <Out>(
		c: unknown,
		name: string,
		args: unknown[],
		output: Out,
	): Out => output,

	actions: {},
});
```

[Documentation](/actors/docs/lifecycle)

### Context Types

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.

examples/docs/actors-crash-course/context-types.ts:

```ts
import { actor, ActionContextOf } from "rivetkit";

const gameRoom = actor({
	state: { players: [] as string[], score: 0 },
	actions: {
		addPlayer: (c, playerId: string) => {
			validatePlayer(c, playerId);
			c.state.players.push(playerId);
		},
	},
});

// Good: derive context type from actor definition
function validatePlayer(c: ActionContextOf<typeof gameRoom>, playerId: string) {
	if (c.state.players.includes(playerId)) {
		throw new Error("Player already in room");
	}
}

// Bad: don't manually define context types like this
// type MyContext = { state: { players: string[] }; ... };
```

[Documentation](/actors/docs/types)

### Errors

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.

### Actor

examples/docs/actors-crash-course/errors-actor.ts:

```ts
import { actor, UserError } from "rivetkit";

const user = actor({
state: { username: "" },
actions: {
updateUsername: (c, username: string) => {
if (username.length < 3) {
throw new UserError("Username too short", {
code: "username_too_short",
metadata: { minLength: 3, actual: username.length },
});
}
c.state.username = username;
},
},
});
```

### Client

examples/docs/actors-crash-course/errors-client.ts:

```ts
import { actor, setup, UserError } from "rivetkit";
import { createClient, ActorError } from "rivetkit/client";

const user = actor({
  state: { username: "" },
  actions: {
    updateUsername: (c, username: string) => {
      if (username.length < 3) {
        throw new UserError("Username too short", {
          code: "username_too_short",
          metadata: { minLength: 3, actual: username.length },
        });
      }
      c.state.username = username;
    },
  },
});

const registry = setup({ use: { user } });
const client = createClient<typeof registry>("http://localhost:6420");

try {
  await client.user.getOrCreate([]).updateUsername("ab");
} catch (error) {
  if (error instanceof ActorError) {
    console.log(error.code);     // "username_too_short"
    console.log(error.metadata); // { minLength: 3, actual: 2 }
  }
}
```

[Documentation](/actors/docs/errors)

### Low-Level HTTP & WebSocket Handlers

For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`.

[HTTP Handler Documentation](/actors/docs/request-handler) · [WebSocket Handler Documentation](/actors/docs/websocket-handler)

### Icons & Names

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.

```typescript
import { actor } from "rivetkit";

const chatRoom = actor({
	options: {
		name: "Chat Room",
		icon: "💬", // or FontAwesome: "comments", "chart-line", etc.
	},
	// ...
});
```

[Documentation](/actors/docs/appearance)

## Client Documentation

Find the full client guides here:

- [JavaScript Client](/actors/docs/clients/javascript)
- [React Client](/actors/docs/clients/react)
- [Swift Client](/actors/docs/clients/swift)

## Common Patterns

Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns:

[Documentation](/actors/docs/design-patterns)

### Actor Per Entity

Create one actor per user, document, or room. Use compound keys to scope entities:

client.ts:

```ts
import { createClient } from "rivetkit/client";
import type { registry } from "./index";

const client = createClient<typeof registry>("http://localhost:6420");

// Single key: one actor per user
client.user.getOrCreate(["user-123"]);

// Compound key: document scoped to an organization
client.document.getOrCreate(["org-acme", "doc-456"]);
```

index.ts:

```ts
import { actor, setup } from "rivetkit";

export const user = actor({
  state: { name: "" },
  actions: {},
});

export const document = actor({
  state: { content: "" },
  actions: {},
});

export const registry = setup({ use: { user, document } });

registry.start();
```

### Coordinator & Data Actors

**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.

index.ts:

```ts
import { actor, setup } from "rivetkit";

// Coordinator: tracks chat rooms within an organization
export const chatRoomList = actor({
state: { rooms: [] as string[] },
actions: {
addRoom: async (c, name: string) => {
// Create the chat room actor
const client = c.client<typeof registry>();
await client.chatRoom.create([c.key[0], name]);
c.state.rooms.push(name);
},
listRooms: (c) => c.state.rooms,
},
});

// Data actor: handles a single chat room
export const chatRoom = actor({
state: { messages: [] as string[] },
actions: {
send: (c, msg: string) => { c.state.messages.push(msg); },
},
});

export const registry = setup({ use: { chatRoomList, chatRoom } });

registry.start();
```

client.ts:

```ts
import { createClient } from "rivetkit/client";
import type { registry } from "./index";

const client = createClient<typeof registry>("http://localhost:6420");

// Coordinator per org
const coordinator = client.chatRoomList.getOrCreate(["org-acme"]);
await coordinator.addRoom("general");
await coordinator.addRoom("random");

// Access chat rooms created by coordinator
client.chatRoom.get(["org-acme", "general"]);
```

### Run Loop

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.

examples/docs/actors-crash-course/run-loop.ts:

```ts
import { actor, queue, setup } from "rivetkit";

const counterWorker = actor({
	state: { value: 0 },
	queues: {
		mutate: queue<{ delta: number }>(),
	},
	run: async (c) => {
		for await (const message of c.queue.iter()) {
			c.state.value += message.body.delta;
		}
	},
	actions: {
		getValue: (c) => c.state.value,
	},
});

const registry = setup({ use: { counterWorker } });
```

### Workflow Loop

Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up.

examples/docs/actors-crash-course/workflow-loop.ts:

```ts
import { actor, queue, setup } from "rivetkit";
import { Loop, workflow } from "rivetkit/workflow";

type WorkMessage = { amount: number };
type ControlMessage = { type: "stop"; reason: string };

const worker = actor({
	state: {
		phase: "idle" as "idle" | "running" | "stopped",
		processed: 0,
		total: 0,
		stopReason: null as string | null,
	},
	queues: {
		work: queue<WorkMessage>(),
		control: queue<ControlMessage>(),
	},
	run: workflow(async (ctx) => {
		await ctx.step("setup", async (ctx) => {
			await fetch("https://api.example.com/workers/init", {
				method: "POST",
			});
			ctx.state.phase = "running";
			ctx.state.stopReason = null;
		});

		const stopReason = await ctx.loop("worker-loop", async (loopCtx) => {
			const message = await loopCtx.queue.next("wait-command", {
				names: ["work", "control"],
			});

			if (message.name === "work") {
				await loopCtx.step("apply-work", async (loopCtx) => {
					await fetch("https://api.example.com/workers/process", {
						method: "POST",
						body: JSON.stringify({ amount: message.body.amount }),
					});
					loopCtx.state.processed += 1;
					loopCtx.state.total += message.body.amount;
				});
				return;
			}

			return Loop.break((message.body as ControlMessage).reason);
		});

		await ctx.step("teardown", async (ctx) => {
			await fetch("https://api.example.com/workers/shutdown", {
				method: "POST",
			});
			ctx.state.phase = "stopped";
			ctx.state.stopReason = stopReason;
		});
	}),
});

const registry = setup({ use: { worker } });
```

[Documentation](/workflows/docs)

### Actions vs Queues

- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input.
- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work.

### Authentication, Security, & CORS

- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections.
- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters.
- For cross-origin access, validate the request origin in `onBeforeConnect`.

[Authentication Documentation](/actors/docs/authentication) · [CORS Documentation](/actors/docs/general/cors)

### Versions & Upgrades

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](/actors/docs/versions) 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.

[Documentation](/actors/docs/versions)

### Anti-Patterns

#### Never build a "god" actor

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.

#### Never create an actor per request

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.
