Skip to main content
Languages & Frameworks

Effect

Call Rivet Actors from Effect programs and write Rivet Actors as Effect programs, with typed contracts, typed errors, event streams, and SQLite.

This page is the reference for the Effect SDK (@rivetkit/effect): first how to call actors, then how to write actors. If you are new to the SDK, start with the Effect quickstart.

Calling Actors

Install

Add the Effect SDK and its Effect packages:

npm install rivetkit @rivetkit/effect effect @effect/platform-node

The Effect client is typed by the actor contract. Import the contract that your actor implements. There is no need to define the actor again on the client. The examples on this page use this contract:

import { Action, Actor, Event } from "@rivetkit/effect";
import { Schema } from "effect";

export class CounterOverflow extends Schema.TaggedError<CounterOverflow>()(
	"CounterOverflow",
	{ limit: Schema.Number },
) {}

export const Increment = Action.make("Increment", {
	payload: { amount: Schema.Number },
	success: Schema.Number,
	error: CounterOverflow,
});

export const GetCount = Action.make("GetCount", {
	success: Schema.Number,
});

export const CountChanged = Event.make("CountChanged", {
	payload: { count: Schema.Number },
});

export const Counter = Actor.make("Counter", {
	actions: [Increment, GetCount],
	events: [CountChanged],
});

Minimal Client

Counter.client gives an accessor for Counter actors. Client.layer provides the connection to the control plane:

import { NodeRuntime } from "@effect/platform-node";
import { Client } from "@rivetkit/effect";
import { Effect } from "effect";
import { Counter } from "./api";

const program = Effect.gen(function* () {
	const counter = (yield* Counter.client).getOrCreate("my-counter");

	const count = yield* counter.Increment({ amount: 1 });
	yield* Effect.log(`New count: ${count}`);
});

program.pipe(
	Effect.provide(Client.layer({ endpoint: "http://localhost:6420" })),
	NodeRuntime.runMain,
);

Provide Client.layer one time, at the root of the program. The other examples on this page show only the program.

Stateless vs Stateful

import { Effect } from "effect";
import { Counter } from "./api";

export const program = Effect.gen(function* () {
	const counter = (yield* Counter.client).getOrCreate("my-counter");

	// Stateless: each call is independent.
	yield* counter.Increment({ amount: 1 });

	// Stateful: the connection stays open until the scope closes.
	const connection = yield* counter.connect;
	yield* connection.Increment({ amount: 1 });
}).pipe(Effect.scoped);

A stateless call on the handle is one request for each action. handle.connect opens a connection that you can use for many calls and for events. The connection has the same action methods as the handle.

Getting Actors

import { Effect } from "effect";
import { Counter } from "./api";

export const program = Effect.fn(function* (actorId: string) {
	const counters = yield* Counter.client;

	// Creates the actor on the first call if it does not exist.
	const counter = counters.getOrCreate("my-counter");

	// Calls fail with `actor.not_found` if the actor does not exist.
	const existing = counters.get("my-counter");

	// Addresses an actor by its actor ID.
	const byId = counters.getForId(actorId);

	// Creates a new actor. Fails if an actor for the key exists.
	const created = yield* counters.create(["counter", crypto.randomUUID()]);

	return { counter, existing, byId, created };
});
  • getOrCreate, get and getForId return a handle at once. The client finds the actor on the first call.
  • create is an effect. It fails with a RivetError if an actor for the key exists.
  • getOrCreate also takes createWithInput, createInRegion and poolName. create also takes input, region and poolName. An actor that declares input must get it in create and getOrCreate. See SQLite And Migrations.
  • fork copies an existing actor into a new one. See Forking.
  • A handle has resolve, which succeeds with the actor ID, and getGatewayUrl, which succeeds with the raw URL that routes traffic to the actor. issueToken issues a token scoped to the actor. Without permissions, the token can only read through the actor gateway. To issue a token with any grants for the namespace, use auth.issueToken of the Client.Client service. See Scoped Tokens.

Connection Parameters

If the actor contract declares connection, each accessor method takes typed params:

The actor checks the params in authorize. If it refuses the connection, the call fails with the declared connection.error. See Connections And Events.

Subscribing to Events

connection.events has one Stream of decoded payloads for each event of the contract:

import { Effect, Fiber, Stream } from "effect";
import { Counter } from "./api";

export const program = Effect.gen(function* () {
	const counter = (yield* Counter.client).getOrCreate("my-counter");
	const connection = yield* counter.connect;

	// Start the stream before the calls, so it gets the events they cause.
	const changes = yield* connection.events.CountChanged.pipe(
		Stream.take(2),
		Stream.runCollect,
		Effect.forkScoped({ startImmediately: true }),
	);

	yield* connection.Increment({ amount: 1 });
	yield* connection.Increment({ amount: 2 });

	for (const { count } of yield* Fiber.join(changes)) {
		yield* Effect.log(`Count changed: ${count}`);
	}
}).pipe(Effect.scoped);

A stream subscribes when it starts and ends when the connection closes.

Connection Lifecycle

A connection lives in a Scope. handle.connect opens it, and it closes when the scope closes, for example at the end of Effect.scoped.

  • connect fails with the declared connection.error if authorize refuses the connection, and with a RivetError if the connection cannot open.
  • The connection reconnects after a transient failure. A reconnect makes a new connection on the actor, with a new id.
  • Interrupting an action call drops the action if it is still queued while the connection opens or reconnects. An action already sent can still run on the actor.
  • An event stream fails with a RivetError if the connection drops and cannot reconnect.
  • If the actor’s canSubscribe refuses a subscription, RivetKit closes the connection, and each event stream of the connection fails with the RivetError auth.forbidden.

Low-Level HTTP & WebSocket

For actors that implement the http or webSocket handler, call them directly:

import { Effect } from "effect";
import { Socket } from "effect/socket";
import { Counter } from "./api";

