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,getandgetForIdreturn a handle at once. The client finds the actor on the first call.createis an effect. It fails with aRivetErrorif an actor for the key exists.getOrCreatealso takescreateWithInput,createInRegionandpoolName.createalso takesinput,regionandpoolName. An actor that declaresinputmust get it increateandgetOrCreate. See SQLite And Migrations.forkcopies an existing actor into a new one. See Forking.- A handle has
resolve, which succeeds with the actor ID, andgetGatewayUrl, which succeeds with the raw URL that routes traffic to the actor.issueTokenissues a token scoped to the actor. Withoutpermissions, the token can only read through the actor gateway. To issue a token with any grants for the namespace, useauth.issueTokenof theClient.Clientservice. See Scoped Tokens.
Connection Parameters
If the actor contract declares connection, each accessor method takes typed params:
import { Effect } from "effect";
import { Room } from "./room";
export const program = Effect.gen(function* () {
const room = (yield* Room.client).getOrCreate("general", {
params: { authToken: "jwt-token-here" },
});
const history = yield* room
.GetHistory()
.pipe(Effect.catchTag("Unauthorized", () => Effect.succeed([])));
yield* Effect.log(`${history.length} messages`);
});
import { Action, Actor } from "@rivetkit/effect";
import { Schema } from "effect";
export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
"Unauthorized",
{},
) {}
export const GetHistory = Action.make("GetHistory", {
success: Schema.Array(Schema.String),
});
export const Room = Actor.make("Room", {
actions: [GetHistory],
connection: {
params: Schema.Struct({ authToken: Schema.String }),
error: Unauthorized,
},
});
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.
connectfails with the declaredconnection.errorifauthorizerefuses the connection, and with aRivetErrorif 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
RivetErrorif the connection drops and cannot reconnect. - If the actor’s
canSubscriberefuses a subscription, RivetKit closes the connection, and each event stream of the connection fails with theRivetErrorauth.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 orRequestwhose path is used. It succeeds with the response for any status. It fails with aRivetErrorif the actor cannot be reached. Interruption aborts the request.handle.webSocket(path, protocols)gives aSocketfromeffect/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
SocketOpenErrorwhose cause is theRivetError.
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
RivetErrorfor all other failures. Itsreasonis a tagged value, such asActorNotFound,ActionTimedOut,ForbiddenorInternalError.
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 toRIVET_ENDPOINT. It accepts the same URL auth syntax, sohttps://my-namespace:my-token@api.rivet.devsets the namespace and token in one value.namespace- target namespace. Falls back toRIVET_NAMESPACE.token- authentication token for the control plane. Falls back toRIVET_TOKEN.getToken- function that issues and renews a token on demand. It overridestoken.poolName- node pool that new actors are created in. Falls back toRIVET_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 totoLayerdirectly.- 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, seeonDestroy. - A service that the SDK does not provide becomes a requirement of the actor layer. Provide it with
Layer.provide. The services onMyActor, such asMyActor.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" })),
);
successdefaults toSchema.Void. For more than one declared error, useSchema.Union. A payload that does not decode fails the call before the handler runs.- A handler can fail only with the declared
errorof its action. Handle all other errors in the handler, for example withEffect.orDie. A defect reaches the caller as aRivetErrorwithout its cause. The actor logs the cause. - An actor layer that uses a client requires
Client. ProvideClient.layerto the actor layers. A declared error of the called action passes through the calling action only if the calling action declares it too. onBeforeActionResponsein the hooks ofMyActor.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:
- The
onMigrateof thedbprovider. onMigratefrom thetoLayeroptions.onCreatefrom thetoLayeroptions, only on the start that creates the actor. On the first start of a fork,onForkruns in its place. See Forking.- The wake effect.
- Only an actor that declares
dbgetsMyActor.sql. In an actor withoutdb, 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 withEffect.orDie, or map it to a declared error. - Handlers of one actor can run concurrently. Use
sql.withTransactionfor writes that must stay together. onCreateandonMigratecannot use the services that need an awake actor, such asschedule,eventsandActor.sleep. RivetKit stops waiting foronCreateafter 5 seconds and foronMigrateafter theonMigrateTimeoutactor 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());
});
onForkgets the source actor’sactorIdandkey, theforkedAttime, and the forkinput. The SDK decodes the input with the actor’sinputschema, so an actor that declaresinputmust get it infork.onForkruns in place ofonCreate, with the same services. Input that does not decode, or a defect, fails the start of the fork.- A fork is not idempotent. A
keythat is already held fails withactor.duplicate_key. Actor.CurrentAddress.forkChainlists 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.namespaceis 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.sleepputs the actor to sleep now.Actor.destroydestroys 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.forkScopedin 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 inActor.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
onDestroyfor cleanup that must not outlive the actor. onDestroyruns afteronDisconnectfor each closing connection and before the finalizers, so the values of the wake effect and SQLite still work. RivetKit stops waiting for it aftersleepGracePeriod. A failure is logged and the actor is destroyed anyway.onDestroyis best effort. A sleeping actor is destroyed without a wake, and a crash takes the sleep path, soonDestroydoes 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}`),
});
}),
);
| Method | Result |
|---|---|
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.list | Cancel, 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
connectionisNone. namein 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.
getfails with anActor.ScheduledCallDecodeErroror anActor.CronJobDecodeErrorfor it.listskips it and logs a warning. - All methods fail with a
RivetErrorif RivetKit rejects the call, for example whenmaxSchedulesis 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,
},
);
| Effect | Result |
|---|---|
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
toLayeris an effect that succeeds with the workflow body.actionsin thetoLayeroptions takesMyWorkflow.of(handlers),MyWorkflow.of(handlers, hooks), or an effect that succeeds with one. It is required if the contract declares actions orconnection. 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
Workfloweffects 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 tomaxRetriestimes (default: 3), so make the effect idempotent.timeout(default: 30 seconds) fails the workflow unless you setretryOnTimeout. ephemeral: truesaves 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
valuemust be JSON-compatible. RivetKit saves the state after each iteration, so the loop continues with it after the actor sleeps. - Without
catch,Workflow.tryStepreturnsexhausted,timeoutandcriticalfailures, andWorkflow.tryreturnsstep,joinandracefailures. Another kind of failure fails the workflow. onErrorin thetoLayeroptions 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, runActor.destroyin 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"),
},
},
);
}),
);
authorizeis required when the actor declaresconnection. 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 declarederror. Params that do not decode refuse the connection with aRivetErrorbeforeauthorizeruns.canSubscriberuns before each subscription to its event, with the connection that subscribes. When it succeeds withfalse, RivetKit closes that connection withauth.forbidden, and each event stream of that connection fails with thatRivetError. An event without a hook allows every connection.onConnectruns afterauthorizeaccepts a connection.onDisconnectruns when that connection closes while the actor is awake. The hooks run only after the wake effect completes.- Each action request has
connection, anOptionwith theid, thescopeand theparamsof the caller. It isNonefor an action that the schedule or a cron job starts. Theidis an address, not an identity. Do not use it for authorization. - The
scopecloses 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,
);
}),
},
),
);
httpruns one time for each request. A failure becomes a500response. An actor withouthttpanswers404.webSocketruns one time for each connection. The WebSocket closes when the handler exits: normally on success, with code1011on a failure. When the client disconnects or the actor sleeps, the handler is interrupted.- In the
webSockethandler, the request path keeps a/websocketprefix. In thehttphandler, 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);
| Option | Use | Default |
|---|---|---|
endpoint | The URL of the control plane. | RIVET_ENDPOINT |
namespace | The namespace of the actors. | RIVET_NAMESPACE |
token | The token for the control plane. | RIVET_TOKEN |
noWelcome | Set to true to hide the welcome message at startup. | false |
sqlite | The SQLite backend, "local" or "remote". | |
startEngine | Set to true to start a local control plane. | RIVET_RUN_ENGINE |
startServices | Set to false to not start Services with a local control plane. | RIVET_RUN_SERVICES |
runtime | The RivetKit runtime, "auto", "native" or "wasm". | RIVETKIT_RUNTIME |
node.version | The 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. OnSIGINTorSIGTERM, it closes the layer. That shuts down the registry and puts its actors to sleep. - If
Registry.layerhas neitherendpointnorstartEngine,Registry.teststarts 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 needClient.layerwith the endpoint of the same control plane. Effect.logworks in the wake effect, in action handlers and in hooks. The SDK adds theactor,keyandactorIdto each log line.RIVET_LOG_LEVELsets the minimum level. To use your own Pino logger, provideRivetLogger.layerFromPino. For the client logs, provide it to the program that usesClient.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
rawRivetkitContextwitheffect/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 becauseeffect/rpcis marked unstable in Effect 4.x. For auth, useauthorize. waitUntiland the abort signal. Use fibers in the wake scope,Actor.keepAwakeand Effect interruption.
API Reference
Package: @rivetkit/effect