effect-actors-node
v0.0.1
Published
Node.js platform composition for effect-actors
Readme
effect-actors
Durable, typed actors that run inside your own Effect application. There is no separate control plane: you define actors in code, compose them into Layers, and run them in your processes on top of effect/unstable/cluster.
Two actor kinds:
- State actors own framework-managed state. A command turns a pure reducer result into one SQL transaction that commits the next state, an immutable receipt, emitted events, timer changes, and outbox intents — before the reply reaches the client.
- Hosted actors supervise application-supplied authority inside an actor scope. Your service keeps its own durability; the framework provides addressing, lifecycle, and a typed client around it.
Status
The three packages release together at 0.0.1 and require the Effect 4.0.0-rc.112 family pinned exactly, including @effect/platform-node-shared. Bun is pinned to 1.4.0; the Node package needs Node >= 24.
Packages are published only by the tagged release workflow on GitHub Actions — see docs/release.md.
Packages
| Package | Contents |
| -------------------- | -------------------------------------------------------------------------------------- |
| effect-actors | Actor definitions, typed clients, runtime services, SQL store, hosted actors, gateway. |
| effect-actors-bun | Bun + SQLite single runner; Bun + PostgreSQL cluster and client-only compositions. |
| effect-actors-node | Node + PostgreSQL single runner, cluster, and client-only compositions. |
Install
From source, until the first tag publishes:
git clone https://github.com/dallenpyrah/effect-actors.git
cd effect-actors
bun install --frozen-lockfile
bun run buildAfter publication, pin the whole Effect family exactly — a mixed prerelease graph is not supported:
# Bun + SQLite
bun add --exact [email protected] @effect/[email protected] \
[email protected] [email protected]
# Node + PostgreSQL
npm install --save-exact [email protected] @effect/[email protected] \
[email protected] [email protected]Quickstart
A counter actor on Bun + SQLite. This program is complete and runnable; the CI suite typechecks and executes every TypeScript block on this page against the packed packages.
import { BunRuntime } from "@effect/platform-bun"
import { Effect, Layer, Result, Schema, Stream } from "effect"
import { Actor } from "effect-actors"
import { SqliteSingle } from "effect-actors-bun"
// Domain errors are schema-coded so they round-trip through receipts and the gateway.
class NonPositiveIncrement extends Schema.Error<NonPositiveIncrement>("NonPositiveIncrement")({
_tag: Schema.tag("NonPositiveIncrement"),
by: Schema.Int,
}) {}
const Counter = Actor.make("Counter", {
protocolVersion: 1,
state: {
version: 1,
schema: Schema.Struct({ count: Schema.Int }),
initial: () => ({ count: 0 }),
migrations: [],
},
events: Schema.Struct({ _tag: Schema.Literal("Incremented"), count: Schema.Int }),
})
// Reducers are synchronous and pure. A transition is data: next state, reply
// value, events, timers, outbox calls — committed in one transaction.
.command("increment", {
payload: Schema.Struct({ by: Schema.Int }),
success: Schema.Struct({ count: Schema.Int }),
error: NonPositiveIncrement,
reduce: (state, { by }) => {
if (by <= 0) return Result.fail(new NonPositiveIncrement({ by }))
const count = state.count + by
return Result.succeed({
state: { count },
value: { count },
events: [{ _tag: "Incremented" as const, count }],
})
},
})
.query("read", {
payload: Schema.Null,
success: Schema.Struct({ count: Schema.Int }),
error: Schema.Never,
read: (state) => Result.succeed({ count: state.count }),
})
const database = { filename: "./counter.sqlite" }
const store = { tablePrefix: "actors" }
// `Counter.toLayer()` registers the actor; `SqliteSingle.layer` provides the
// runtime, SQL store, cluster runner, and typed `Client` service.
const MainLive = Counter.toLayer().pipe(
Layer.provideMerge(
SqliteSingle.layer({
database,
store,
runtime: {
namespace: "demo",
maxCommandBytes: 16_384,
maxStateBytes: 16_384,
maxEventBytes: 4_096,
maxEventsPerTurn: 16,
maxOutboxCallsPerTurn: 16,
maxTimerChangesPerTurn: 16,
maxTurnDuration: "5 seconds",
actorLeaseDuration: "30 seconds",
actorLeaseRenewEvery: "10 seconds",
},
}),
),
)
const program = Effect.gen(function* () {
const counterFor = yield* Counter.client
const counter = counterFor({ tenant: "acme", key: ["billing"] })
const before = yield* counter.queries.read(null)
// `commandId` is the idempotency identity for this actor address — derive it
// from the caller's request so a retry replays the receipt instead of running again.
const command = { commandId: "req-0001", expectedRevision: before.revision }
const first = yield* counter.commands.increment({ by: 1 }, command)
const replay = yield* counter.commands.increment({ by: 1 }, command)
yield* Effect.logInfo("duplicate command replayed", first.revision === replay.revision)
// A query returns the projection plus an event cursor; subscribing after that
// cursor is a gap-free handoff from read model to stream.
yield* counter.events({ after: before.cursor }).pipe(
Stream.take(1),
Stream.runForEach((event) => Effect.logInfo("event committed", event)),
)
return yield* counter.queries.read(null)
})
// The store layer validates the framework schema when it is built, so
// `migrate` must complete before `Effect.provide` constructs `MainLive`.
// In production the migration is a separate deploy step, not part of startup.
BunRuntime.runMain(
SqliteSingle.migrate({ database, store }).pipe(
Effect.andThen(program.pipe(Effect.provide(MainLive))),
),
)For a long-lived runner — a process that hosts actors until it is stopped — merge each actor layer (and ActorRuntime.layerDispatchers when reducers use timers or outbox) over the platform layer, then hand it to Layer.launch:
BunRuntime.runMain(Layer.launch(RunnerLive)) or NodeRuntime.runMain(Layer.launch(RunnerLive)) keep the process alive and run finalizers on SIGINT/SIGTERM. SqliteSingle starts no runner listener, so it is strictly one actor-owning process.
Migrations stay a separate release step. migrate is a plain Effect, so the migration entrypoint is small:
import { BunRuntime } from "@effect/platform-bun"
import { SqliteSingle } from "effect-actors-bun"
BunRuntime.runMain(
SqliteSingle.migrate({
database: { filename: "./counter.sqlite" },
store: { tablePrefix: "actors" },
}),
)The runnable, CI-verified version of this walkthrough lives in examples/state-counter; bun run pack && bun run examples:check exercises all packaged examples end to end.
What a command commits
Commands serialize per actor address. On a successful reducer result the store writes — in one transaction — the next state and revision, the success receipt, events with cursor advancement, timer changes, and outbox intents. A typed domain failure writes a failure receipt and nothing else; an expectedRevision mismatch writes a RevisionConflict receipt without running the reducer.
| Retry | Result |
| ------------------------------------------- | ----------------------------------------------------------- |
| Same commandId, identical canonical input | Stored receipt returned; the reducer does not run again |
| Same commandId, changed input | CommandConflict — send a corrected request under a new ID |
| New commandId, stale expectedRevision | RevisionConflict failure receipt; state unchanged |
Retention is an operator policy: resuming an event stream below the retained floor fails with CursorExpired, and the client recovers from a fresh query projection. Outbox delivery is at-least-once — give target commands deterministic command IDs and idempotent handlers. The full contract, including address and identifier limits, is in docs/architecture/guarantees.md and docs/guides/state-actors.md.
Timers and outbox
A reducer can attach timers and outbox intents to its transition; they are durable with the commit but executed later by a dispatcher:
import { BunRuntime } from "@effect/platform-bun"
import { Effect, Layer, Result, Schema } from "effect"
import { Actor, ActorRuntime } from "effect-actors"
import { SqliteSingle } from "effect-actors-bun"
const Reminder = Actor.make("Reminder", {
protocolVersion: 1,
state: {
version: 1,
schema: Schema.Struct({ note: Schema.String, fired: Schema.Boolean }),
initial: () => ({ note: "", fired: false }),
migrations: [],
},
events: Schema.Struct({ _tag: Schema.Literal("Fired"), note: Schema.String }),
})
.command("schedule", {
payload: Schema.Struct({ note: Schema.String }),
success: Schema.Null,
error: Schema.Never,
reduce: (state, { note }, context) =>
Result.succeed({
state: { note, fired: false },
value: null,
timers: [
{
_tag: "Set" as const,
timerId: "reminder",
dueAtMillis: context.nowMillis + 100,
command: "fire",
payload: { note },
},
],
}),
})
.command("fire", {
payload: Schema.Struct({ note: Schema.String }),
success: Schema.Null,
error: Schema.Never,
reduce: (state, { note }) =>
state.note === note && !state.fired
? Result.succeed({
state: { ...state, fired: true },
value: null,
events: [{ _tag: "Fired" as const, note }],
})
: Result.succeed({ state, value: null }),
})
.query("read", {
payload: Schema.Null,
success: Schema.Struct({ note: Schema.String, fired: Schema.Boolean }),
error: Schema.Never,
read: (state) => Result.succeed(state),
})
const database = { filename: "./reminder.sqlite" }
const store = { tablePrefix: "reminders" }
const RunnerLive = Layer.mergeAll(
Reminder.toLayer(),
// Without a dispatcher in scope, timer and outbox intents stay committed but pending.
ActorRuntime.layerDispatchers({
pollInterval: "25 millis",
batchSize: 16,
concurrency: 4,
claimDuration: "1 second",
}),
).pipe(
Layer.provideMerge(
SqliteSingle.layer({
database,
store,
runtime: {
namespace: "demo",
maxCommandBytes: 16_384,
maxStateBytes: 16_384,
maxEventBytes: 4_096,
maxEventsPerTurn: 16,
maxOutboxCallsPerTurn: 16,
maxTimerChangesPerTurn: 16,
maxTurnDuration: "5 seconds",
actorLeaseDuration: "30 seconds",
actorLeaseRenewEvery: "10 seconds",
},
}),
),
)
const program = Effect.gen(function* () {
const reminder = (yield* Reminder.client)({ tenant: "acme", key: ["demo"] })
yield* reminder.commands.schedule({ note: "stretch" }, { commandId: "schedule-1" })
yield* Effect.sleep("500 millis")
const state = yield* reminder.queries.read(null)
yield* Effect.logInfo("dispatcher fired the committed timer", state.value)
})
BunRuntime.runMain(
SqliteSingle.migrate({ database, store }).pipe(
Effect.andThen(program.pipe(Effect.provide(RunnerLive))),
),
)A timer Set on an existing timerId replaces it and bumps its generation, so a stale wake cannot run the replacement; { _tag: "Cancel", timerId } removes it. The dispatcher polls and claims inside the surrounding scope — it is not a detached background promise, and a stopped deployment does not wake itself. Cross-actor delivery works the same way through outbox entries targeting another actor's command. See docs/guides/timers-and-outbox.md and the runnable timer-outbox example.
Hosted actors
HostActor wraps execution the framework cannot own — an engine, an integration, an authority with its own journal. make(context) runs on every activation and returns handlers plus a failure supervisor effect; context.fork runs scoped background work and context.scope takes finalizers.
import { BunRuntime } from "@effect/platform-bun"
import { Effect, Layer, Ref, Schema, Scope } from "effect"
import { HostActor } from "effect-actors"
import { SqliteSingle } from "effect-actors-bun"
const Ticker = HostActor.make("Ticker", {
protocolVersion: 1,
actions: {
snapshot: HostActor.action({
payload: Schema.Null,
success: Schema.Struct({ ticks: Schema.Int }),
error: Schema.Never,
delivery: { _tag: "Transient" },
}),
},
})
const database = { filename: "./ticker.sqlite" }
const store = { tablePrefix: "ticker" }
const runtime = {
namespace: "demo",
maxCommandBytes: 16_384,
maxStateBytes: 16_384,
maxEventBytes: 4_096,
maxEventsPerTurn: 16,
maxOutboxCallsPerTurn: 16,
maxTimerChangesPerTurn: 16,
maxTurnDuration: "5 seconds",
actorLeaseDuration: "30 seconds",
actorLeaseRenewEvery: "10 seconds",
} as const
const TickerLive = Ticker.toLayer(
({ fork, scope }) =>
Effect.gen(function* () {
const ticks = yield* Ref.make(0)
yield* Scope.addFinalizer(scope, Effect.logInfo("ticker activation closed"))
yield* fork(
Effect.sleep("50 millis").pipe(
Effect.andThen(Ref.update(ticks, (count) => count + 1)),
Effect.forever,
),
)
return {
handlers: Ticker.of({
snapshot: () => Ref.get(ticks).pipe(Effect.map((ticks) => ({ ticks }))),
}),
failure: Effect.never,
}
}),
{ maxIdleTime: "30 seconds", mailboxCapacity: 16, concurrency: 1 },
).pipe(Layer.provideMerge(SqliteSingle.layer({ database, store, runtime })))
const program = Effect.gen(function* () {
const tickerFor = yield* Ticker.client
const ticker = tickerFor({ tenant: "acme", key: ["main"] })
const first = yield* ticker.actions.snapshot(null)
yield* Effect.sleep("300 millis")
const later = yield* ticker.actions.snapshot(null)
yield* Effect.logInfo("ticker advanced while hosted", { first, later })
})
BunRuntime.runMain(
SqliteSingle.migrate({ database, store }).pipe(
Effect.andThen(program.pipe(Effect.provide(TickerLive))),
),
)Closures and fibers are not persisted — on reactivation make must rebuild pending work from your own durable authority. A retryable authority failure closes the scope and reactivates with backoff (500ms up to a 10s cap); a nonretryable one stops retries for that entity lifetime. Persisted delivery replays a request key your authority must store. docs/guides/hosted-actors.md lists what the application owns before a persisted action can claim durable behavior; examples/hosted-lifecycle verifies scope and finalizer semantics against real SQLite.
Public gateway
Gateway.layer(options) mounts HTTP, SSE, and WebSocket routes on an HttpRouter you own, exposing only the actor protocols you list. Every request — commands, queries, receipt lookups, subscriptions, and their retries — goes through a Gateway.Security service you supply (authenticate, authorize, admit), including tenant scoping, origin checks, and bounded connection/event buffers.
A remote process gets the same typed client by swapping the Client implementation: provide ActorClient.layerHttp({ namespace, baseUrl }) instead of a cluster composition and Counter.client talks to the gateway over HTTP.
Gateway integration is still being qualified against the platform compositions. Treat docs/guides/gateway.md as the contract and verify your deployment before exposing a route.
Deployment
| Topology | Composition | Actor ownership |
| --------------------- | --------------------------------------- | -------------------------------------------- |
| Bun + SQLite | SqliteSingle (effect-actors-bun) | One process, local file — no runner listener |
| Node + PostgreSQL | PostgresSingle (effect-actors-node) | One runner against shared PostgreSQL |
| Bun/Node + PostgreSQL | PostgresCluster | Replicas behind private runner RPC |
| Bun/Node + PostgreSQL | PostgresClient | None — clients and gateways only, no store |
The runtime namespace is also the Cluster shard group: replicas sharing a database must agree on namespace, tablePrefix, and actor definitions. PostgresCluster runners need a peer-reachable advertisedAddress and a bindable listenAddress (build both with RunnerAddress.make(host, port) from effect/unstable/cluster). A client-only process assigns no shard groups and cannot host actors or dispatchers — it is how you run a public gateway without actor ownership. Details in docs/guides/deployment.md.
Testing
Testing.layerMemory provides the runtime, client, and an in-memory store — a full actor environment with no database:
import { BunRuntime } from "@effect/platform-bun"
import { Effect, Layer, Result, Schema } from "effect"
import { Actor, Testing } from "effect-actors"
const Counter = Actor.make("Counter", {
protocolVersion: 1,
state: {
version: 1,
schema: Schema.Struct({ count: Schema.Int }),
initial: () => ({ count: 0 }),
migrations: [],
},
events: Schema.Never,
}).command("increment", {
payload: Schema.Struct({ by: Schema.Int }),
success: Schema.Struct({ count: Schema.Int }),
error: Schema.Never,
reduce: (state, { by }) => {
const count = state.count + by
return Result.succeed({ state: { count }, value: { count } })
},
})
const TestLive = Counter.toLayer().pipe(Layer.provideMerge(Testing.layerMemory))
const program = Effect.gen(function* () {
const counter = (yield* Counter.client)({ tenant: "acme", key: ["test"] })
const receipt = yield* counter.commands.increment({ by: 2 }, { commandId: "test-1" })
yield* Effect.logInfo("in-memory receipt", receipt)
})
BunRuntime.runMain(program.pipe(Effect.provide(TestLive)))What v1 does not do
- No exactly-once external side effects — outbox delivery is at-least-once
- No automatic global placement or live process migration
- No socket hibernation, code sandboxing, or zero-compute timer wakeups
- No cross-actor transactions — one atomic commit per actor address
- No managed backups; multi-runner evidence is limited to the tested failover cases
- Hosted actors do not add a second state store for your authority's data
Documentation
- State actors — reducers, command identity, revisions, receipts, cursors
- Timers and outbox — deferred and cross-actor work
- Hosted actors — authority obligations and lifecycle
- Gateway — HTTP/SSE/WebSocket routes and the security contract
- Deployment — topologies and runner configuration
- Operations — migrations, retention, recovery, diagnostics
- Guarantees — the contract and its boundaries
- Examples — runnable, packaged, finite programs
Developing in this repo
bun install --frozen-lockfile
bun run check # format, lint, typecheck
bun run test # package test suites
bun run pack # build distributable tarballs
bun run smoke:consumer # install tarballs into an isolated consumer
bun run examples:check # typecheck and run examples — and every ```ts block on this pagePostgreSQL-backed tests need a disposable database; see docs/guides/operations.md.
Releases publish only from the v<version> tag workflow on GitHub Actions, never from a workstation — docs/release.md.
License
MIT © 2026 Dallen Pyrah