export const program = Effect.gen(function* () {
	const counter = (yield* Counter.client).getOrCreate("my-counter");

	// Raw HTTP request
	const response = yield* counter.fetch("/history");
	yield* Effect.log(yield* Effect.promise(() => response.json()));

	// Raw WebSocket connection
	const socket = yield* counter.webSocket("/stream");
	const { write } = yield* socket.writer;
	const pull = yield* Socket.readerString(socket);
	yield* write("hello");
	yield* Effect.log(yield* pull);
}).pipe(Effect.scoped);
  • handle.fetch(input, init) takes a path, or a URL or Request whose path is used. It succeeds with the response for any status. It fails with a RivetError if the actor cannot be reached. Interruption aborts the request.
  • handle.webSocket(path, protocols) gives a Socket from effect/socket. It connects when its reader is acquired and closes with the scope of that reader.
  • If the actor cannot be reached, the reader fails with a SocketOpenError whose cause is the RivetError.

Calling from Backend

In an Effect backend, provide Client.layer with your other layers and yield MyActor.client where you need it. In a backend that is not an Effect program, make a ManagedRuntime and run each call on it:

import { Client } from "@rivetkit/effect";
import { Effect, ManagedRuntime } from "effect";
import { Counter } from "./api";

// Build the client one time and share it between requests.
const runtime = ManagedRuntime.make(
	Client.layer({ endpoint: "http://localhost:6420" }),
);

export const increment = (amount: number): Promise<number> =>
	runtime.runPromise(
		Effect.gen(function* () {
			const counter = (yield* Counter.client).getOrCreate(
				"server-counter",
			);
			return yield* counter.Increment({ amount });
		}),
	);

To call an actor from another actor, see Actions And Errors.

Error Handling

An action call fails with one of these:

  • A declared error of the action, with its own tag. See Actions And Errors.
  • A RivetError for all other failures. Its reason is a tagged value, such as ActorNotFound, ActionTimedOut, Forbidden or InternalError.
import { Effect } from "effect";
import { Counter } from "./api";

export const program = Effect.gen(function* () {
	const counter = (yield* Counter.client).get("my-counter");

	const count = yield* counter.Increment({ amount: 1 }).pipe(
		// A declared error of the action.
		Effect.catchTag("CounterOverflow", ({ limit }) =>
			Effect.succeed(limit),
		),
		// All other failures.
		Effect.catchTag("RivetError", (error) =>
			error.reason._tag === "ActorNotFound"
				? Effect.succeed(0)
				: Effect.fail(error),
		),
	);
	yield* Effect.log(`Count: ${count}`);
});

error.isRetryable says if a retry can succeed. error.retryAfter has the delay to wait, if the reason has one.

Concepts

Keys

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

import { Effect } from "effect";
import { Counter } from "./api";

export const program = Effect.gen(function* () {
	const counters = yield* Counter.client;

	// Compound key: [org, room]
	const counter = counters.getOrCreate(["org-acme", "general"]);
	yield* counter.Increment({ amount: 1 });
});

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

Configuration

Client.layer takes the connection options:

import { Client } from "@rivetkit/effect";

export const ClientLayer = Client.layer({
	endpoint: "https://api.rivet.dev",
	namespace: "my-namespace",
	token: "<scoped-token>",
	poolName: "my-pool",
	headers: { "x-custom": "value" },
});
  • endpoint - URL of the control plane. Falls back to RIVET_ENDPOINT. It accepts the same URL auth syntax, so https://my-namespace:my-token@api.rivet.dev sets the namespace and token in one value.
  • namespace - target namespace. Falls back to RIVET_NAMESPACE.
  • token - authentication token for the control plane. Falls back to RIVET_TOKEN.
  • getToken - function that issues and renews a token on demand. It overrides token.
  • poolName - node pool that new actors are created in. Falls back to RIVET_POOL.
  • headers - extra HTTP headers sent with each request.

See Endpoints for details.

Writing Actors

With the Effect SDK, you write Rivet Actors as Effect programs. Actions, events, params and errors are values with effect/Schema types, so the server and the client share one validated contract. Actor features such as SQLite, schedules and connections are Effect services.

Contract And Implementation

Actor.make declares the contract: the name of the actor and its actions, events, creation input and connection params. It has no server code, so client code can import it. MyActor.toLayer adds the implementation and makes a layer that you serve with Registry.serve.

export const Hit = Action.make("Hit", { success: Schema.Number });

export const HitCounter = Actor.make("HitCounter", {
	actions: [Hit],
});

The first argument of toLayer is the wake effect. It runs each time the actor wakes, which includes the first start after the actor is created. It returns the action handlers:

export const HitCounterLive = HitCounter.toLayer(
	Effect.gen(function* () {
		// In-memory data. The actor loses it when it sleeps.
		const hits = yield* Ref.make(0);

		yield* Effect.addFinalizer(() =>
			Ref.get(hits).pipe(
				Effect.flatMap((count) =>
					Effect.log(`Sleeping after ${count} hits`),
				),
			),
		);

		return HitCounter.of({
			Hit: () => Ref.updateAndGet(hits, (count) => count + 1),
		});
	}),
);
  • Values that the wake effect makes stay in memory until the actor sleeps. Store durable data in SQLite.
  • MyActor.of(handlers) checks that there is one handler for each action of the contract. If the actor needs no setup, pass it to toLayer directly.
  • The wake effect runs in a scope that closes when the actor sleeps or is destroyed. Add cleanup with Effect.addFinalizer. Fibers that you fork into the scope are interrupted when it closes. For cleanup that runs only when the actor is destroyed, see onDestroy.
  • A service that the SDK does not provide becomes a requirement of the actor layer. Provide it with Layer.provide. The services on MyActor, such as MyActor.sql, belong to one actor. They do not compile in the wake effect or the handlers of a different actor.

Actions And Errors

Action.make declares an action with schemas for its payload, its success and its errors, and MyActor.of takes one handler for each action. An actor calls another actor with OtherActor.client, the same API that an application uses:

import { Action, Actor, Client } from "@rivetkit/effect";
import { Effect, Layer, Schema } from "effect";

export class BannedWord extends Schema.TaggedError<BannedWord>()("BannedWord", {
	word: Schema.String,
}) {}

export const Review = Action.make("Review", {
	payload: { text: Schema.String },
	error: BannedWord,
});

export const Moderator = Actor.make("Moderator", {
	actions: [Review],
});

export const Post = Action.make("Post", {
	payload: { text: Schema.String },
	error: BannedWord,
});

export const Feed = Actor.make("Feed", {
	actions: [Post],
});

export const ModeratorLive = Moderator.toLayer(
	Moderator.of({
		Review: ({ payload }) =>
			payload.text.includes("spam")
				? Effect.fail(new BannedWord({ word: "spam" }))
				: Effect.void,
	}),
);

export const FeedLive = Feed.toLayer(
	Effect.gen(function* () {
		const moderators = yield* Moderator.client;

		return Feed.of({
			// `BannedWord` from `Review` reaches the caller of `Post`.
			Post: ({ payload }) =>
				moderators
					.getOrCreate("main")
					.Review({ text: payload.text })
					.pipe(Effect.catchTag("RivetError", Effect.die)),
		});
	}),
);

export const ActorsLayer = Layer.mergeAll(ModeratorLive, FeedLive).pipe(
	Layer.provide(Client.layer({ endpoint: "http://localhost:6420" })),
);
  • success defaults to Schema.Void. For more than one declared error, use Schema.Union. A payload that does not decode fails the call before the handler runs.
  • A handler can fail only with the declared error of its action. Handle all other errors in the handler, for example with Effect.orDie. A defect reaches the caller as a RivetError without its cause. The actor logs the cause.
  • An actor layer that uses a client requires Client. Provide Client.layer to the actor layers. A declared error of the called action passes through the calling action only if the calling action declares it too.
  • onBeforeActionResponse in the hooks of MyActor.of(handlers, hooks) changes the success of an action before the caller gets it. Each key is an action tag. The hook does not run when the handler fails.

See Actions for the concept and Error Handling for the caller side.

SQLite And Migrations

Declare db in the toLayer options to give the actor a SQLite database, then yield MyActor.sql, the SqlClient of effect/sql, to query it. onCreate gets the decoded creation input. onMigrate in the toLayer options runs each time the actor starts, for schema migrations that are safe to repeat:

import { Action, Actor, db } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const GetOwner = Action.make("GetOwner", {
	success: Schema.String,
});

export const Workspace = Actor.make("Workspace", {
	actions: [GetOwner],
	input: Schema.Struct({ owner: Schema.String }),
});

export const WorkspaceLive = Workspace.toLayer(
	Effect.gen(function* () {
		const sql = yield* Workspace.sql;

		return Workspace.of({
			GetOwner: () =>
				sql<{ owner: string }>`SELECT owner FROM workspace`.pipe(
					Effect.map(([{ owner }]) => owner),
					Effect.orDie,
				),
		});
	}),
	{
		db: db({
			onMigrate: async (client) => {
				await client.execute(
					"CREATE TABLE IF NOT EXISTS workspace (owner TEXT NOT NULL)",
				);
			},
		}),
		// RivetKit does not keep the input, so store what later wakes need.
		onCreate: ({ owner }) =>
			Effect.gen(function* () {
				const sql = yield* Workspace.sql;
				yield* sql`INSERT INTO workspace (owner) VALUES (${owner})`;
			}).pipe(Effect.orDie),
	},
);

sql.withTransaction runs an effect in one transaction. If the effect fails, the transaction rolls back:

Transfer: ({ payload }) =>
	sql
		.withTransaction(
			Effect.gen(function* () {
				yield* sql`UPDATE accounts SET balance = balance - ${payload.amount} WHERE name = ${payload.from}`;
				yield* sql`UPDATE accounts SET balance = balance + ${payload.amount} WHERE name = ${payload.to}`;
			}),
		)
		.pipe(Effect.orDie),

Each time an actor starts, the SDK runs these steps in order:

  1. The onMigrate of the db provider.
  2. onMigrate from the toLayer options.
  3. onCreate from the toLayer options, only on the start that creates the actor. On the first start of a fork, onFork runs in its place. See Forking.
  4. The wake effect.
  • Only an actor that declares db gets MyActor.sql. In an actor without db, the program does not compile.
  • A query can fail with a SqlError. An action handler cannot fail with it, so turn it into a defect with Effect.orDie, or map it to a declared error.
  • Handlers of one actor can run concurrently. Use sql.withTransaction for writes that must stay together.
  • onCreate and onMigrate cannot use the services that need an awake actor, such as schedule, events and Actor.sleep. RivetKit stops waiting for onCreate after 5 seconds and for onMigrate after the onMigrateTimeout actor option. A defect in either stops the actor before it wakes.
  • Columns that have the same name merge into one in a result row. Give them aliases, for example SELECT a.id AS a_id, b.id AS b_id.

See SQLite and Input Parameters for the concepts. To pass the input from a client, see Getting Actors.

Forking

fork on the accessor of MyActor.client copies an actor into a new actor. The new actor starts on a copy of the source’s database, runs onFork from the toLayer options one time, and then runs independently of the source:

import { Action, Actor, db } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const GetAuthors = Action.make("GetAuthors", {
	success: Schema.Array(Schema.String),
});

export const GetForkedFrom = Action.make("GetForkedFrom", {
	success: Schema.Array(Schema.String),
});

export const Draft = Actor.make("Draft", {
	actions: [GetAuthors, GetForkedFrom],
	input: Schema.Struct({ author: Schema.String }),
});

const addAuthor = Effect.fn("Draft.addAuthor")(function* (author: string) {
	const sql = yield* Draft.sql;
	yield* sql`INSERT INTO authors (name) VALUES (${author})`;
});

export const DraftLive = Draft.toLayer(
	Effect.gen(function* () {
		const sql = yield* Draft.sql;
		const address = yield* Actor.CurrentAddress;

		return Draft.of({
			GetAuthors: () =>
				sql<{ name: string }>`SELECT name FROM authors`.pipe(
					Effect.map((rows) => rows.map((row) => row.name)),
					Effect.orDie,
				),
			// The actor IDs this draft was forked from, oldest first.
			GetForkedFrom: () =>
				Effect.succeed(address.forkChain.map((link) => link.actorId)),
		});
	}),
	{
		db: db({
			onMigrate: async (client) => {
				await client.execute(
					"CREATE TABLE IF NOT EXISTS authors (name TEXT NOT NULL)",
				);
			},
		}),
		onCreate: ({ author }) => addAuthor(author).pipe(Effect.orDie),
		// Runs in place of `onCreate` on the first start of a fork, on a copy of the source's database.
		onFork: ({ input }) => addAuthor(input.author).pipe(Effect.orDie),
	},
);

export const program = Effect.gen(function* () {
	const drafts = yield* Draft.client;

	const original = yield* drafts.create("post-1", {
		input: { author: "alice" },
	});
	const copy = yield* drafts.fork(yield* original.resolve, {
		key: "post-1-edit",
		input: { author: "bob" },
	});

	// ["alice", "bob"]: the copied row and the row of `onFork`.
	yield* Effect.log(yield* copy.GetAuthors());
	yield* Effect.log(yield* copy.GetForkedFrom());
});
  • onFork gets the source actor’s actorId and key, the forkedAt time, and the fork input. The SDK decodes the input with the actor’s input schema, so an actor that declares input must get it in fork.
  • onFork runs in place of onCreate, with the same services. Input that does not decode, or a defect, fails the start of the fork.
  • A fork is not idempotent. A key that is already held fails with actor.duplicate_key.
  • Actor.CurrentAddress.forkChain lists the forks behind the actor, oldest first. It is empty for an actor that was never forked.
  • A namespace fork copies every actor of a namespace with the same actor IDs, and does not run onFork. Actor.CurrentAddress.namespace is the namespace the actor runs in, so an actor can compare it with a stored value to find out that it is a copy.

See Forking for the concepts and the token permissions that a fork needs.

Lifecycle And Background Work

An idle actor sleeps after its sleepTimeout, and the next call wakes it. Actor.sleep, Actor.keepAwake and Actor.destroy change that in the wake effect and in action handlers. The second argument of toLayer takes the RivetKit actor options, and Actor.CurrentAddress has the actorId, name, key, region, namespace and forkChain of the actor:

import { Action, Actor } from "@rivetkit/effect";
import { Effect, Scope } from "effect";

export const StartExport = Action.make("StartExport");
export const Pause = Action.make("Pause");
export const Delete = Action.make("Delete");

export const Exporter = Actor.make("Exporter", {
	actions: [StartExport, Pause, Delete],
});

// Stands in for real work.
const runExport = Effect.sleep("30 seconds");

export const ExporterLive = Exporter.toLayer(
	Effect.gen(function* () {
		const wakeScope = yield* Scope.Scope;
		const address = yield* Actor.CurrentAddress;
		yield* Effect.log(`Exporter ${address.key.join("/")} is awake`);

		return Exporter.of({
			/**
			 * Returns at once. The export runs in the background, and the
			 * actor stays awake until it finishes.
			 */
			StartExport: () =>
				runExport.pipe(
					Actor.keepAwake,
					Effect.forkIn(wakeScope),
					Effect.asVoid,
				),
			Pause: () => Actor.sleep,
			Delete: () => Actor.destroy,
		});
	}),
	{
		name: "Exporter",
		icon: "file-export",
		sleepTimeout: "5 minutes",
		actionTimeout: "30 seconds",
	},
);
  • Actor.sleep puts the actor to sleep now. Actor.destroy destroys the actor and deletes its data. Neither finishes before the effect returns.
  • To run work in the background, fork a fiber into the wake scope, for example with Effect.forkScoped in the wake effect. The fiber is interrupted when the actor sleeps or is destroyed. It does not keep the actor awake, so wrap work that must finish in Actor.keepAwake.
  • Data that only a background fiber saves can be lost when the actor sleeps. Write data that must not be lost to SQLite in the action. For work that must survive sleep and crashes, use a workflow, a schedule or a cron job.
  • Timeouts and intervals in the options take a Duration.Input, such as "5 minutes". A number is milliseconds.

onDestroy in the hooks of MyActor.of runs when the actor is destroyed while it is awake. A finalizer on the wake scope runs on every sleep and destroy:

import { Action, Actor } from "@rivetkit/effect";
import { Effect } from "effect";

// Stand-in for a client of another system.
const openUpstream = (roomId: string) =>
	Effect.succeed({
		send: (text: string) => Effect.log(`${roomId}: ${text}`),
		close: Effect.log(`Closed the connection of ${roomId}`),
		deleteRoom: Effect.log(`Deleted ${roomId} upstream`),
	});

export const Send = Action.make("Send");

export const Room = Actor.make("Room", { actions: [Send] });

export const RoomLive = Room.toLayer(
	Effect.gen(function* () {
		const { actorId } = yield* Actor.CurrentAddress;
		const upstream = yield* openUpstream(actorId);

		// Runs on every sleep and destroy: this wake is over.
		yield* Effect.addFinalizer(() => upstream.close);

		return Room.of(
			{ Send: () => upstream.send("hello") },
			{
				// Runs only when the awake actor is destroyed: the actor is gone.
				onDestroy: upstream.deleteRoom,
			},
		);
	}),
);
  • Use a finalizer to release what this wake opened. Use onDestroy for cleanup that must not outlive the actor.
  • onDestroy runs after onDisconnect for each closing connection and before the finalizers, so the values of the wake effect and SQLite still work. RivetKit stops waiting for it after sleepGracePeriod. A failure is logged and the actor is destroyed anyway.
  • onDestroy is best effort. A sleeping actor is destroyed without a wake, and a crash takes the sleep path, so onDestroy does not run. Do not rely on it for a delete that must happen.

See Lifecycle and Destroying Actors for the concepts.

Schedule And Cron

yield* MyActor.schedule schedules one call of an action of the actor, and yield* MyActor.cron manages recurring jobs. RivetKit stores both, so they survive sleep, restarts and upgrades:

import { Action, Actor } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const Notify = Action.make("Notify", {
	payload: { text: Schema.String },
});

export const Remind = Action.make("Remind", {
	payload: { text: Schema.String },
	success: Schema.String,
});

export const Reminder = Actor.make("Reminder", {
	actions: [Remind, Notify],
});

export const ReminderLive = Reminder.toLayer(
	Effect.gen(function* () {
		const schedule = yield* Reminder.schedule;

		return Reminder.of({
			// Calls `Notify` in 10 minutes and returns the schedule id.
			Remind: ({ payload }) =>
				schedule
					.after("10 minutes", Notify, { text: payload.text })
					.pipe(Effect.orDie),
			Notify: ({ payload }) => Effect.log(payload.text),
		});
	}),
);
import { Action, Actor } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const Start = Action.make("Start");

export const SendDigest = Action.make("SendDigest", {
	payload: { channel: Schema.String },
});

export const Digest = Actor.make("Digest", {
	actions: [Start, SendDigest],
});

export const DigestLive = Digest.toLayer(
	Effect.gen(function* () {
		const cron = yield* Digest.cron;

		return Digest.of({
			// Calls `SendDigest` at 09:00 in Berlin, Monday to Friday.
			Start: () =>
				cron
					.set(
						{
							name: "weekday-digest",
							expression: "0 9 * * 1-5",
							timezone: "Europe/Berlin",
						},
						SendDigest,
						{ channel: "general" },
					)
					.pipe(Effect.orDie),
			SendDigest: ({ payload }) =>
				Effect.log(`Digest for ${payload.channel}`),
		});
	}),
);
MethodResult
schedule.after(delay, action, payload)Calls action after delay, a Duration.Input. Succeeds with a schedule id.
schedule.at(time, action, payload)Calls action at time, a DateTime or a Date. Succeeds with a schedule id.
schedule.cancel(id), schedule.get(id), schedule.listCancel, read or list the pending calls.
cron.set(options, action, payload)Calls action each time the five-field cron expression matches. timezone is an IANA time zone. The default is UTC.
cron.every(options, action, payload)Calls action one time for each interval, a Duration.Input of 5 seconds or more.
cron.get(name), cron.list, cron.delete(name), cron.history(name)Read, list or delete jobs, or read the most recent runs of a job.
  • A scheduled action or a job action runs like a client call, but its connection is None.
  • name in the cron options identifies the job. A job with a used name replaces the old job.
  • A stored call or job can stop decoding, for example after a payload schema change. get fails with an Actor.ScheduledCallDecodeError or an Actor.CronJobDecodeError for it. list skips it and logs a warning.
  • All methods fail with a RivetError if RivetKit rejects the call, for example when maxSchedules is full or an expression is not valid.

See Schedule & Cron for the concept.

Workflows

Workflow.make defines a workflow contract: an actor that also runs a durable workflow body. It takes the same options as Actor.make. RivetKit records each finished step, so the workflow continues where it stopped after a sleep, a crash or an upgrade:

import { Action, db, Workflow } from "@rivetkit/effect";
import { DateTime, Effect, Schema } from "effect";

export const GetStatus = Action.make("GetStatus", {
	success: Schema.String,
});

export const Order = Workflow.make("Order", {
	actions: [GetStatus],
});

export const OrderLive = Order.toLayer(
	Effect.gen(function* () {
		const sql = yield* Order.sql;

		const setStatus = Effect.fn("Order.setStatus")(function* (
			status: string,
		) {
			yield* sql`UPDATE orders SET status = ${status} WHERE id = 1`;
		});

		// Stands in for a call to a payment provider.
		const charge = Effect.fn("Order.charge")(function* () {
			yield* setStatus("paid");
			return yield* DateTime.now;
		});

		return Effect.gen(function* () {
			const paidAt = yield* Workflow.step("charge", charge(), {
				schema: Schema.DateTimeUtc,
				maxRetries: 5,
				timeout: "1 minute",
			});
			yield* Workflow.sleepUntil(
				"wait-for-shipping",
				DateTime.add(paidAt, { hours: 1 }),
			);
			yield* Workflow.step("ship", setStatus("shipped"));
		});
	}),
	{
		db: db({
			onMigrate: async (client) => {
				await client.execute(
					"CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY CHECK (id = 1), status TEXT NOT NULL)",
				);
				await client.execute(
					"INSERT OR IGNORE INTO orders (id, status) VALUES (1, 'new')",
				);
			},
		}),
		actions: Effect.gen(function* () {
			const sql = yield* Order.sql;

			return Order.of({
				GetStatus: () =>
					sql<{
						status: string;
					}>`SELECT status FROM orders WHERE id = 1`.pipe(
						Effect.map(([{ status }]) => status),
						Effect.orDie,
					),
			});
		}),
	},
);

Loop state, catch, ephemeral steps and onError:

import { Workflow } from "@rivetkit/effect";
import { Effect } from "effect";

// Stand-ins for calls to another system.
const readPageSize = Effect.succeed(100);
const fetchPage = (page: number, pageSize: number) =>
	Effect.succeed(page < 3 ? new Array<string>(pageSize).fill("item") : []);
const notifyOwner = (count: number) => Effect.log(`Synced ${count} items`);

export const Sync = Workflow.make("Sync");

export const SyncLive = Sync.toLayer(
	Effect.succeed(
		Effect.gen(function* () {
			// Saved with the next write, so a crash can run it again.
			const pageSize = yield* Workflow.step(
				"read-page-size",
				readPageSize,
				{ ephemeral: true },
			);

			// RivetKit saves the state after each iteration.
			const count = yield* Workflow.loop("pages", {
				state: { page: 0, count: 0 },
				run: ({ page, count }) =>
					Effect.gen(function* () {
						const items = yield* Workflow.step(
							"fetch",
							fetchPage(page, pageSize),
						);
						if (items.length === 0)
							return Workflow.Loop.break(count);
						return Workflow.Loop.continue({
							page: page + 1,
							count: count + items.length,
						});
					}),
			});

			// Only a timeout comes back as a value. Other failures fail the workflow.
			yield* Workflow.tryStep("notify", notifyOwner(count), {
				timeout: "10 seconds",
				catch: ["timeout"],
			}).pipe(
				Effect.catchTag("WorkflowStepFailure", () =>
					Effect.logWarning("The owner was not notified"),
				),
			);
		}),
	),
	{
		onError: (event) =>
			"step" in event
				? Effect.logWarning(
						`Step ${event.step.stepName} failed: ${event.step.error.message}`,
					)
				: Effect.void,
	},
);
EffectResult
Workflow.step(name, effect, options)Runs effect one time and saves the result. rollback in the options undoes the step when the workflow fails.
Workflow.tryStep(name, effect, options)Fails with a Workflow.StepFailure that the workflow can handle, where Workflow.step fails the workflow. catch in the options sets the kinds of failure that it returns.
Workflow.try(name, body, options)Fails with a Workflow.TryFailure when a step, join or race in body fails. catch in the options sets the kinds of failure that it returns.
Workflow.rollbackCheckpoint(name)Run it before the first step that has a rollback.
Workflow.sleep(name, duration), Workflow.sleepUntil(name, time)Save their deadline. If the actor sleeps, RivetKit wakes it at the deadline.
Workflow.loop(name, body)Runs body again and again until it succeeds with Workflow.loopBreak.
Workflow.loop(name, { state, run })Runs run with the state of the loop. run succeeds with Workflow.Loop.continue(next) or Workflow.Loop.break(value), and the loop succeeds with value.
Workflow.join(name, branches)Runs named branches concurrently and succeeds with the result of each branch.
Workflow.race(name, branches)Succeeds with the winner and the value of the first branch that finishes. The other branches are interrupted.
Workflow.getVersion(name, latest)Gives latest to a workflow that gets to the call for the first time, and 1 to a workflow that ran past this point before the call existed.
Workflow.removed(name, originalType)Stands in for a call that you deleted, for example a "step" or a "sleep".
  • The first argument of toLayer is an effect that succeeds with the workflow body. actions in the toLayer options takes MyWorkflow.of(handlers), MyWorkflow.of(handlers, hooks), or an effect that succeeds with one. It is required if the contract declares actions or connection. Both effects run on each wake, before the body starts.
  • RivetKit runs the body again from the start on each wake. A finished step, sleep or loop iteration returns its saved result. Code outside a step must be deterministic, so put each side effect, and each read of the clock, of random values or of SQLite, in a Workflow.step.
  • Each step, sleep and loop needs a name that is unique in its scope. Run the Workflow effects one at a time. They compile only in the workflow body.
  • A step result must be JSON-compatible, or pass schema. RivetKit runs a failed step again, up to maxRetries times (default: 3), so make the effect idempotent. timeout (default: 30 seconds) fails the workflow unless you set retryOnTimeout.
  • ephemeral: true saves the result of a step with the next write of the workflow history instead of at once. If the actor stops before that write, the step runs again.
  • The state of a loop and its value must be JSON-compatible. RivetKit saves the state after each iteration, so the loop continues with it after the actor sleeps.
  • Without catch, Workflow.tryStep returns exhausted, timeout and critical failures, and Workflow.try returns step, join and race failures. Another kind of failure fails the workflow.
  • onError in the toLayer options runs when a step attempt, a rollback or the workflow fails. It gets the services of the wake effect. RivetKit does not replay it, so use it for logs, metrics and error reports.
  • The actor does not sleep from idle while the workflow runs or waits in Workflow.sleep. To delete the actor when the work is done, run Actor.destroy in the last step.

See Workflows for the concept.

Connections And Events

Declare connection in Actor.make to type the params that a client connects with and the error that refuses a connection. The hooks authorize, onConnect and onDisconnect go in the second argument of MyActor.of, and yield* MyActor.connections lists and closes the open connections:

import { Action, Actor } from "@rivetkit/effect";
import { Effect, Option, Schema } from "effect";

export class Refused extends Schema.TaggedError<Refused>()("Refused", {
	userId: Schema.String,
}) {}

export const WhoAmI = Action.make("WhoAmI", { success: Schema.String });

export const Kick = Action.make("Kick", {
	payload: { userId: Schema.String },
});

export const Room = Actor.make("Room", {
	actions: [WhoAmI, Kick],
	connection: {
		params: Schema.Struct({ userId: Schema.String }),
		error: Refused,
	},
});

export const RoomLive = Room.toLayer(
	Effect.gen(function* () {
		const connections = yield* Room.connections;

		return Room.of(
			{
				WhoAmI: ({ connection }) =>
					Option.match(connection, {
						onNone: () => Effect.die("WhoAmI needs a connection"),
						onSome: ({ params }) => Effect.succeed(params.userId),
					}),
				// Closes each open connection of the user.
				Kick: Effect.fn(function* ({ payload }) {
					const open = yield* connections.list;
					yield* Effect.forEach(
						open.filter(
							({ params }) => params.userId === payload.userId,
						),
						(connection) =>
							connections.disconnect(connection, "kicked"),
						{ discard: true },
					).pipe(Effect.orDie);
				}),
			},
			{
				authorize: ({ userId }) =>
					userId === "mallory"
						? Effect.fail(new Refused({ userId }))
						: Effect.void,
				onConnect: ({ params }) =>
					Effect.log(`${params.userId} joined`),
				onDisconnect: ({ params }) =>
					Effect.log(`${params.userId} left`),
			},
		);
	}),
);

Declare events with Event.make and add them to events in Actor.make. yield* MyActor.events sends them to every connection (broadcast) or to one connection (send):

import { Action, Actor, Event } from "@rivetkit/effect";
import { Effect, Option, Schema } from "effect";

export const ScoreChanged = Event.make("ScoreChanged", {
	payload: { score: Schema.Number },
});

export const Welcome = Event.make("Welcome");

export const Join = Action.make("Join");

export const SetScore = Action.make("SetScore", {
	payload: { score: Schema.Number },
});

export const Game = Actor.make("Game", {
	actions: [Join, SetScore],
	events: [ScoreChanged, Welcome],
});

export const GameLive = Game.toLayer(
	Effect.gen(function* () {
		const events = yield* Game.events;

		return Game.of({
			// Sends `Welcome` only to the caller.
			Join: ({ connection }) =>
				Option.match(connection, {
					onNone: () => Effect.void,
					onSome: (caller) => events.send(caller, Welcome),
				}),
			// Sends `ScoreChanged` to every connection.
			SetScore: ({ payload }) =>
				events.broadcast(ScoreChanged, { score: payload.score }),
		});
	}),
);

canSubscribe in the hooks of MyActor.of decides which connections can subscribe to an event. Each key is an event tag:

import { Action, Actor, Event } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const ScoreChanged = Event.make("ScoreChanged", {
	payload: { score: Schema.Number },
});

export const SetScore = Action.make("SetScore", {
	payload: { score: Schema.Number },
});

export const Match = Actor.make("Match", {
	actions: [SetScore],
	events: [ScoreChanged],
	connection: {
		params: Schema.Struct({
			role: Schema.Literals(["player", "spectator"]),
		}),
	},
});

export const MatchLive = Match.toLayer(
	Effect.gen(function* () {
		const events = yield* Match.events;

		return Match.of(
			{
				SetScore: ({ payload }) =>
					events.broadcast(ScoreChanged, { score: payload.score }),
			},
			{
				authorize: () => Effect.void,
				canSubscribe: {
					// Only players get the score.
					ScoreChanged: ({ params }) =>
						Effect.succeed(params.role === "player"),
				},
			},
		);
	}),
);
  • authorize is required when the actor declares connection. It runs before each connection opens, also for a stateless call, a raw HTTP request and a raw WebSocket connection. A failure refuses the connection, and the client gets the declared error. Params that do not decode refuse the connection with a RivetError before authorize runs.
  • canSubscribe runs before each subscription to its event, with the connection that subscribes. When it succeeds with false, RivetKit closes that connection with auth.forbidden, and each event stream of that connection fails with that RivetError. An event without a hook allows every connection.
  • onConnect runs after authorize accepts a connection. onDisconnect runs when that connection closes while the actor is awake. The hooks run only after the wake effect completes.
  • Each action request has connection, an Option with the id, the scope and the params of the caller. It is None for an action that the schedule or a cron job starts. The id is an address, not an identity. Do not use it for authorization.
  • The scope closes when the connection closes or the actor sleeps. Add a resource to that scope to release it at that time. Keep finalizers short, because RivetKit stops waiting for them after 5 seconds.

See Connections, Realtime and Authentication for the concepts. To connect and read events from an Effect program, see Connection Parameters and Subscribing to Events.

Raw HTTP And WebSocket

Pass http and webSocket in the hooks of MyActor.of to handle raw HTTP requests and raw WebSocket connections with effect/http and effect/socket:

import { Actor } from "@rivetkit/effect";
import { Effect } from "effect";
import { HttpServerRequest, HttpServerResponse } from "effect/http";
import { Socket } from "effect/socket";

export const Gateway = Actor.make("Gateway");

export const GatewayLive = Gateway.toLayer(
	Gateway.of(
		{},
		{
			// Answers each request with its method and URL as JSON.
			http: Effect.gen(function* () {
				const request = yield* HttpServerRequest.HttpServerRequest;
				return yield* HttpServerResponse.json({
					method: request.method,
					url: request.url,
				});
			}),
			// Sends each text message back until the client disconnects.
			webSocket: Effect.gen(function* () {
				const socket = yield* Socket.Socket;
				const { write } = yield* socket.writer;
				const pull = yield* Socket.readerString(socket);
				yield* pull.pipe(
					Effect.flatMap(Effect.forEach(write)),
					Effect.forever,
				);
			}),
		},
	),
);
  • http runs one time for each request. A failure becomes a 500 response. An actor without http answers 404.
  • webSocket runs one time for each connection. The WebSocket closes when the handler exits: normally on success, with code 1011 on a failure. When the client disconnects or the actor sleeps, the handler is interrupted.
  • In the webSocket handler, the request path keeps a /websocket prefix. In the http handler, the path has no prefix.

See Low-Level HTTP Handler and Low-Level WebSocket Handler for the concepts. To call the handlers from an Effect client, see Low-Level HTTP & WebSocket.

Registry And Testing

Registry.serve starts the actors of a layer, and Registry.layer holds the options that all the actors share. Merge the actor layers with Layer.mergeAll:

import { NodeRuntime } from "@effect/platform-node";
import { Registry } from "@rivetkit/effect";
import { Layer } from "effect";
import { GreeterLive, TranslatorLive } from "../actors-effect/services";
import { CounterLive } from "../actors-quickstart-effect/src/live";

const ActorsLayer = Layer.mergeAll(
	CounterLive,
	GreeterLive.pipe(Layer.provide(TranslatorLive)),
);

const MainLayer = Registry.serve(ActorsLayer).pipe(
	Layer.provide(
		Registry.layer({
			endpoint: "https://api.rivet.dev",
			namespace: "my-namespace",
			token: process.env.RIVET_TOKEN,
			noWelcome: true,
		}),
	),
);

Layer.launch(MainLayer).pipe(NodeRuntime.runMain);
OptionUseDefault
endpointThe URL of the control plane.RIVET_ENDPOINT
namespaceThe namespace of the actors.RIVET_NAMESPACE
tokenThe token for the control plane.RIVET_TOKEN
noWelcomeSet to true to hide the welcome message at startup.false
sqliteThe SQLite backend, "local" or "remote".
startEngineSet to true to start a local control plane.RIVET_RUN_ENGINE
startServicesSet to false to not start Services with a local control plane.RIVET_RUN_SERVICES
runtimeThe RivetKit runtime, "auto", "native" or "wasm".RIVETKIT_RUNTIME
node.versionThe version of this node. Increase it on every deploy.RIVET_NODE_VERSION

Registry.prometheusMetrics and Registry.health are effect/http handlers that answer with the Prometheus metrics and the health of the registry. Before the registry starts, they answer 503. A node that runs on its own, for example in a Docker image, sets startEngine: false, startServices: false and runtime: "native", serves its metrics on a private port and its health on the public one:

import { createServer } from "node:http";
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
import { Registry } from "@rivetkit/effect";
import { Layer } from "effect";
import { HttpRouter } from "effect/http";
import { CounterLive } from "../actors-quickstart-effect/src/live";

// Serves the metrics of this node on a private port.
const MetricsServer = HttpRouter.add(
	"GET",
	"/metrics",
	Registry.prometheusMetrics,
).pipe(
	HttpRouter.serve,
	Layer.provide(
		NodeHttpServer.layer(createServer, {
			host: "127.0.0.1",
			port: Number(process.env.RIVETKIT_METRICS_PORT ?? 9464),
		}),
	),
);

// Serves the app routes and the health of this node on the public port.
const AppServer = HttpRouter.add("GET", "/health", Registry.health).pipe(
	HttpRouter.serve,
	Layer.provide(
		NodeHttpServer.layer(createServer, {
			port: Number(process.env.PORT ?? 8080),
		}),
	),
);

const MainLayer = Layer.mergeAll(
	Registry.serve(CounterLive),
	MetricsServer,
	AppServer,
).pipe(
	Layer.provide(
		Registry.layer({
			startEngine: false,
			startServices: false,
			runtime: "native",
		}),
	),
);

Layer.launch(MainLayer).pipe(NodeRuntime.runMain);

Registry.test is a layer that starts the registry in the test process and provides a Client for it:

import { Registry } from "@rivetkit/effect";
import { Effect, Layer } from "effect";
import { expect, test } from "vitest";
import { Counter } from "../actors-quickstart-effect/src/api";
import { CounterLive } from "../actors-quickstart-effect/src/live";

const TestLayer = Registry.test.pipe(
	Layer.provideMerge(CounterLive),
	Layer.provide(Registry.layer()),
);

test("increments the count", () =>
	Effect.gen(function* () {
		const counter = (yield* Counter.client).getOrCreate(
			crypto.randomUUID(),
		);

		yield* counter.Increment({ amount: 2 });
		const count = yield* counter.Increment({ amount: 3 });

		expect(count).toBe(5);
	}).pipe(Effect.provide(TestLayer), Effect.runPromise));
  • Run the program with NodeRuntime.runMain. On SIGINT or SIGTERM, it closes the layer. That shuts down the registry and puts its actors to sleep.
  • If Registry.layer has neither endpoint nor startEngine, Registry.test starts a local control plane. Use a new key for each test, so that tests do not share actor data. Actors that call other actors still need Client.layer with the endpoint of the same control plane.
  • Effect.log works in the wake effect, in action handlers and in hooks. The SDK adds the actor, key and actorId to each log line. RIVET_LOG_LEVEL sets the minimum level. To use your own Pino logger, provide RivetLogger.layerFromPino. For the client logs, provide it to the program that uses Client.layer.
  • The SDK makes a span for each action call, for example Counter/Increment. To export the spans, provide an Effect tracer layer. A call from an Effect client or from another actor joins the trace of the caller.

See Registry Configuration, Testing, Logging and Tracing for more information.

Raw Escape Hatch

For a RivetKit feature that has no Effect API, pass a function to toLayer. Its argument has rawRivetkitContext, the RivetKit context of the actor. In a workflow body, Workflow.Workflow has the rawRivetkitContext of the workflow:

import { Action, Actor } from "@rivetkit/effect";
import { Effect, Schema } from "effect";

export const Ping = Action.make("Ping", {
	payload: { url: Schema.String },
	success: Schema.Number,
});

export const Probe = Actor.make("Probe", {
	actions: [Ping],
});

export const ProbeLive = Probe.toLayer(({ rawRivetkitContext }) =>
	Probe.of({
		// Aborts the request when the actor shuts down.
		Ping: ({ payload }) =>
			Effect.promise(() =>
				fetch(payload.url, { signal: rawRivetkitContext.abortSignal }),
			).pipe(Effect.map((response) => response.status)),
	}),
);
  • The raw context and the Effect APIs use the same actor.
  • The SDK does not validate calls through rawRivetkitContext with effect/Schema. The types are those of the RivetKit API.

Not Available Yet

  • Contract middleware. There is no middleware in the style of Effect’s RpcMiddleware. It waits because effect/rpc is marked unstable in Effect 4.x. For auth, use authorize.
  • waitUntil and the abort signal. Use fibers in the wake scope, Actor.keepAwake and Effect interruption.

API Reference

Package: @rivetkit/effect

Edit this page Last updated November 26, 2026