The Effect 4 Handbook — A Guided Tour of Effect v4
Source-grounded guide for humans and coding agents. Validation target refreshed 2026-11-19 to published effect@4.1.4, tag effect@4.1.4, commit 289a53f7 (released 2026-11-11). Each module is labelled with its public import path and stability marker.
This edition validates examples against published effect@4.1.4 — not unreleased main. The source audit covered all 144 modules exported from the effect root barrel, all 23 public effect/<area> families (266 modules), the 35 public packages, their tests and examples, every change from 4.1.0 to 4.1.4, and every canonical Markdown page in this site. Examples are checked with pnpm, Node's native TypeScript execution, TypeScript 7.0.2 in strict mode, and Effect @effect/tsgo 0.70.0 diagnostics. Short fragments may declare application-specific boundaries.
All chapters and deep dives inherit this edition's audit target. Edition URLs identify major.minor; the release above, the site footer, and generated Markdown headers identify the exact audited patch. Chapter prose states the behavior directly; explicit version numbers are reserved for release history, migration boundaries, reproducible installation, and pinned source links.
New to Effect 4? Start with Getting Started — it covers installation (npm install effect now installs Effect 4), TypeScript and ESM settings, and a first program.
Your first session: follow the small approval worker route through errors, a tested service, resource ownership, Layers, and shutdown — five small exercises with observable self-checks.
Effect 4.0 is a stable release with a published long-term-support policy: bug fixes until September 2029 or one year after 5.0 ships, and security fixes until September 2029 or two years after 5.0 ships, whichever is later. The effect runtime and packages in its release train share one version number and are released together, so upgrade them as one coordinated bump. External compiler tooling such as @effect/tsgo has its own version line.
Stability is declared per API with a JSDoc tag, not by import path. Since 4.0.2 every module and every directly importable export carries an explicit tag:
Tag
Promise
Where you meet it
@stability stable
Strict semantic versioning: breaking changes only in a major release.
Most of the "effect" root barrel — Effect, Layer, Schema, Stream, Config, the data structures, most Tx* transactional modules — plus effect/testing's TestClock and the text codecs Base64, Base64Url, Hex, and EncodingError under effect/encoding.
@stability unstable
May gain features in a patch release and break in a minor release. Production-ready; pin exact versions and read release notes before upgrading.
The subsystem families under effect/<area> — http, http-api, rpc, sql, cluster, workflow, ai, cli, reactivity, persistence, eventlog, observability, net, socket, process, workers, devtools, schema, crypto, jose — a set of root-barrel modules (Arbitrary, ByteSize, Bytes, ChannelSchema, ErrorReporter, ExecutionPlan, FileSystem, Graph, HashRing, LayerMap, LayerRef, Newtype, PartitionedSemaphore, Path, PlatformError, Rational, SemVer, SemVerRange, Stdio, Terminal, TxChunk, Version), TestConsole and TestSchema, the format codecs Csv, Ini, JsonArray, Json5, Jsonc, Ndjson, SchemaBinary, Sse, Tar, Toml, and Yaml, a set of advanced Schema APIs, and every API that exposes a third-party dependency (driver options and clients in @effect/sql-*, provider clients and generated schemas in @effect/ai-*, @effect/opentelemetry, the vitest re-export in @effect/vitest, Redis and undici accessors in the platform packages).
@stability experimental
May gain features and break in a patch release.
The effect/graphql family and @effect/graphql-generator; the @effect/platform-cloudflare package; Host, Dns, and AddressResolver under effect/net; DatagramSocket under effect/socket; the root modules Glob and TextDiff; the Xml and Zip codecs; CircuitBreaker under effect/persistence; McpClient, McpClientError, AgUi, AgUiSchema, and AgUiServer under effect/ai; their related Schema codecs and host adapters. Pin exact versions and re-check contracts on every upgrade; see GraphQL and Platform & Runtime Hosts.
"Unstable" describes the compatibility contract, not the quality: HTTP, SQL, and RPC are what production Effect applications are built on. Every module section carries its stable, unstable, or experimental label. TestConsole and TestSchema are unstable testing APIs. Each page describes the pinned release. What changed from one audited release to the next — behavior, stability, renamed options and telemetry names, new modules, and handbook corrections — is recorded in Release History; the per-package CHANGELOG.md files in the Effect repository remain the authoritative record of every change.
These official resources complement the handbook with longer explanations and executable examples. The GitHub links are pinned to the same audited release so their code and this handbook stay reproducible together; the website guides track Effect's main branch, so where they differ from this handbook, the pinned release and this handbook win.
The official website's narrative guides — error management, requirements, resources, concurrency, streams, scheduling, Schema, and platform. Not release-pinned. Every handbook topic links the matching guides at the top of its page.
The maintainers' own coding conventions for agents (also published as LLMS.md), with topic-organized executable examples under node_modules/effect/ai-docs/src. See Coding conventions for agents below for how this handbook relates to it.
The long-form reference for codecs, validation, transformations, serialization, tooling, errors, integrations, and migration.
Effect 4 ships as one library. The core effect package holds the runtime, standard library, and the subsystem families (http, rpc, sql, cluster, ai, …), with platform-, driver-, and provider-specific satellites around it. One import surface, one version number, zero runtime dependencies, a runtime built for speed and tree-shaking.
import { Effect } from "effect"// An Effect<Success, Error, Requirements> is a *description* of a program that,// when run, will either succeed with A, fail with a typed E, or need services R.declare const loadEmployee: (id: string) => Effect.Effect<Employee, EmployeeNotFound, Hris>// ▲ value ▲ typed err ▲ deps
Three type parameters; almost every module is "a thing you can put in one of those slots." A Stream is the many-valued sibling of the success channel. Cause is the full truth of the error channel. Layer satisfies the requirements channel.
The house style (every example in this handbook uses it)
Idiomatic Effect 4 uses Effect.gen for inline composition and Effect.fn for functions returning effects (adds a tracing span and tidy stack traces automatically).
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"// Errors are schema-defined, tagged classes — serializable and pattern-matchable.class BudgetExceeded extends Schema.TaggedError<BudgetExceeded>()("BudgetExceeded", { remaining: Schema.Finite, requested: Schema.Finite}) {}// Effect.fn("name") = a traced, generator-based function returning an Effect.export const drawFromMeritBudget = Effect.fn("drawFromMeritBudget")( function*(remaining: number, raise: number) { if (raise > remaining) { // `return yield*` makes termination explicit to TypeScript. return yield* new BudgetExceeded({ remaining, requested: raise }) } yield* Effect.log(`Approving raise of ${raise}`) return remaining - raise })
Services are classes that extend Context.Service; the implementation rides along as a static Layer:
Dual APIs. Most Effect functions ship two overloads with identical behavior: data-last (Effect.map(f) returns a function that expects the value, built for .pipe(...) chains) and data-first (Effect.map(self, f), convenient for a single step). Rule of thumb: one step, data-first; several steps, .pipe with data-last. Function.dual builds the same pair for your own functions.
The effect package ships its maintainers' conventions as AGENTS.md (the same text as the repository's LLMS.md), and this handbook follows them. The rules that matter most when generating code:
Generators over combinator chains. Write inline logic with Effect.gen; write reusable functions with Effect.fn("name") when a tracing span is useful and Effect.fnUntraced when it is not (library internals, hot paths). Do not write a function whose only body is return Effect.gen(...). Attach extra behaviour as trailing arguments to Effect.fn rather than .pipe on its result.
Return when you fail. Inside a generator, write return yield* new SomeError(...) so TypeScript knows the function does not continue.
Errors are Schema.TaggedError classes, recovered with Effect.catchTag / Effect.catchTags for specific tags and Effect.catch for everything. Model variants inside one error with a tagged reason field and Effect.catchReason.
Behaviour lives in services. Define a service with Context.Service<Self, Interface>()("package/path/Name"), attach its implementation as a static layer, and build it with Service.of({...}). Use Context.Reference for values with a default (configuration, feature flags).
Validate with Schema, never by hand. Untrusted input is decoded with a schema; domain models are Schema.Classes. For runtime type guards on unknown, use the Predicate module instead of writing isString-style helpers.
Time goes through DateTime and Clock, not Date.now(), so it is testable.
Run at the edge.NodeRuntime.runMain or Layer.launch for a process; ManagedRuntime when a host framework calls in.
Observability is built in. Prefer the lightweight Otlp modules from effect/observability in new projects; use @effect/opentelemetry when joining an existing OpenTelemetry setup.
Two tooling habits make agents measurably more effective with Effect: install the Effect language service (@effect/tsgo, see Effect diagnostics) so a wrong channel or an un-yielded Effect is a compiler error rather than a runtime surprise, and keep the installed effect source in reach — the official guidance is to prefer the installed package and its ai-docs over other copies of the documentation, which may describe a different version.
effect — The core: 144 root modules (Effect, Stream, Schema, Layer, the data structures, STM…) plus 23 public effect/<area> families (http, http-api, rpc, sql, cluster, ai, cli, workflow, eventlog, encoding, crypto, jose, reactivity, persistence, net, testing, graphql, and more).
@effect/platform-* — node, bun, deno, browser, plus the shared Node implementation package — concrete implementations of FileSystem, HttpServer, sockets, workers, and runtimes for each host — and the experimental cloudflare package, which runs cluster entities, workflows, and queues on Durable Objects.
@effect/sql-* — Drivers: pg, mysql2, mssql, clickhouse, libsql, d1, pglite, and a family of sqlite-* variants.
@effect/ai-* — Provider bindings: amazon-bedrock, anthropic, openai, openai-compat, openrouter, typesafe — concrete backends for the provider-agnostic AI modules.
@effect/atom-* — Framework bindings for the reactive Atom system: react, solid, vue.
@effect/opentelemetry — Bridges Effect's tracing/metrics/logging to a real OpenTelemetry SDK (Node SDK, Web SDK, exporters).
@effect/vitest — First-class testing: it.effect, TestClock-aware assertions, layer-sharing helpers, property tests over the native Arbitrary module.
tools — The repo's own build/codegen tooling — AI code/doc generators, OpenAPI and GraphQL generators, @effect/doctest, the bundler and jsdoc pipeline.
Import style. Each module is labelled with its subpath (effect/Queue), while examples import from the "effect" barrel: import { Effect, Queue } from "effect". The two are equivalent at runtime. The package declares no side effects, so bundlers with deep scope analysis (Rolldown, Rollup, Webpack 5+) tree-shake the barrel; import * as Queue from "effect/Queue" is the conservative form elsewhere. Area families are always imported by their own barrel, for example import { HttpClient } from "effect/http". Official guide: Importing Effect.
⌘K / Ctrl+K — search — Jump to a module by name. Type "semaphore", "TxRef", "HttpApi", "Sink" — hit enter and you land right on it, with the module highlighted.
Sidebar — browse by theme — Chapters are grouped from foundations → concurrency → data → web → distributed → tooling. Roughly the order you'd grow into them.
Prev / Next — read it like a book — Each chapter ends with navigation.
Reading programmatically — Every page has a Markdown twin at the same path with .md appended, llms.txt routes intents to sections, and effect-4-modules.md lists every module. Using the Handbook from an Agent is the full protocol, including a drop-in AGENTS.md block.
Other Effect versions — One edition of the handbook is published per Effect major.minor, each audited against one release and served under its own path (/4.0/, /4.1/, …); the site root is always the newest. Use the edition switcher in the navigation bar, or versions.json at the site root, to match the handbook to the effect version you have installed.
Major module entries cover what the API is, its mental model, a real example, and a "reach for it when" line. Smaller supporting modules stay compact so this remains useful as an agent reference.
Tip: Every Effect API in this handbook is grounded in the audited implementation, tests, or package examples. Pin compatible effect and @effect/* versions together, and re-audit unstable imports before upgrading.
Everything else in this handbook assumes a project where Effect is installed, TypeScript is strict, and one entrypoint runs an Effect. This page gets you there and names the traps on the way: mismatched package versions, compiler settings that silently weaken the types, and packages that do not exist for Effect 4.
Official guides:Installation (asks for Node.js 22.18+; the release-matched README states Node.js 22.19+ as the general minimum), Importing Effect, The Effect Type, Creating Effects, Running Effects (it names the runFork result RuntimeFiber; the type is Fiber), Using Generators, Building Pipelines (it calls Option and Result yieldable inside Effect.gen; they are not — use Effect.fromOption and Effect.fromResult), Devtools. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Effect 4 is the latest release on npm: a plain pnpm add effect installs it. Pin the exact version anyway, so that an upgrade is a deliberate, audited change rather than a side effect of a fresh install.
Keep application effect and @effect/* integration packages on one release. These packages are released together. Pin matching versions for the platform, SQL, provider, UI, and testing adapters: each is built and tested against that release, and subsystem families under effect/<area> may change between minor releases. Developer tools such as @effect/tsgo have their own version line. Check for a single copy with pnpm why effect (or npm ls effect) after every install; the Effect language service reports a second copy as duplicatePackage.
Install when you need
Package
The core, plus every effect/<area> family (HTTP, RPC, SQL client, CLI, AI, JOSE, cluster, workflow, …)
effect — no runtime dependencies
A process entrypoint, file system, HTTP server or client for a host
Do not install @effect/platform, @effect/cli, @effect/rpc, @effect/sql, @effect/cluster, @effect/workflow, @effect/ai, or @effect/experimental: they have no Effect 4 release, and their modules ship inside effect under effect/<area> paths such as effect/http, effect/rpc, and effect/sql.
The library's floor and this handbook's validation target are different things. The first column is what the audited release asks of you; the second is what every example here is compiled and run with.
Required by Effect (release-matched README and package metadata)
Used to validate this handbook
TypeScript
5.9 or newer; TypeScript 7 recommended
7.0.2
Node.js
22.19 or newer (the README's general minimum; @effect/platform-node, @effect/platform-node-shared, and @effect/opentelemetry declare engines.node >=22.19.0); on Deno, @effect/platform-deno declares engines.deno >=2.9.3
26, which runs .ts entrypoints directly
Test runner
@effect/vitest and @effect/doctest require Vitest 5; @effect/atom-react requires React 19
Vitest 5.1.1
Type checking
strict: true
strict plus the flags below
Module format
ESM only: the packages are "type": "module" with no CommonJS build
module: NodeNext
Set "type": "module" in your own package.json, then start from this tsconfig.json:
Without it, E and R inference degrades and null flows through unchecked.
target / lib: ES2025
handbook choice; set both to your oldest runtime
ES2025 is the newest target TypeScript 7 accepts. It assumes a current runtime — Node.js 24+ or a current evergreen browser — for library APIs such as Promise.try and Iterator helpers. Effect itself needs nothing newer than ES2022, so lower both settings together when you support older hosts; add "DOM" to lib for browser code.
exactOptionalPropertyTypes
recommended; on in the Effect repository and in this handbook
Keeps "key absent" and "key present with undefined" distinct, which is the difference between Schema.optionalKey and Schema.optional.
module / moduleResolution: NodeNext (or Bundler behind a bundler)
required in practice
Both honor the package exports map; subpaths such as effect/http and effect/testing do not resolve under legacy node10 resolution.
Source stays runnable by a type-stripping runtime: type-only imports are written import type, and enums, namespaces, and constructor parameter properties are rejected.
noUncheckedIndexedAccess
handbook choice
Array and record lookups produce T | undefined, which pairs naturally with Option.fromNullishOr.
One file, one runtime call. NodeRuntime.runMain is the process edge: it forks the program as the root fiber, interrupts it on SIGINT or SIGTERM so finalizers run, reports an unhandled failure through the logger, and sets the exit code (0 on success, 130 when the program was only interrupted, non-zero on failure). The runtime itself keeps the process alive while fibers are pending, so runMain is about signals, exit codes, and error reporting rather than liveness.
Self-contained source · Type-checked
ts
import { NodeRuntime } from "@effect/platform-node"import { Effect, Schema } from "effect"class RaiseOutOfBand extends Schema.TaggedError<RaiseOutOfBand>()("RaiseOutOfBand", { percent: Schema.Finite, maximum: Schema.Finite}) {}// An Effect-returning function: traced, and typed as// (salary, percent) => Effect<number, RaiseOutOfBand>const proposeRaise = Effect.fn("proposeRaise")(function*(salary: number, percent: number) { if (percent > 0.15) { return yield* new RaiseOutOfBand({ percent, maximum: 0.15 }) } yield* Effect.logInfo(`raise of ${percent * 100}% accepted`) return Math.round(salary * (1 + percent))})// Inline composition. Nothing has run yet: `program` is a description.const program = Effect.gen(function*() { const next = yield* proposeRaise(120_000, 0.04) yield* Effect.logInfo(`new salary: ${next}`)})NodeRuntime.runMain(program)
text
$ node src/main.ts[20:40:57.787] INFO (#2): raise of 4% accepted[20:40:57.788] INFO (#2): new salary: 124800
Change 0.04 to 0.4 and the process logs ERROR (#2): RaiseOutOfBand with a stack that points at proposeRaise, then exits with code 1.
Four reading rules carry into every other page:
Effect<A, E, R> is a description: it succeeds with A, fails with a typed E, and needs services R. Building one performs no work, so Effect.succeed(Date.now()) reads the clock while the program is being built; write Effect.sync(() => Date.now()).
yield* sequences; return yield* fails. Inside Effect.gen and Effect.fn, yield* runs an Effect and gives you its value. Yielding a tagged error fails the Effect, and the return tells TypeScript the code after it is unreachable.
E = never means "no modeled failure is left", not "cannot go wrong". Defects and interruption exist regardless of the error type.
Run at an edge you own. Reusable code returns Effects; only an entrypoint, a host adapter, or a test calls a runner.
Edge
Runner
On failure
Process entrypoint
NodeRuntime.runMain (BunRuntime, DenoRuntime in their packages)
logs, sets the exit code
JavaScript caller that wants a Promise
Effect.runPromise
rejects with the failure value or defect; only an Exit runner tells failure, defect, and interruption apart
Caller that must branch on the outcome
Effect.runPromiseExit, Effect.runSyncExit
resolves with an Exit
Provably synchronous effect
Effect.runSync
throws, including when the effect turns out to be asynchronous
Caller that keeps and owns the fiber
Effect.runFork
returns a Fiber; someone must join, observe, or interrupt it
A host that calls in repeatedly (web framework, UI)
// Barrel: every root module as a namespace. The handbook uses this form.import { Effect, Layer, Schema } from "effect"// Subpath: one module per import. Same module instance as the barrel export.import * as Option from "effect/Option"// Area families have their own barrels and per-module subpaths.import { HttpClient } from "effect/http"import * as HttpClientRequest from "effect/http/HttpClientRequest"// Test services live under their own entry point.import { TestClock } from "effect/testing"
The module label on every handbook section — `effect/Queue` — stable — is the subpath. The example beneath it imports the same module from the barrel; the two are interchangeable.
Tree-shaking is a bundler property, enabled by the package.effect declares its side-effect-free modules and exposes its API as module functions rather than methods, so a bundler can drop what a program never references. When a bundler or test runner handles the barrel poorly, switch that project to subpath imports; no call site changes.
effect/internal/* and */index subpaths are blocked by the exports map. If an import needs them, the API is not public.
Functions are dual.Effect.map(effect, f) and effect.pipe(Effect.map(f)) are the same operation; use the first for one step and .pipe for several.
Stability is a per-API contract declared with a JSDoc tag, not an import path; since 4.0.2 every module and directly importable export is tagged explicitly. The handbook summarizes it as a badge on every module section.
Badge
Promise
What carries it
stable (@stability stable)
semantic versioning: breaking changes only in a major release
most of the root barrel — Effect, Layer, Schema, Stream, Config, the data structures, most Tx* transactional modules — plus TestClock from effect/testing and the text codecs under effect/encoding (Base64, Base64Url, Hex, EncodingError)
unstable (@stability unstable)
may break in a minor release
the subsystem families effect/ai, cli, cluster, devtools, eventlog, http, http-api, jose, net, observability, persistence, process, reactivity, rpc, schema, socket, sql, workers, workflow; root-barrel modules such as Arbitrary, FileSystem, Path, ExecutionPlan, LayerMap, Graph, and ByteSize (each module section shows its badge); TestConsole and TestSchema; the remaining effect/encoding codecs; some advanced Schema APIs; and every API that exposes a third-party dependency (driver options in @effect/sql-*, provider clients in @effect/ai-*, @effect/opentelemetry)
experimental (@stability experimental)
may break in a patch release
effect/graphql; Host, Dns, and AddressResolver in effect/net; the related host and DNS schemas in Schema
"Unstable" describes the API contract, not the quality: HTTP, SQL, and RPC are what production Effect applications are built on. It does change how you depend on them. Pin exact versions, read the release notes before every upgrade, and keep leaf area imports behind a small service you own so a rename touches one file. The maintainers' stated plan is to promote these families to stable as production feedback settles them.
The Effect language service ships as @effect/tsgo, built on the native TypeScript compiler, and needs typescript 7 installed beside it. It adds Effect-aware diagnostics and quick fixes: an Effect that was never yielded or assigned, a bare yield without *, implementation services leaking through a service method, a second copy of an Effect package, and APIs that do not exist in the installed version. npx @effect/tsgo setup adds the dependency and the @effect/language-service entry under compilerOptions.plugins; effect-tsgo patch (run it from a prepare script, as the Effect repository does) patches the local TypeScript install so tsc emits the same diagnostics; and npx @effect/tsgo diagnostics --project tsconfig.json --strict is a standalone CI check in which warnings fail the build. This handbook compiles every example under exactly that pair: strict tsc and strict Effect diagnostics, with one rule turned off: unstableApiUsage warns on every API tagged @stability unstable, including effect/http, effect/sql, effect/rpc, effect/ai, and the other unstable area families. A project that uses those modules sets "diagnosticSeverity": { "unstableApiUsage": "off" } in the plugin options (or downgrades it to a suggestion) rather than suppressing it line by line; a project that wants to be told when it strays outside the semver-covered surface leaves it on.
The official guidance for working with coding agents makes the same point from the other side: the tighter the feedback loop, the better the generated code, so install the language service first, and keep the installed effect source (and its bundled AGENTS.md and ai-docs/) within the agent's reach rather than relying on remembered API shapes. Testing & Dev Tooling covers the tooling in depth.
After the first program, follow these five stops in order. Grow one small worker that processes raise proposals through a replaceable approval service; use an in-memory fake and a counted resource rather than a real payroll connection. The recipes are patterns to adapt, not successive files to paste together. These are self-check exercises, not automatically executed or graded lessons.
Exercise: Put approval behind a service whose method retains step 1's expected error. Substitute a recording fake and assert the submitted proposal and result.
Done when: The assertion depends on a call recorded only by the fake; the same worker runs unchanged with either implementation.
Exercise: Give the approval service a counted app-lifetime client, distinct from the per-job handle. Wire client → service → worker, and provide the graph once at the edge.
Done when: The runnable worker has no remaining service requirements; two jobs share one client acquisition, and that client closes once when the owning scope ends.
Exercise: Host the worker as scoped background work in an application Layer, launch it with the platform runner, and send SIGINT or SIGTERM during a job.
Done when: The active job releases its handle, the app-lifetime client closes, and the process exits without leaving the worker running.
Effect is not a running program — it's a description. The runtime spins up fibers to execute descriptions, scopes bound resource lifetimes, and a finished computation returns an Exit carrying a full Cause. Build a value of type Effect<A, E, R> by composing combinators; nothing runs until you execute it. Running forks a root fiber that may fork children, await deferreds, race siblings, or open scopes. When it finishes it produces an Exit<A, E> — either Success<A> or Failure holding a Cause<E> recording everything that went wrong (typed errors, defects, interruptions).
This page covers building and combining Effects. How they run — Exit and Cause, fibers and their handles, Scope, the scheduler and clock, Deferred, Latch, and ManagedRuntime — is on Fibers, Scopes & Runtimes.
Official guides:Creating Effects, Running Effects (its runFork text still names a RuntimeFiber return type; Effect.runFork returns Fiber). These guides track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Effect<A, E, R> is a lazy, immutable description of a computation that yields an A, may fail with typed E, and requires services R. Think of it as program-as-data: you assemble a recipe and the runtime executes it. That indirection enables typed errors, dependency injection, retries, interruption, and tracing as ordinary composition.
Read the three slots honestly.A is what success returns, E lists the failures the program chose to model, and R lists what must still be provided. E = never means "no modeled failure is left", not "cannot go wrong": defects (a throw inside Effect.sync, a bug in a finalizer) and interruption exist for every effect and travel in the Cause, never in E. The types make the operational questions visible — what fails, what it needs, who can cancel it — but they do not prove that a timeout value or a retry rule is the right policy. When a channel has to be named, extract it from the inferred type: Effect.Success<typeof program>, Effect.Error<typeof program>, Effect.Services<typeof program>.
The ownership habit. For anything that runs or holds a resource, ask three questions: who closes it, what bounds it, and what runs when it loses? The answers are a Scope owner (section 6), a fork owner (Fiber), a { concurrency } bound (section 4), and a finalizer.
Pull values, sync code, promises, nullables, and callback APIs into the Effect world. Note Effect.callback (v4's name — not async) and Effect.tryPromise for fallible promises.
Choose the constructor by the JavaScript convention being wrapped — how the foreign code reports failure and when it does its work — not by which one makes E smallest. A constructor is an assertion about the wrapped code: sync and promise assert "this cannot throw or reject", so when it does anyway the failure is a defect, invisible in E.
You are wrapping
Constructor
A throw or rejection becomes
A value you already hold
Effect.succeed(value)
not applicable — the argument is evaluated eagerly (see the warning below)
A known failure
Effect.fail(error), or yield* new MyError(...)
not applicable; Effect.failSync(() => error) when building the error is itself work
Synchronous code that cannot throw
Effect.sync(() => ...)
a defect
Synchronous code that can throw (JSON.parse, new URL)
Effect.try({ try, catch })
the typed error catch returns; the bare-thunk form Effect.try(() => ...) yields Cause.UnknownError
Effect.promise(() => fetch(url)) is the classic misuse: it claims the network cannot fail and silently moves every outage out of the typed channel. For Effect.try and Effect.tryPromise, the bare-thunk form always has E = Cause.UnknownError and the { try, catch } form has exactly the type catch returns; there is no overload for an explicit two-type-argument call on the bare form, nor for an argument that is a union of both forms — write { try, catch } with a real mapper instead.
Warning:Arguments are evaluated before the call.Effect.succeed(Date.now()), Effect.succeed(counter.next()), and Effect.fail(buildError()) do their work while the program is being built, and every run — and every retry — replays that one captured value. Symptoms: stale timestamps, work that "already happened" before anything ran, retries that reuse the first result. Use Effect.sync / Effect.try when the work must happen at run time, and Effect.suspend when even choosing the next effect must wait. The same trap applies to any helper that takes a value instead of a thunk. A cheap regression test: build the effect, assert the spy count is 0, run it, assert 1.
Effect.fromOption(option, onNone?) lifts an Option; without the callback it fails with NoSuchElementError, while onNone lets the boundary produce a custom typed error lazily.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { endpoint: Schema.String, cause: Schema.Defect()}) {}class InvalidBandFile extends Schema.TaggedError<InvalidBandFile>()("InvalidBandFile", { cause: Schema.Defect()}) {}const fromValue = Effect.succeed({ cycle: "2026-MERIT" }) // already have itconst fromSync = Effect.sync(() => crypto.randomUUID()) // side effect that cannot throwconst fromEnv = Effect.fromNullishOr(process.env.HRIS_BASE_URL) // -> fails NoSuchElementError if unset// Synchronous code that can throw: the throw becomes a typed failure.const parseBandFile = (text: string) => Effect.try({ try: () => JSON.parse(text) as unknown, catch: (cause) => new InvalidBandFile({ cause }) })// Promise that can reject. The Promise is created inside the thunk (so nothing starts// until the effect runs) and the supplied signal is forwarded, so a timeout, a lost// race, or a shutdown aborts the HTTP request instead of abandoning it.const fetchEmployee = Effect.fn("fetchEmployee")((id: string) => Effect.tryPromise({ try: (signal) => fetch(`/hris/employees/${id}`, { signal }).then((r) => r.json()), catch: (cause) => new HrisUnavailable({ endpoint: `/hris/employees/${id}`, cause }) }))// Callback-style async: resume once, return a finalizer for interruption.// e.g. a payroll webhook that fires once the nightly run settles.const awaitPayrollAck = Effect.callback<string>((resume) => { const id = setTimeout(() => resume(Effect.succeed("ack:run-2026-06")), 10) return Effect.sync(() => clearTimeout(id))})
Effect.callback details: only the first resume(...) counts (later calls are ignored, so a multi-event source needs a Queue or Stream.callback instead); the register function also receives an AbortSignal as its second argument; and the type parameters usually have to be written out because nothing in the body lets TypeScript infer them. Adapters that must be cancellable are covered in section 8.
Deferring construction with Effect.suspend. Three situations need it: an expression that would otherwise be captured once while building (a counter, a mutable lookup); a recursive function that would build its whole tree of effects before anything runs; and a function whose branches return differently typed effects, which suspend unifies into one Effect<A, E, R>.
Self-contained source · Type-checked
ts
import { Effect } from "effect"let attempts = 0const captured = Effect.succeed(++attempts) // incremented once, while buildingconst perRun = Effect.suspend(() => Effect.succeed(++attempts)) // incremented on every run// Recursion: each level is built only when the previous one runs.const vestedAfter = (quarters: number): Effect.Effect<number> => quarters === 0 ? Effect.succeed(0) : Effect.suspend(() => vestedAfter(quarters - 1)).pipe(Effect.map((shares) => shares + 250))
Generators are the imperative-looking glue. Use Effect.gen inline; use Effect.fn("name") for functions that return an effect — it adds a tracing span and clean stack traces. Always return yield* a terminal effect so TypeScript knows the function stops there.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"class BudgetExceeded extends Schema.TaggedError<BudgetExceeded>()( "BudgetExceeded", { remaining: Schema.Finite, requested: Schema.Finite }) {}// A traced, reusable effect-returning function. Note: do NOT .pipe an Effect.fn —// pass extra combinators as further arguments instead.// Draw a raise down against the remaining merit-budget pool.export const drawDownBudget = Effect.fn("drawDownBudget")( function*(remaining: number, raiseAmount: number) { if (raiseAmount > remaining) { return yield* new BudgetExceeded({ remaining, requested: raiseAmount }) } yield* Effect.log(`Approving raise of ${raiseAmount} from pool`) return remaining - raiseAmount })
Tip:gen vs. fn vs. fnUntraced. Use Effect.gen for one-off inline composition. Use Effect.fn("name") for any function called from elsewhere — the span name is valuable in traces. Drop to Effect.fnUntraced only on genuinely hot paths where per-call span overhead shows up in a profile. Like Effect.fn, Effect.fnUntraced (and fnUntracedEager) accepts { self } before the generator body to bind this for a method defined as a class field.
Pipeline combinators have different jobs. Each is dual, so Effect.map(self, f), pipe(self, Effect.map(f)), and self.pipe(Effect.map(f)) are the same thing. Use a pipeline when every step can be named inline, and switch to Effect.gen once several intermediate values are needed — the execution model is identical.
Combinator
Give it
Success value afterwards
Typical mistake
Effect.map(f)
a plain function A => B
B
passing an effect-returning function: the result is a nested Effect that never runs
Effect.flatMap(f)
A => Effect<B>
B
—
Effect.andThen(next)
an effect, or A => Effect<B>
B
passing a plain value, Promise, Option, or Result — only the two forms on the left have overloads
Effect.tap(f)
an effect, or A => Effect<X>
the original A (a failing tap still fails the pipeline)
using tap to "change" the value: it is silently unchanged
Effect.as(value) / Effect.asVoid
a constant / nothing
value / void
—
An effect that is created inside a callback but neither returned nor chained is silently dropped — the pipeline form of “My Effect never ran”.
Note:Yield descriptions, not handles. Inside Effect.gen you can yield* an Effect, an Exit, a Context.Service key or Context.Reference, a Config, and a yieldable error (Schema.TaggedError, Data.TaggedError, the built-in Cause.*Error classes). Runtime handles and plain data types are not effects: for a Fiber, Ref, Deferred, Option, or Result use Fiber.join, Ref.get, Deferred.await, Effect.fromOption, or Effect.fromResult. yield* someOption is a type error, and forcing it past the compiler dies with Not a valid effect. (Option and Result keep their iterators for Option.gen / Result.gen.)
Generator functions do not inherit this. In a class method, bind it with the options overload instead of aliasing const self = this: Effect.gen({ self: this }, function*() { return this.cycleId }).
Do notation is the pipe-only equivalent. You will meet Effect.Do with Effect.bind / Effect.bindTo / Effect.let in migrated code and in other modules. Each step adds a named field to a growing record (a repeated name replaces the field); later steps receive the whole record. The handbook standardizes on Effect.gen because it is flat, uses native control flow, and needs no record threading.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const loadBaseSalary: Effect.Effect<number>declare const loadMeritRate: Effect.Effect<number>const viaDo = Effect.Do.pipe( Effect.bind("base", () => loadBaseSalary), Effect.bind("rate", () => loadMeritRate), Effect.let("raise", ({ base, rate }) => base * rate), Effect.map(({ base, raise }) => base + raise))const viaGen = Effect.gen(function*() { const base = yield* loadBaseSalary const rate = yield* loadMeritRate return base + base * rate})
Errors live in the typed E channel. Recover with Effect.catch, narrow by tag with catchTag/catchTags, or reach for the cause with catchCause/catchDefect. Convert a failure into a value with Effect.result.
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import type { EmployeeNotFound, BandViolation } from "./errors.ts"declare const proposeRaise: ( employeeId: string) => Effect.Effect<number, EmployeeNotFound | BandViolation>const recommendation = proposeRaise("emp_142").pipe( // Catch several tags at once, each handler narrowed to its error type. Effect.catchTags({ EmployeeNotFound: () => Effect.succeed(0), // no employee, no raise BandViolation: (e) => Effect.fail(e) // re-raise: a comp analyst must review }), // Final safety net for anything still in the error channel. Effect.catch(() => Effect.succeed(0)))// `Effect.result` moves the failure into a value so you can branch on it.// Result.Success carries the value in `.success` (not `.value`).const inspected = Effect.gen(function*() { const result = yield* Effect.result(proposeRaise("emp_999")) return result._tag === "Success" ? result.success : -1})
Tagged reasons. When one error wraps several distinct causes, model the cause as a reason field typed as a Schema.Union of tagged errors. Recover at the reason level without unpacking the parent: Effect.catchReason handles one reason tag (with an optional catch-all), Effect.catchReasons handles several at once, and Effect.unwrapReason lifts the reasons into the error channel so catchTag/catchTags apply.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"// A tagged error whose `reason` is itself a tagged union — the v4 idiom for an// error that wraps several distinct failure causes.class RateLimited extends Schema.TaggedError<RateLimited>()("RateLimited", { retryAfter: Schema.Natural }) {}class QuotaExceeded extends Schema.TaggedError<QuotaExceeded>()("QuotaExceeded", { limit: Schema.Natural }) {}class HrisError extends Schema.TaggedError<HrisError>()("HrisError", { reason: Schema.Union([RateLimited, QuotaExceeded])}) {}declare const fetchRoster: Effect.Effect<ReadonlyArray<string>, HrisError>// catchReason: handle ONE reason tag, with an optional catch-all for the rest.const oneReason = fetchRoster.pipe( Effect.catchReason( "HrisError", // parent error _tag "RateLimited", // reason _tag (reason) => Effect.succeed([`retry after ${reason.retryAfter}s`]), (reason) => Effect.succeed([`HRIS failed: ${reason._tag}`]) // optional catch-all ))// catchReasons: handle SEVERAL reason tags at once.const manyReasons = fetchRoster.pipe( Effect.catchReasons("HrisError", { RateLimited: (reason) => Effect.succeed([`retry after ${reason.retryAfter}s`]), QuotaExceeded: (reason) => Effect.succeed([`quota ${reason.limit} hit`]) }))// unwrapReason: lift the reasons into the error channel, then use catchTags.const unwrapped = fetchRoster.pipe( Effect.unwrapReason("HrisError"), Effect.catchTags({ RateLimited: (reason) => Effect.succeed([`back off ${reason.retryAfter}s`]), QuotaExceeded: (reason) => Effect.succeed([`raise quota past ${reason.limit}`]) }))
This section is a summary. The full recovery toolkit — accumulation, folding with Effect.match, mapError, fallbacks, ignore versus ignoreCause, and when an outcome is a result rather than a failure — lives in Errors, Option & Result. One fact belongs here because it is about the runtime's Cause: typed handlers such as Effect.catch, catchTag, and orDie act on the first typed failure they find and replace the whole cause with the handler's result, so a defect or interruption recorded next to that failure is dropped — see recovering from a mixed Cause.
Official guide: Expected Errors (it defines errors with Data.TaggedError; the handbook's house style is Schema.TaggedError, and both are valid constructors).
Most combinators take a { concurrency } option. "unbounded" runs everything at once; a number caps in-flight work; the default is sequential. Types.Concurrency is exactly number | "unbounded"; there is no "inherit" mode.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const employeeIds: ReadonlyArray<string>declare const loadCompBand: (id: string) => Effect.Effect<{ mid: number }>// Sequential (default): one at a time.const serial = Effect.forEach(employeeIds, loadCompBand)// Bounded: at most 10 in flight — kind to the HRIS rate limit.const bounded = Effect.forEach(employeeIds, loadCompBand, { concurrency: 10 })// Unbounded: all at once.const all = Effect.forEach(employeeIds, loadCompBand, { concurrency: "unbounded" })// Fire-and-collect a heterogeneous bundle; first failure interrupts the rest.const bundle = Effect.all([loadCompBand("emp_1"), loadCompBand("emp_2")], { concurrency: 2 })
The Effect.all contract. Do not read it as Promise.all (eager and unbounded) or as Promise.allSettled (accumulating): it is lazy, sequential unless told otherwise, and fail-fast unless told otherwise.
Facet
Contract
Shape
A tuple returns a tuple, an iterable returns an array, and a record of effects returns a record with the same keys. Positions and keys follow the input, even when a later member finishes first. Prefer the record form for unrelated inputs — there is no positional destructuring to get wrong.
Default mode
Fail-fast, no partial results. Sequentially, members after the first failure never start; concurrently, the first failure interrupts the siblings still running. The resulting Cause holds that first failure only.
{ mode: "result" }
Runs every member and returns a Result per slot, so the combined effect has E = never. The only modes are "default" and "result".
{ discard: true }
Side effects only: the result is void and no collection is built.
Accumulating over a collection
Effect.partition(items, f) never fails and returns [successes, failures]; Effect.validate(items, f) fails with a non-empty array of every error. Both are covered in Errors, Option & Result.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const loadBand: Effect.Effect<{ readonly mid: number }, "BandMissing">declare const loadBudget: Effect.Effect<number, "BudgetMissing">// Record in, record out.const inputs = Effect.all({ band: loadBand, budget: loadBudget }, { concurrency: 2 })// Effect<{ band: { readonly mid: number }; budget: number }, "BandMissing" | "BudgetMissing">// Run every slot and keep each outcome; this effect cannot fail.const outcomes = Effect.all([loadBand, loadBudget], { mode: "result" })// Effect<[Result<{ readonly mid: number }, "BandMissing">, Result<number, "BudgetMissing">]>// Side effects only.const announce = Effect.all([Effect.log("cycle open"), Effect.log("budget loaded")], { discard: true })
For exactly two effects, Effect.zip(a, b) returns the pair and Effect.zipWith(a, b, f) combines them; both are sequential unless you pass { concurrent: true } (a boolean — not the concurrency option used elsewhere). Effect.zipLeft / zipRight no longer exist; see section 9.
Official guide: Basic Concurrency (its printed Cause output shows nested Parallel / Sequential nodes; a Cause here is flat — see Cause). The guide for zip, forEach, and all shapes is linked from section 9.
Effect.race returns the first success and interrupts the loser; raceFirst lets the first completion (success or failure) win. Effect.timeout fails with Cause.TimeoutError; timeoutOption gives Option.none instead; timeoutOrElse runs a fallback.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const livePayBand: Effect.Effect<number>declare const cachedPayBand: Effect.Effect<number>// Whichever source answers first wins; the other is interrupted —// the live HRIS and a warm replica race for the band midpoint.const fastest = Effect.race(livePayBand, cachedPayBand)// Bound a flaky HRIS call; on timeout, fall back to last night's snapshot.const guarded = livePayBand.pipe( Effect.timeoutOrElse({ duration: "2 seconds", orElse: () => Effect.succeed(150_000) // cached midpoint }))
Race semantics, precisely.
Operator
Who wins
When every contender fails
Losers
Effect.race(a, b) / Effect.raceAll([...])
the first success — an early failure does not end the race
fails with one flat Cause holding every contender's failure reasons
interrupted, and the race result is delivered only after their finalizers finish
Effect.raceFirst(a, b) / Effect.raceAllFirst([...])
the first completion, success or failure
not applicable — the first failure already won
same as above
race is raceAll with two members, and raceFirst is raceAllFirst with two. Because losers are interrupted, a branch that owns a resource must be interruptible and finalizer-backed, and a slow loser finalizer delays the winner's result. The interruption is sent in the same step that settles the race, before the racing fiber resumes, so a loser suspended in an interruptible wait cannot complete afterwards and have its result thrown away: Effect.timeoutOption(Queue.take(queue), "1 second") either returns the item or leaves it in the queue. Interruption reaches every loser even if the race settles (or is itself interrupted) while some contenders are still starting — none are left running unsupervised. Every race function accepts { onWinner }, a purely observational callback receiving { fiber, index, parentFiber } — useful for a "which replica answered" metric. Wrap each side in Effect.result when you want the first settled outcome as a value.
Timeout semantics. All three operators are built on raceFirst against a sleep, so they interrupt the source when the deadline passes and wait for that interruption — including the source's finalizers — before continuing. Effect.timeoutOrElse evaluates its fallback only after the source has finished interrupting, in the caller's fiber, so the fallback never overlaps the source's cleanup. A source failure that happens before the deadline is preserved as-is by all three, and Effect.timeoutOption maps only the timeout to Option.none() — typed failures stay in E, so it is not a failure suppressor. There is no timeoutFail / timeoutFailCause / timeoutTo: to surface a domain error, fail from orElse (reserve Effect.die there for invariant violations).
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"class HrisTimeout extends Schema.TaggedError<HrisTimeout>()("HrisTimeout", { afterMillis: Schema.Int}) {}declare const primaryBand: Effect.Effect<number, "PrimaryDown">declare const replicaBand: Effect.Effect<number, "ReplicaDown">// First success wins; a replica that fails fast does not end the race.const fastestBand = Effect.raceAll([primaryBand, replicaBand], { onWinner: ({ index }) => console.log(`band source #${index} answered first`)})// A domain error instead of Cause.TimeoutError.const bounded = fastestBand.pipe( Effect.timeoutOrElse({ duration: "2 seconds", orElse: () => Effect.fail(new HrisTimeout({ afterMillis: 2000 })) })) // Effect<number, "PrimaryDown" | "ReplicaDown" | HrisTimeout>
Warning: A deadline can only fire where the fiber can be interrupted. A long synchronous section (a tight loop, a large JSON.parse) runs to completion — and can even beat the deadline it overran — before Effect.timeout can act, and an interrupted adapter that ignores its AbortSignal leaves the foreign work running — see section 8.
Official guides: Timing Out, Basic Concurrency (it says an all-failing raceAll fails with the last error; it instead fails with one Cause collecting every contender's failure reasons).
Interruption is cooperative and first-class. Effect.uninterruptible protects a critical section; uninterruptibleMask provides a restore to re-open windows inside it. Effect.acquireRelease guarantees cleanup runs on any exit — success, failure, or interruption. ensuring attaches an unconditional finalizer.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const openHrisConnection: Effect.Effect<{ close: () => void query: (sql: string) => string}>// Acquire/release ties cleanup to the surrounding scope. Requires Scope,// so run it under Effect.scoped (or a Layer).const readHeadcount = Effect.gen(function*() { const conn = yield* Effect.acquireRelease( openHrisConnection, (c) => Effect.sync(() => c.close()) // always runs, even if a review is interrupted ) return conn.query("SELECT count(*) FROM employees")}).pipe(Effect.scoped)
What try / finally cannot do.finally protects only code that runs after try was entered, so setup between "acquire" and try leaks; a throwing cleanup replaces the original error; and nothing runs at all when the caller simply abandons the Promise. Effect's brackets close all three gaps, and they also run on interruption.
Choose the bracket by the lifetime's shape, then name the owner.
Lifetime shape
Tool
Who closes it
May cleanup fail in E?
Exactly one operation; the handle must not escape
Effect.acquireUseRelease(acquire, use, release)
the bracket, as soon as use ends
yes — release receives use's Exit and may fail
Acquire now, use across several later steps
Effect.acquireRelease(acquire, release), which adds Scope to R
whoever discharges Scope: Effect.scoped, a Layer build, or a manually closed scope
the layer's scope: Layer.launch under runMain, ManagedRuntime.dispose(), or the test layer's teardown
no
Cleanup around existing work, no resource value
Effect.ensuring(finalizer)
runs when the wrapped effect ends
no
Cleanup that depends on the outcome
Effect.onExit, Effect.onError, Effect.onInterrupt
runs when the wrapped effect ends
onExit and onInterrupt yes; onError no
Register cleanup in the current scope without a resource value
Effect.addFinalizer((exit) => ...)
the scope's owner
no
Scope still in R means nobody owns the resource yet.acquireRelease registers cleanup but does not decide who closes it; the requirement stays in the type until an owner discharges it. Read a signature such as Effect<Conn, never, Scope> as "a connection whose lifetime the caller must choose".
Finalizer
Runs on
Receives
Effect.ensuring(fin)
every outcome
nothing — it cannot tell how the work ended
Effect.onExit((exit) => ...)
every outcome
the full Exit<A, E>
Effect.onError((cause) => ...)
typed failure, defect, or interruption
the Cause<E>
Effect.onInterrupt((ids) => ...)
interruption only
the ReadonlySet<number> of interrupting fiber ids
Effect.addFinalizer((exit) => ...), or the release of acquireRelease
the owning scope closing
the Exit that closed the scope
Fragment · Type-checked
ts
import { Effect, Exit } from "effect"declare const openLedgerTx: Effect.Effect<{ readonly post: (entry: string) => Effect.Effect<void, "LedgerDown"> readonly commit: Effect.Effect<void> readonly rollback: Effect.Effect<void>}>// One operation; the handle cannot escape; release sees how `use` ended.const postRaise = Effect.acquireUseRelease( openLedgerTx, (tx) => tx.post("raise:emp_142:8500"), (tx, exit) => (Exit.isSuccess(exit) ? tx.commit : tx.rollback))declare const settlePayroll: Effect.Effect<number, "LedgerDown">const audited = settlePayroll.pipe( Effect.onInterrupt(() => Effect.logWarning("payroll run cancelled")), // interruption only Effect.onError((cause) => Effect.logError("payroll run did not complete", cause)), // anything but success Effect.onExit((exit) => Effect.logInfo(`payroll run finished: ${exit._tag}`)), // always, with the Exit Effect.ensuring(Effect.logDebug("run lock released")) // always, outcome unknown)
Facts that decide correctness:
Finalizers of a scope run in reverse registration order, so a dependent resource closes while the thing it depends on is still alive (Scope.make("parallel") opts into concurrent finalization).
The acquire step is uninterruptible by default ({ interruptible: true } opts out), so a resource is never half-acquired without its finalizer registered. Finalizers also run uninterruptibly: an unbounded finalizer is an unbounded shutdown.
Release is registered only after acquire succeeds. If one acquire effect allocates two things and fails on the second, nothing releases the first. Give each allocation its own acquireRelease (the earlier one then unwinds when the later one fails) or make the acquire effect roll back its own partial work. The same applies inside a Layer.effect build.
Effect.acquireUseRelease releases even when use throws synchronously before returning an effect; the throw becomes a defect.
Cleanup attached with Effect.tap or Effect.andThen is success-only. It passes every happy-path test and leaks on failure and interruption.
Compare interrupted exits with Exit.hasInterrupts(exit), not structural equality — the cause carries a fiber id. Effect.interrupt is how a fiber cancels itself.
Fragment · Type-checked
ts
import { Effect } from "effect"interface Cursor { readonly readAll: Effect.Effect<ReadonlyArray<string>> readonly close: Effect.Effect<void>}declare const openPool: Effect.Effect<{ readonly openCursor: Effect.Effect<Cursor, "CursorLimit"> readonly close: Effect.Effect<void>}>// One acquireRelease per allocation: if `openCursor` fails, the pool is still released.const exportRoster = Effect.gen(function*() { const pool = yield* Effect.acquireRelease(openPool, (p) => p.close) // registered first, closed last const cursor = yield* Effect.acquireRelease(pool.openCursor, (c) => c.close) // closed first, pool still alive return yield* cursor.readAll}).pipe(Effect.scoped)
Limits of cooperative interruption. User code never polls a cancellation flag: an interruptible fiber that is suspended — sleeping, awaiting a callback, waiting on a queue — is resumed with the interruption at once, and code opts out only by marking a region uninterruptible. Two things interruption cannot do: pre-empt a long synchronous section (a tight loop or a large JSON.parse finishes first), and force an uncooperative external system to stop — that needs a real cancel mechanism such as the AbortSignal in section 8, a driver-level cancel, or a process kill. What to do when the cleanup itself can fail is section 10; manual scopes and finalizer order are under Scope. For the full startup, readiness, and shutdown story see Owning Lifetimes — Startup, Readiness, and Shutdown.
Effect.reduce(iterable, () => zero, step) is the effectful, strictly sequential fold: the lazy seed is rebuilt on every run, the step receives its zero-based index, and the first failure stops later steps. For context, provideContext satisfies part of an environment while retaining unrelated outer services; setContext replaces the wrapped effect's entire environment with an already-complete Context. updateServiceScoped(Service, f, { reset? }) temporarily updates a service until scope close and can merge the original, updated, and then-current values while restoring it.
Two small accessors round this out: Effect.withFiberSucceed((fiber) => value) computes a value from the current fiber without building an effect (the effectful sibling is Effect.withFiber), and Effect.head(effect) takes the first element of an effect's iterable result, failing with Cause.NoSuchElementError when it is empty.
8. Cancellable adapters for promises and callbacks
Interruption stops the fiber. The socket, query, timer, or child process behind an adapter keeps running — and keeps holding its connection or quota — unless the adapter tells the foreign API to stop. Deadlines, races, and structured shutdown are only as good as the leaf adapters, so the chain must be unbroken: host signal → root fiber interruption → the adapter's AbortSignal → foreign cancel → finalizers.
Create the Promise inside the thunk and forward the signal.Effect.tryPromise and Effect.promise hand the thunk an AbortSignal that is aborted when the fiber is interrupted (timeout, lost race, scope close, shutdown). The AbortController is allocated only when the thunk declares the parameter, so an adapter written as () => fetch(url) costs nothing and cancels nothing.
For callback APIs, pass the signal or return a cleanup effect.Effect.callback's register function receives (resume, signal); for APIs without abort support, return an Effect<void> that detaches the listener or clears the timer.
Keep cancellation as cancellation. Interrupting a tryPromise produces an interrupt-only Cause. The catch mapper may still be invoked for the resulting AbortError, but its value is discarded — so keep catch a pure mapping with no logging or metrics. Hand-written adapters must preserve this: an abort is never a RequestFailed, never a retry trigger, and never logged as a fault by default.
Let Effect.timeout own the deadline. A second wall-clock timer inside the adapter (setTimeout, AbortSignal.timeout) cannot be driven by TestClock and races the outer deadline.
If the adapter accepts an external signal, check signal.aborted first and refuse before starting transport work.
A foreign Promise is a trust boundary. Whatever it rejects with is unknown. Mapping all of it to one domain error makes a TypeError inside the adapter indistinguishable from an expected outage, and a retry policy will then happily retry a bug. Recognize the failures the contract allows and Effect.die the rest.
Interrupting tryPromise does not wait for the Promise to settle. It aborts the signal and continues immediately. When the next step must not overlap the previous attempt's teardown (a retry after a timeout, releasing a lock), build the adapter with Effect.callback and return a cleanup effect that awaits settlement; Fiber.interrupt, Effect.timeout, and Effect.race then wait for it.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"class PayrollApiDown extends Schema.TaggedError<PayrollApiDown>()("PayrollApiDown", { status: Schema.Int}) {}class UnrecognizedSdkFailure extends Schema.TaggedError<UnrecognizedSdkFailure>()("UnrecognizedSdkFailure", { cause: Schema.Defect()}) {}interface Receipt { readonly receiptId: string}declare const payrollSdk: { submitRun(runId: string, options: { readonly signal: AbortSignal }): Promise<Receipt>}declare const isOutage: (cause: unknown) => cause is { readonly status: number }// Promise adapter: lazy, abortable, and honest about what it recognizes.const submitRun = Effect.fn("submitRun")((runId: string) => Effect.tryPromise({ try: (signal) => payrollSdk.submitRun(runId, { signal }), catch: (cause) => isOutage(cause) ? new PayrollApiDown({ status: cause.status }) // allowed by the contract: stays typed : new UnrecognizedSdkFailure({ cause }) }).pipe( // Anything the contract does not allow is a bug: a defect, invisible to retry policies. Effect.catchTag("UnrecognizedSdkFailure", (failure) => Effect.die(failure.cause)) ))// Callback API that understands AbortSignal: the listener is removed on interruption.const nextApproval = (bus: EventTarget) => Effect.callback<Event>((resume, signal) => { bus.addEventListener("raise-approved", (event) => resume(Effect.succeed(event)), { once: true, signal }) })// Interruption completes only after the foreign Promise has settled.const submitRunAndSettle = (runId: string) => Effect.callback<Receipt, unknown>((resume, signal) => { const running = payrollSdk.submitRun(runId, { signal }) running.then((receipt) => resume(Effect.succeed(receipt)), (cause) => resume(Effect.fail(cause))) return Effect.promise(() => running.then(() => undefined, () => undefined)) })
Effect.abortSignal is the scope-bound variant — an Effect<AbortSignal, never, Scope> whose signal is aborted when the surrounding scope closes — for APIs that take a signal outside a Promise adapter, such as a long-lived subscription.
Effect 4 keeps the control-flow surface small: branch with ordinary if / ternaries and loop with ordinary for / while inside Effect.gen or Effect.fn, and reach for an operator only when the condition is itself an effect. Coding agents routinely emit the operators below, which do not exist in Effect 4.
Not in Effect 4
Write instead
Effect.if, Effect.unless
a JavaScript conditional inside Effect.gen, or Effect.suspend(() => cond ? a : b)
Effect.whenEffect, Effect.unlessEffect
Effect.when(self, conditionEffect); negate the condition for "unless"
Effect.loop, Effect.iterate
a for / while loop in Effect.gen; Effect.forEach or Effect.reduce for collections
Effect.zipRight
Effect.andThen(next)
Effect.zipLeft
Effect.tap(next), or Effect.zip followed by Effect.map
Effect.when takes an Effect<boolean> — not a boolean and not a thunk, so Effect.when(() => cond) does not type-check — and reports the skipped case as Option.none(), so its result type is Option<A>. Effect.whileLoop({ while, body, step }) still exists, but it is a low-level primitive that returns void; prefer a generator loop.
Fragment · Type-checked
ts
import { Effect } from "effect"import type { Option } from "effect"declare const cycleIsFrozen: Effect.Effect<boolean>declare const notifyManager: Effect.Effect<void>// Plain condition and plain loop: ordinary JavaScript inside a generator.const drawDown = Effect.fn("drawDown")(function*(pool: number, raises: ReadonlyArray<number>) { let remaining = pool for (const raise of raises) { if (raise > remaining) return yield* Effect.fail("OverBudget" as const) remaining -= raise } return remaining})// Effectful condition: a skip is Option.none(). This is the old `unlessEffect` shape.const maybeNotified: Effect.Effect<Option.Option<void>> = notifyManager.pipe( Effect.when(Effect.map(cycleIsFrozen, (frozen) => !frozen)))
Official guide: Control Flow Operators (its whileLoop signature block shows an Effect.loop-style shape; the real whileLoop takes { while, body, step }, has no state, no result array, and no discard).
The finalizer of Effect.acquireRelease, Effect.ensuring, Effect.onError, and Effect.addFinalizer must have error type never. Finalizers are infallible by type, so a fallible close() forces you to decide what a failed teardown means — before it compiles.
shutdown must not hang on a dead peer — a telemetry exporter, a remote flush
Escalate to a defect
close.pipe(Effect.orDie)
a failed close is a bug, or leaves state you cannot reason about
Report to the caller
Effect.acquireUseRelease or Effect.onExit, whose cleanup may fail in E
the caller must see it — a commit or flush whose failure means lost data
Whatever you choose, the original outcome is not overwritten. When use fails and the release fails too, both reasons are present in the resulting Cause. This is not "last error wins", so tests should assert through Effect.exit and inspect cause.reasons rather than expect one error to replace the other. A finalizer that dies next to a typed failure also takes precedence: the typed failure is recorded as a defect too ([Die(error), Die(defect)]), so the caller's catchTag no longer handles it — which is why "escalate to a defect" is a real decision, not a tidy-up (Recovery and mixed causes). Remember that Effect.ignore absorbs typed failures only; use Effect.ignoreCause to absorb defects as well.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const openExporter: Effect.Effect<{ readonly flush: Effect.Effect<void, "ExporterUnreachable">}>// Bounded, best-effort exporter shutdown: never fails, never hangs.const exporter = Effect.acquireRelease(openExporter, (handle) => handle.flush.pipe( Effect.timeout("5 seconds"), Effect.ignore({ log: "Warn", message: "exporter flush failed during shutdown" }) ))
Keep finalizers small, reliable, and time-bounded: they run uninterruptibly, so an unbounded finalizer is an unbounded shutdown.
Nothing runs until a runner is called. Choose the runner by the outcome contract the host needs, and treat every runFork as an ownership obligation — somebody must join, observe, or interrupt the fiber it returns.
Runner
Returns
Failure surfaces as
Choose when
Effect.runSync
A
a throw of the squashed cause (the typed error value itself, or the defect); throws Cause.AsyncFiberError at the first async boundary
the effect is known to finish synchronously. The types cannot tell you that, so this is a deliberate edge case, not a default.
Effect.runSyncExit
Exit<A, E>
never throws; async work shows up as a defect holding AsyncFiberError
a synchronous edge that wants the outcome as data
Effect.runPromise
Promise<A>
a rejection with the squashed cause — the Fail / Die / Interrupt distinction is lost
a JavaScript edge that wants value-or-rejection
Effect.runPromiseExit
Promise<Exit<A, E>>
always resolves
an adapter, reporter, or test that must keep typed failure, defect, and interruption apart. Prefer it whenever the host can represent the outcome.
Effect.runFork
Fiber<A, E>, immediately
Fiber.await or fiber.addObserver
the caller keeps the handle and owns its lifetime. The other runners are built on it.
Effect.runCallback
an interruptor function
the onExit callback receives the Exit
callback-style hosts
Platform runMain
void
a logged error and a process exit code — see Runtime
Every runner except runSync / runSyncExit accepts RunOptions: signal (aborting it interrupts the fiber), scheduler, uninterruptible, and onFiberStart. Each also has a curried *With(context) twin — Effect.runPromiseWith(context)(effect), runForkWith, runSyncWith, and so on — for a host that already holds a Context<R> (captured with Effect.context<R>() inside a Layer, or assembled with Context.make) and wants to run effects requiring exactly R without paying for a ManagedRuntime.
Run at owned edges, not "once". A server, a test runner, and a plugin host each legitimately run many effects. The rule is that reusable code — services, domain functions, libraries — never calls a runner.
An interior runner severs supervision.Effect.promise(() => Effect.runPromise(inner)) type-checks and returns the right value, but:
inner is now a separate root fiber: interrupting the outer fiber (timeout, race, shutdown) does not reach it, so it runs to completion unobserved;
bare runners start from an empty context, so inner loses the surrounding services and references — the provided Clock (and therefore TestClock), loggers, the current span — and its R must already be fully provided;
its typed failure is flattened into a rejection, which Effect.promise then reports as a defect.
The fix is almost always to return the effect and let the caller compose it. If a nested runner is genuinely unavoidable (a third-party callback insists on a Promise), forward the adapter's signal so interruption still crosses the gap, and carry the Exit across so the failure keeps its type. A second variant of the same mistake is calling a runner while building a description (Effect.runSync(parse(x)); return workflow), which makes construction non-inert.
Fragment · Type-checked
ts
import { Cause, Effect, Exit } from "effect"declare const recomputeBudget: Effect.Effect<number, "LedgerDown">// A host edge that keeps the three outcomes apart. The runner looks at `signal` only// after the fiber's first synchronous run, so check an already-aborted signal yourself.const onRecomputeRequest = async (signal: AbortSignal): Promise<string> => { if (signal.aborted) return "client went away" const exit = await Effect.runPromiseExit(recomputeBudget, { signal }) if (Exit.isSuccess(exit)) return `budget ${exit.value}` return Cause.hasInterruptsOnly(exit.cause) ? "cancelled" : "failed"}// Unavoidable nested runner: `{ signal }` restores interruption, and re-raising the// Exit restores the typed failure.const throughLegacyHook = <A, E>(inner: Effect.Effect<A, E>): Effect.Effect<A, E> => Effect.promise((signal) => Effect.runPromiseExit(inner, { signal })).pipe(Effect.flatten)
Reach for it when you want typed errors, dependency injection, structured concurrency, and interruption-safe resource handling as the default.
An ordered failover policy for an Effect or Stream. Each step provides the services needed by the same computation and may add an attempt count, a retry Schedule, or a while predicate. Effect.withExecutionPlan reruns the computation under each step until it succeeds or the plan is exhausted; Stream.withExecutionPlan does the same for an entire stream execution.
The retry schedule sleeps between attempts, so the program is asynchronous: run it with Effect.runPromise (or inside a larger program). Effect.runSync would throw an AsyncFiberError instead of returning.
attempts is per step; ExecutionPlan.CurrentMetadata exposes the cumulative 1-based attempt and 0-based step index inside the computation. The optional onEvent observer receives strictly ordered AttemptStart / AttemptSuccess / AttemptFailure events: attempt is cumulative, stepAttempt resets for each step, and failures carry the full Cause. Every start is paired with one terminal event, including interruption; observer failure cannot change the computation's outcome. ExecutionPlan.merge concatenates independently defined plans, while plan.captureRequirements captures services needed to build its layers and schedules.
Reach for it when one operation should retry or fail over across interchangeable service implementations — regional endpoints, model providers, replicas, or storage tiers — without putting fallback branching inside the operation itself.
The low-level toolkit for making custom values behave like effects — so they can be yield*-ed inside Effect.gen and evaluated by the runtime. It exposes three entry points: Effectable.Class<A, E, R> (abstract base class), Effectable.Mixin(Base) (insert the Effect prototype into an existing class hierarchy), and Effectable.Prototype (class-free builder). With Class and Mixin you implement one abstract method, asEffect(), returning the Effect your value stands for. The runtime calls it on the instance for each execution, so it sees current receiver state and the services provided at that point. This explains why non-Effect types (e.g. a Context.Service key) are still yieldable.
Self-contained source · Type-checked
ts
import { Clock, Effect, Effectable } from "effect"// A domain value that *is* an Effect when evaluated: "the current// review-cycle timestamp", read through the testable Clock.class ReviewClockStamp extends Effectable.Class<number> { // The abstract member is the effect this value stands for. asEffect() { return Clock.currentTimeMillis }}// Mixin keeps an existing base class (and its constructor) and infers A/E/R// from the concrete asEffect() return type.class ReviewCycle { readonly cycleId: string constructor(cycleId: string) { this.cycleId = cycleId }}class OpenedReviewCycle extends Effectable.Mixin(ReviewCycle) { asEffect() { return Effect.map(Clock.currentTimeMillis, (at) => ({ cycleId: this.cycleId, at })) }}const program = Effect.gen(function*() { // Yielding the value evaluates its asEffect(). const stampedAt = yield* new ReviewClockStamp() const opened = yield* new OpenedReviewCycle("2025-Q4") return { event: "cycle-opened", at: stampedAt, opened }})
With Mixin, Effect's prototype members shadow same-named base members: pipe, toString, toJSON, [Symbol.iterator], and the Node inspect hook.
Reach for it when building a library primitive or DSL whose values should be first-class citizens of Effect.gen.
What happens after you build an Effect: how it finishes (Exit and its full Cause), the fibers that run it and the handles that supervise them, the Scope that bounds every resource, the scheduler and clock underneath, the one-shot and gate primitives fibers coordinate with, and the runtimes that run Effects from non-Effect code. Core Runtime & Execution covers building and combining Effects; this page covers owning them while they run.
An Effect is only a description until an owned edge runs it on a root fiber. Every fiber it forks has an owner that ends it, every resource is released by the Scope that acquired it, and the run ends in an Exit carrying the full Cause.
Exit<A, E> is the result of a finished computation: either Success<A> (holding the value) or Failure<A, E> (holding a Cause<E>). Returned by runSyncExit, runPromiseExit, Fiber.await, and finalizers. An Exit is itself an Effect, so you can yield* it to re-raise its result. Pattern-match with Exit.match, or guard with isSuccess / isFailure.
Self-contained source · Type-checked
ts
import { Cause, Effect, Exit, Fiber } from "effect"const program = Effect.gen(function*() { // Run a per-employee review task and capture its outcome as data // instead of letting a single failure propagate. const fiber = yield* Effect.forkChild(Effect.fail("hris timeout")) const exit = yield* Fiber.await(fiber) // Exit<never, string>, never fails return exit})// Branch on a finished review result.const describe = (exit: Exit.Exit<number, string>) => Exit.match(exit, { onSuccess: (raise) => `approved raise: ${raise}`, // onFailure receives the *Cause*, not a bare error. onFailure: (cause) => `review failed: ${Cause.pretty(cause)}` })
Note: Use Effect.catch for error handling within effects. Use Exit at boundaries where a computation has already finished and you need to inspect the result as a value: awaiting a fiber, reading a finalizer's exit, or running at the app edge with runSyncExit.
Inside an effect, Effect.exit(self) captures the complete outcome — typed failure, defect, and interruption — as a value with E = never; Effect.result captures only the typed failure. Construct exits with Exit.succeed, Exit.fail, Exit.die, Exit.interrupt, and Exit.failCause(cause); classify them with Exit.hasFails / Exit.hasDies / Exit.hasInterrupts — plain boolean checks, like their Cause counterparts, so a false does not narrow the exit; narrow with Exit.isSuccess / Exit.isFailure — and pull the first typed error out with Exit.findErrorOption. Test assertions should match on this structure, never on rendered failure text.
The complete, structured record of why an effect failed. A single failure can be several things simultaneously — a typed error, a finalizer that threw, and an interruption. Cause retains all of them. A Cause is a flat array of reasons. There are exactly three reason kinds: Fail (typed error), Die (unexpected defect), and Interrupt (fiber cancelled). An empty cause is an empty array.
Self-contained source · Type-checked
ts
import type { Cause } from "effect"type CauseShape<E> = { readonly reasons: ReadonlyArray<Cause.Reason<E>>}// Cause.Reason<E> = Cause.Fail<E> | Cause.Die | Cause.Interrupt
Because it's flat, inspection is a loop, not a recursion. Narrow each reason with is*Reason guards; query whole-cause with hasFails / hasDies / hasInterrupts.
Fragment · Type-checked
ts
import { Cause } from "effect"const summarize = (cause: Cause.Cause<string>): string => { for (const reason of cause.reasons) { if (Cause.isFailReason(reason)) return `comp error: ${reason.error}` if (Cause.isDieReason(reason)) return `defect: ${String(reason.defect)}` if (Cause.isInterruptReason(reason)) return `cycle interrupted by ${reason.fiberId}` } return "empty cause"}// Whole-cause predicates avoid hand-rolling the loop.declare const cause: Cause.Cause<string>const wasCancelledCleanly = Cause.hasInterruptsOnly(cause)const allFails = cause.reasons.filter(Cause.isFailReason)
When a Cause holds more than one reason. Reasons accumulate where outcomes combine: a failing use plus a failing finalizer (section 10 of Core Runtime & Execution), every contender of a race that nobody won, or an explicit Cause.combine(a, b). A fail-fast Effect.all or Effect.forEach is not such a place — it records the first failure only, so later members' failures never appear in reasons; accumulate with { mode: "result" }, Effect.partition, or Effect.validate instead.
Constructing and re-raising. Build causes with Cause.fail(error), Cause.die(defect), Cause.interrupt(fiberId?), and Cause.combine; fail with one through Effect.failCause(cause) (a die-only or interrupt-only cause leaves E = never). After Effect.catchCause, propagate what you cannot handle with Effect.failCause(cause)unchanged — Effect.fail(Cause.squash(cause)) collapses the record to a single value. Interrupt.fiberId is number | undefined.
Rendering.Cause.pretty(cause) is for humans: an empty cause renders as the empty string, a non-Error failure is wrapped as Error: <value>, and a combined cause renders one block per reason. Cause.prettyErrors(cause) returns the per-reason Error objects for a reporter. Both are diagnostics that change between releases — never assert on them.
Reach for it when you need to distinguish a typed error from a defect from an interruption, inspect every reason when outcomes combine, or render a full diagnostic with Cause.pretty.
The typed recovery operators — Effect.catch, catchTag / catchTags, catchIf, Effect.match, Effect.result, Effect.retry, and Effect.orDie — look up the first Fail reason in the flat cause, with one rule first: a defect takes precedence. If the cause holds any Die, they do not recover; they turn every typed error into a defect and propagate it. If there is no Fail, the cause passes through untouched. An interruption beside a Fail does not block recovery, and is dropped when the handler's result replaces the outcome. Effect.mapError is not recovery: it maps every typed error in place and keeps all other reasons.
Input cause
Effect.catch(() => fallback)
Effect.orDie
Guarded catchCause (below)
Die only
unchanged — still a defect
unchanged
unchanged
Fail only
success with the fallback
Die(error)
success with the fallback
Fail + Die
Die(error) + Die(defect) — the handler does not run
Die(error) + Die(defect)
unchanged — both reasons kept
Fail + Interrupt
success — the interruption is lost
Die(error) — the interruption is lost
unchanged — both reasons kept
two Fail reasons
the handler sees only the first
Die(first)
success with the fallback
The runtime applies the same precedence when it combines outcomes itself: a typed failure followed by a dying finalizer, or a failing fiber whose interrupted sibling dies during cleanup, already yields [Die(error), Die(defect)].
So: where an interruption or a second typed failure recorded alongside matters, recover through Effect.catchCause with an explicit guard; recover from a defect only deliberately, with Effect.catchDefect or catchCause; and never use Effect.orDie as a way to tidy an error union. Effect.tapError and the finalizer family observe without replacing, so they are safe.
Self-contained source · Type-checked
ts
import { Cause, Effect } from "effect"// Recover the expected failure only when nothing else went wrong alongside it.const recoverCleanFailure = <A, E, R>(self: Effect.Effect<A, E, R>, fallback: A) => self.pipe( Effect.catchCause((cause) => Cause.hasDies(cause) || Cause.hasInterrupts(cause) ? Effect.failCause(cause) // not ours to handle: propagate every reason : Effect.succeed(fallback) ) )
Effect.sandbox(self) is the other route: it moves the whole Cause<E> into the error channel so ordinary typed combinators (catch, mapError, result) see it. There is no unsandbox; restore the normal model with Effect.catch(Effect.failCause). For a single recovery step catchCause is simpler. The operator-by-operator treatment is in Errors, Option & Result.
Fiber<A, E> is a lightweight green thread — a running or finished execution of an effect. You don't construct one directly; you get a handle from Effect.forkChild (and friends). A child fiber is bound to its parent's lifetime: when the parent ends, the child is interrupted — no leaks. Fiber.await gives you the Exit (never fails); Fiber.join propagates the result into the current effect (fails if the fiber failed); Fiber.interrupt cancels it and waits for cleanup.
Self-contained source · Type-checked
ts
import { Effect, Fiber } from "effect"const program = Effect.gen(function*() { // forkChild: a supervised child that recomputes one employee's vested equity. const valuation = yield* Effect.forkChild( Effect.gen(function*() { yield* Effect.sleep("1 second") return 4_250 // vested shares as of today }) ) // join propagates success/failure into this fiber... const vested = yield* Fiber.join(valuation) // ...whereas await would hand back the Exit without failing. return vested})
A fork returns a handle, not a result, and a Fiber is not yieldable — yield* fiber does not compile. Turn handles back into effects and then use ordinary combinators: Fiber.join for one, Fiber.joinAll(fibers) for an array of results, Fiber.awaitAll(fibers) for an array of exits, Fiber.interruptAll(fibers) to cancel a group. Low-level integrations that read a fiber's derived state use fiber.cache (scheduler, span, logLevel, minimumLogLevel, maxOpsBeforeYield, ...); there is no separate family of current* fields. Once a fiber exits, its cache.span and cache.stackFrame are cleared, so a finished fiber held by a cache entry, an observer, or a Deferred does not keep its last span and that span's parents alive.
Official guide: Fibers (its prose calls Effect.yieldNow(); Effect.yieldNow is a value, not a function, and the guide does not mention startImmediately).
Reach for it when you need manual control over a background task — fork work, keep the handle, and await or interrupt on your own schedule. For fixed bundles of work, prefer Effect.all/forEach with { concurrency }.
Name the owner first; the fork function follows. The four fork functions differ only in who is responsible for interrupting the fiber.
Function
Owner
Interrupted when
Choose when
Avoid when
Effect.forkChild(effect)
the current fiber
the parent ends — success, failure, or interruption — and the child's finalizers run
the work must not outlive the code that started it: a helper for this request or this batch
the work has to survive the function that forked it
Effect.forkScoped(effect) (adds Scope to R)
the surrounding Scope
that scope closes
background work owned by a Layer, a request scope, or a test
the nearest scope closes too early — wrapping the fork itself in Effect.scoped interrupts it at once
Effect.forkIn(effect, scope)
a Scope you were handed, or captured with Effect.scope
that scope closes
"start it here, own it there" — forked inside an inner scope but owned by an outer one
the current scope is already the right owner
Effect.forkDetach(effect)
nobody — the global scope
never, unless someone keeps the handle and interrupts it
process-lifetime work with a documented stop path
library and domain code. If nobody can say who interrupts a detached fiber, it is a leak.
Two corollaries: a long-lived loop should be exposed as an effect and run in the caller's fiber or scope rather than forked internally, and reusable code should not create root fibers. All four functions accept { startImmediately, uninterruptible }. Forking into a scope that has already closed (forkScoped or forkIn) never runs the effect, even with those options: it returns an already-interrupted fiber. For dynamic populations of fibers use FiberHandle, FiberMap, or FiberSet instead of hand-kept handles; the worked example is Structured Concurrency Through a Bounded Worker.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const heartbeat: Effect.Effect<never>declare const pollApprovals: Effect.Effect<never>const meritCycleServer = Effect.scoped(Effect.gen(function*() { const cycleScope = yield* Effect.scope yield* Effect.scoped(Effect.gen(function*() { yield* Effect.forkIn(heartbeat, cycleScope) // owned by the outer scope yield* Effect.forkScoped(pollApprovals) // owned by this inner scope })) // pollApprovals is already interrupted here; heartbeat runs until the outer scope closes.}))
Forking returns the handle immediately; the child is only scheduled and does not run until the current fiber yields or suspends. Code that forks a listener — a PubSub or SubscriptionRef.changes consumer, a queue taker, a latch waiter — and then publishes straight away can therefore lose the first events. Letting the parent yield (yield* Effect.yieldNow, a value, not a function) usually helps but is not a hard ordering guarantee. When the child must register before the parent continues, pass { startImmediately: true }: the child runs synchronously up to its first suspension before the fork returns. The same option removes "has it started yet?" guesses from tests.
Self-contained source · Type-checked
ts
import { Effect, Fiber, Ref } from "effect"const program = Effect.gen(function*() { const events = yield* Ref.make<ReadonlyArray<string>>([]) const record = (event: string) => Ref.update(events, (all) => [...all, event]) const lazyListener = yield* Effect.forkChild(record("listener registered")) yield* record("first approval published") // runs first: the child is only scheduled so far yield* Fiber.join(lazyListener) const eagerListener = yield* Effect.forkChild(record("eager listener registered"), { startImmediately: true }) yield* record("second approval published") // runs after the eager child registered yield* Fiber.join(eagerListener) return yield* Ref.get(events)})// ["first approval published", "listener registered",// "eager listener registered", "second approval published"]
Fiber.interrupt(fiber) completes only after the target has finished — finalizers included — so it back-pressures the caller, and a slow finalizer makes a slow cancel. A fiber inside an uninterruptible region or a finalizer keeps running until that region ends. If the region then fails, the pending interruption still wins: recovery handlers such as Effect.catch are skipped, the typed failure is dropped from the Cause, and the fiber exits interrupted (defects are kept). When the caller must not wait (inside a request handler, under its own deadline), signal and move on: Effect.forkChild(Fiber.interrupt(fiber), { startImmediately: true }) sends the interruption before continuing while cleanup proceeds in the background, and fiber.interruptUnsafe() is the synchronous hook that platform runMain uses for SIGINT. A public "cancel" API should say which of the two it offers: request cancellation or await cleanup.
A scoped holder for at most one fiber. Setting a new fiber interrupts the previous one (unless onlyIfMissing is passed); closing the owning scope interrupts the current fiber automatically, and also waits for replaced fibers that are still running their interruption cleanup. "Latest wins." The structured-concurrency answer to the let current; current?.cancel(); current = start() pattern.
Fragment · Type-checked
ts
import { Effect, FiberHandle } from "effect"// Recompute the merit-budget pool whenever a recommendation changes.declare const recomputeBudget: Effect.Effect<void>const makeBudgetRecomputer = Effect.gen(function*() { const handle = yield* FiberHandle.make<void>() // Each edit replaces the in-flight recompute — the older one is interrupted. const trigger = FiberHandle.run(handle, recomputeBudget) yield* trigger yield* trigger // first recompute cancelled, second takes over}).pipe(Effect.scoped) // closing the scope interrupts whatever is running
Reach for it when exactly one instance of a task should be alive at a time and re-triggering should cancel the old one.
A scoped map of fibers keyed by some value. Running work under a key replaces any existing fiber for that key (or skips with onlyIfMissing). Completed fibers remove themselves; closing the scope interrupts all remaining fibers, including replaced ones whose interruption cleanup is still running, and waits for them. FiberHandle generalized from one slot to many, with the same leak-proof guarantee.
Fragment · Type-checked
ts
import { Effect, FiberMap } from "effect"// Run one supervised review task per employee, keyed by employee id.declare const runReview: (employeeId: string) => Effect.Effect<void>const meritCycle = Effect.gen(function*() { const reviews = yield* FiberMap.make<string>() // One supervised fiber per employee. yield* FiberMap.run(reviews, "emp_142", runReview("emp_142")) yield* FiberMap.run(reviews, "emp_207", runReview("emp_207")) // Idempotent start: don't restart a review that's already running. yield* FiberMap.run(reviews, "emp_142", runReview("emp_142"), { onlyIfMissing: true }) const inFlight = yield* FiberMap.size(reviews) return inFlight}).pipe(Effect.scoped) // every review fiber is interrupted on shutdown
Reach for it when you have a dynamic population of keyed background fibers and want them all interrupted cleanly when the parent scope closes.
A scoped, unkeyed bag of fibers. Added fibers remove themselves on completion; closing the scope interrupts whatever remains. FiberSet.awaitEmpty blocks until the set drains. The keyless sibling of FiberMap — use when spawning an unbounded stream of fire-and-forget tasks that need group supervision.
Fragment · Type-checked
ts
import { Effect, FiberSet } from "effect"// Fan out one fiber per raise-approved notification, then wait for the batch.declare const notifyManager: (raise: unknown) => Effect.Effect<void>declare const approvedRaises: ReadonlyArray<unknown>const sendApprovals = Effect.gen(function*() { const fibers = yield* FiberSet.make<void>() for (const raise of approvedRaises) { yield* FiberSet.run(fibers, notifyManager(raise)) // fire-and-supervise } yield* FiberSet.awaitEmpty(fibers) // wait for every notification to finish}).pipe(Effect.scoped)
Official guide: Tracking Fibers (uses FiberSet.size as a live "fibers in flight" gauge).
Reach for it when you spawn many independent throwaway fibers and want them tracked as a group — interrupted together on scope close, or awaited together with awaitEmpty.
Process-lifecycle helpers: makeRunMain (used by platform packages to build runMain), Teardown / defaultTeardown (turn an Exit into a process exit code), error markers for custom exit codes, and the InterruptExitCode annotation for interruptions that end the program on purpose. Application code almost never imports this directly — use NodeRuntime.runMain / BunRuntime.runMain, which are built on makeRunMain. Touch it only to customize how completion maps to an exit code.
Fragment · Type-checked
ts
import { Effect, Exit, Runtime } from "effect"// A custom teardown for the nightly payroll job: log the outcome, then// choose an exit code so the cron wrapper knows whether the run succeeded.const teardown: Runtime.Teardown = (exit, onExit) => { if (Exit.isSuccess(exit)) { onExit(0) } else { console.error("payroll run failed:", exit.cause) onExit(1) }}declare const nightlyPayroll: Effect.Effect<void>// Platform runMain accepts a `teardown` override:// NodeRuntime.runMain(nightlyPayroll, { teardown })
What runMain does by default. It forks the program as the root fiber, interrupts it on SIGINT or SIGTERM (Node and Bun), waits for finalizers, and then sets the exit code through Runtime.defaultTeardown:
Outcome
Exit code
Logged?
Success
0
no
Interrupt-only Cause (a signal arrived, nothing else failed)
130
no
Interrupt-only Cause in which every interruption carries a Runtime.InterruptExitCode annotation
the largest annotated code
no
Any other failure
the squashed error's [Runtime.errorExitCode] when it is a number, otherwise 1
yes, with Effect.logError — unless { disableErrorReporting: true } is passed or the error carries [Runtime.errorReported] = false
Ending the program on purpose by interruption. A component that finishes the program by interrupting the main fiber — a stdio server whose input closed, say — would otherwise report 130, the code for an external signal. Runtime.InterruptExitCode is a Context.Service key whose value is the exit code; attach it to the interruption itself with Fiber.interruptAs(fiber, fiberId, annotations). defaultTeardown reads it from the final Cause, not from the running effect's services, so Effect.provideService(Runtime.InterruptExitCode, 0) does nothing. One unannotated interruption (a real SIGINT or SIGTERM arriving at the same time) keeps the exit code at 130, and a cause that also holds a failure or defect uses the failure path. The RPC and MCP stdio servers exit with 0 this way once stdin closes and pending responses drain.
Self-contained source · Type-checked
ts
import { Context, Fiber, Runtime } from "effect"// The payroll import's input stream ended: stop the main fiber and exit 0, not 130.const finishImport = (main: Fiber.Fiber<void>) => Fiber.interruptAs(main, undefined, Context.make(Runtime.InterruptExitCode, 0))
The two markers let a domain error choose its own exit code and avoid double logging without a custom teardown:
Self-contained source · Type-checked
ts
import { Data, Effect, Runtime } from "effect"class CompConfigInvalid extends Data.TaggedError("CompConfigInvalid")<{ readonly key: string }> { // `override`: Effect augments the global `Error` interface with both optional markers. override readonly [Runtime.errorExitCode] = 78 // the process exits with 78 instead of 1 override readonly [Runtime.errorReported] = false // already reported by the loader; skip runMain's log}const main = Effect.fail(new CompConfigInvalid({ key: "MERIT_BUDGET" }))// NodeRuntime.runMain(main)
The entry-point recipe is Recipe: A Graceful Node Entrypoint. Official guide: Platform Runtime (it describes exit codes as only 0 and 1 and names only SIGINT; the runtime also uses 130 for interruption-only failures and listens for SIGTERM as well as SIGINT).
Reach for it when writing a platform adapter or needing bespoke exit-code logic for a process entry point. For ordinary apps, use NodeRuntime.runMain.
A lifetime boundary. A Scope collects finalizers; closing it runs them (sequentially or in parallel) with the Exit that ended the work. The machinery underneath acquireRelease, Effect.scoped, and every Layer. Most of the time you never name a scope — Effect.scoped opens one, runs your effect, and closes it, discharging the Scope requirement. Manipulate scopes directly only when a resource must outlive the expression that created it.
Fragment · Type-checked
ts
import { Effect, Scope } from "effect"declare const acquireHrisConn: Effect.Effect<{ close: () => void }, never, Scope.Scope>// Open a scope by hand when the connection must outlive a single expression —// e.g. it's reused across loading employees, bands, and writing raises.const manual = Effect.gen(function*() { const scope = yield* Scope.make() // `Scope.use` supplies this scope, runs all work that may use the connection, // and closes the scope with the work's actual Exit. Do not return the scoped // connection: it is finalized before `Scope.use` completes. return yield* Scope.use( Effect.gen(function*() { const conn = yield* acquireHrisConn // ...use `conn` across loading employees, bands, and writing raises... return "review batch complete" }), scope )})
Tip: Prefer the high-level path: Effect.acquireRelease to register cleanup, Effect.scoped to bound it, and Layer when a resource should live for the whole app. Hand-managed Scope.make / close is for the rare case where a resource's lifetime doesn't align with any single effect.
Finalizer order and what finalizers see.
A scope runs its finalizers in reverse registration order (the default "sequential" strategy), which is what makes "open the pool, then open a cursor on it" tear down safely: the cursor closes while the pool is still alive. Every finalizer runs even if an earlier one fails. Scope.make("parallel") runs them concurrently instead.
Finalizers are exit-aware.Effect.addFinalizer((exit) => ...), Scope.addFinalizerExit(scope, (exit) => ...), and the release function of Effect.acquireRelease((resource, exit) => ...) all receive the Exit the scope was closed with, so cleanup can commit on success and roll back otherwise.
Scope in R is an unpaid debt. Until Effect.scoped, a Layer build, Scope.use, or Scope.provide discharges it, the resource has no owner — see the chooser in section 6 of Core Runtime & Execution.
Interleaved lifetimes. Everything sequenced under one Effect.scoped shares that scope, so all of its finalizers wait until the end. When two resources need different lifetimes, create scopes with Scope.make(), attach work with Scope.provide(scope) — it extends the work's resources into that scope without closing it — and end each with Scope.close(scope, exit) at the moment you choose (Scope.use is provide-then-close with the work's real Exit). Three facts to keep in mind: closing a scope runs finalizers and interrupts fibers forked into it, but does nothing to other fibers that still hold its resources; registering a finalizer on an already-closed scope runs it immediately; and closing a closed scope is a no-op.
Fragment · Type-checked
ts
import { Effect, Exit, Scope } from "effect"declare const openStagingTable: Effect.Effect<void, never, Scope.Scope>declare const openLedgerConnection: Effect.Effect<void, never, Scope.Scope>declare const loadIntoStaging: Effect.Effect<void, "StagingRejected">declare const postToLedger: Effect.Effect<void, "LedgerDown">// A manual scope still needs an owner: its close is registered in the enclosing scope,// so a failure or interruption half-way through cannot strand it.const ownedScope = Effect.acquireRelease(Scope.make(), (scope, exit) => Scope.close(scope, exit))const payrollImport = Effect.gen(function*() { const staging = yield* ownedScope const ledger = yield* ownedScope yield* openStagingTable.pipe(Scope.provide(staging)) // attaches to `staging` without closing it yield* openLedgerConnection.pipe(Scope.provide(ledger)) yield* loadIntoStaging yield* Scope.close(staging, Exit.void) // staging is released now... yield* postToLedger // ...while the ledger connection stays open}).pipe(Effect.scoped)
Reach for it when a resource must live longer than the expression that creates it, or when implementing a primitive that controls finalization order directly.
Decides when queued fiber work runs on the JavaScript thread, and when a long-running fiber should yield. The default is a MixedScheduler in "async" mode, installed as a Context.Reference so it can be swapped: it batches queued tasks by priority (FIFO within a priority) and dispatches each batch with setImmediate, or setTimeout(0) where setImmediate does not exist. It falls back to a Promise microtask when setting that timer throws — Cloudflare Workers forbid timers in global scope — so an effect run at module load can still yield. new MixedScheduler("sync") dispatches through microtasks. Effect's fibers are cooperative — they run in bursts and periodically yield to keep the event loop responsive. Two useful knobs: Scheduler.MaxOpsBeforeYield (operations before yielding, default 2048) and PreventSchedulerYield (disable yielding for controlled workloads).
Fragment · Type-checked
ts
import { Effect, Scheduler } from "effect"// A hot, latency-insensitive pass: value every equity grant in the ledger.declare const valueAllGrants: Effect.Effect<void>// Let it run longer between yields so the batch finishes faster.const tuned = valueAllGrants.pipe( Effect.provideService(Scheduler.MaxOpsBeforeYield, 8192))
Note: A custom Scheduler can provide deterministic task ordering in tests, but synchrony and flushing behavior belong to that scheduler implementation; merely replacing the service does not make every scheduler synchronous.
Reach for it when tuning throughput-vs-fairness for a heavy workload, or needing deterministic task ordering in a test. Otherwise the default scheduler is correct.
The service that owns "what time is it" and "sleep." Clock.currentTimeMillis and currentTimeNanos read the time as effects; Effect.sleep goes through the clock too. Installed as a Context.Reference — always available and always replaceable. Time is a dependency, not a global: read it through the clock so tests can install a virtual one and fast-forward to any point without real waiting.
Self-contained source · Type-checked
ts
import { Clock, Effect } from "effect"// Time as an effect — substitutable in tests, never a hidden global.const stampReviewOpened = Effect.gen(function*() { const now = yield* Clock.currentTimeMillis return { event: "merit-cycle-opened", at: now }})// `clockWith` hands you the live clock when you need it directly —// e.g. how long is left before the review-cycle deadline.const timeUntilDeadline = (deadline: number) => Clock.clockWith((clock) => Effect.sync(() => deadline - clock.currentTimeMillisUnsafe()) )
Warning: No Date.now() or new Date() inside effects. Read wall-clock time via Clock (or DateTime for calendar math). Anything else makes time-sensitive logic untestable and non-deterministic.
Wall-clock readings (currentTimeMillis / currentTimeNanos) may jump when the operating system corrects its clock; elapsed-time measurement uses the separate monotonic clock. A custom Clock.Clock implementation must therefore provide both monotonicTimeNanosUnsafe() and monotonicTimeNanos, with an arbitrary but consistently increasing origin.
Reach for it when any logic depends on current time, durations, or delays — so you can drive it with a virtual clock under test.
A one-shot, write-once coordination cell. A Deferred<A, E> starts empty, can be completed exactly once (with a success, failure, defect, or interruption), and lets any number of fibers await the result. Awaiting suspends the fiber without blocking a thread; every waiter sees the same outcome. A Promise completed by hand, but Effect-native: typed error channel, interruptible await, runtime-integrated.
Self-contained source · Type-checked
ts
import { Deferred, Effect } from "effect"const program = Effect.gen(function*() { // The approved merit budget, published once HRBP signs off. const approvedBudget = yield* Deferred.make<number>() // Producer completes the cell exactly once. yield* Effect.forkChild( Effect.gen(function*() { yield* Effect.sleep("100 millis") yield* Deferred.succeed(approvedBudget, 2_400_000) }) ) // Every per-manager planner awaits the same approved figure. const budget = yield* Deferred.await(approvedBudget) return budget})
Tip:Deferred.into runs an effect and completes a deferred with its full exit (success or cause), uninterruptibly. Useful for "load once, let every waiter get the result" caching and single-flight patterns.
Every completion function returns Effect<boolean>: true only for the call that actually completed the cell. That boolean is how competing producers learn who won; ignoring it hides lost writes. A Deferred is a handle, not an effect — read it with Deferred.await, or check it without suspending via Deferred.isDone(d) and Deferred.poll(d) (an effect yielding Option<Effect<A, E>>).
the outcome of running an effect once — memoized, every waiter sees the same result
Deferred.complete(d, effect); Deferred.into(effect, d) does the same uninterruptibly
the effect itself — not memoized, each waiter runs it again
Deferred.completeWith(d, effect); a sharp edge for side-effecting effects
Gates are per lifecycle generation, and must complete on every outcome. A Deferred cannot be reopened, so anything restartable — a scheduler generation, a reconnecting client, a readiness signal — mints a fresh one per generation; reusing a completed gate lets the next generation sail through on stale readiness. When a generation ends, fail its gate so anyone still waiting on it is woken rather than left hanging, and use Deferred.fail for "startup failed" so waiters fail fast rather than time out. A late completion from a retired producer is then detectably ignored (false) rather than overwriting state. When the same gate really must reopen, use a Latch.
Self-contained source · Type-checked
ts
import { Deferred, Effect, Ref, Schema } from "effect"class HrisSyncRetired extends Schema.TaggedError<HrisSyncRetired>()("HrisSyncRetired", { generation: Schema.Int}) {}interface SyncGeneration { readonly generation: number readonly ready: Deferred.Deferred<void, HrisSyncRetired>}// Start the next sync generation: fresh gate, and the retired gate fails its waiters.const rollOver = Effect.fn("rollOver")(function*(current: Ref.Ref<SyncGeneration>) { const ready = yield* Deferred.make<void, HrisSyncRetired>() const previous = yield* Ref.getAndUpdate(current, (g) => ({ generation: g.generation + 1, ready })) const released = yield* Deferred.fail(previous.ready, new HrisSyncRetired({ generation: previous.generation })) // `released` is false when the previous generation had already become ready or failed. return { released, ready }})
Official guide: Deferred (its intro calls a Deferred a subtype of Effect; it is not yieldable, and Deferred.poll returns an Effect<Option<Effect<A, E>>> — None while unresolved, Some wrapping the completed effect once it is).
Reach for it when one fiber must signal a single value or completion to others — bridging callbacks, gating on an approved result, or building single-flight/memoization.
A reusable open/closed gate. While a Latch is closed, await (and whenOpen) suspend; open releases current and future waiters; release frees only current waiters; close makes future waiters suspend again. Where Deferred is one-shot, a Latch resets — open it, close it, open it again.
Latch.isOpen(latch) (or the instance's .isOpen()) is a synchronous, non-mutating status check; use it for observation, never as a substitute for await when correctness depends on the gate remaining open.
Self-contained source · Type-checked
ts
import { Effect, Latch } from "effect"const program = Effect.gen(function*() { // Start closed: every manager's planner waits at the gate until kickoff. const cycleGate = yield* Latch.make(false) yield* Effect.forkChild( Effect.gen(function*() { yield* cycleGate.await // suspends until the cycle opens yield* Effect.log("planner unlocked — entering recommendations") }) ) yield* Effect.sleep("50 millis") yield* Latch.open(cycleGate) // open the merit cycle to everyone // `whenOpen` gates an arbitrary effect behind the latch. yield* Latch.whenOpen(cycleGate, Effect.log("accepting recommendations"))})
Official guide: Latch (a gate releases everyone at once; a Semaphore admits a bounded number at a time).
Reach for it when you need a gate that opens and closes repeatedly. For a one-time signal, use Deferred instead.
A reusable runtime built once from a Layer. Constructs services lazily on first use, caches them, and exposes plain runPromise / runSync / runFork methods so non-Effect code can execute effects with full dependency injection. Call dispose() to release everything the layer acquired. The bridge for embedding Effect inside a world that isn't Effect — Express handlers, React event callbacks, test harnesses, CLI commands. Pay the layer-construction cost once, then call runtime.runPromise(effect) repeatedly.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, ManagedRuntime } from "effect"// The compensation engine, exposed as a service.class CompService extends Context.Service<CompService, { readonly recommendRaise: (employeeId: string) => Effect.Effect<number>}>()("app/CompService") { static readonly layer = Layer.succeed(this)({ recommendRaise: (employeeId) => Effect.succeed(employeeId === "emp_142" ? 8_500 : 0) })}// Build services once; reuse the runtime across many web requests.const runtime = ManagedRuntime.make(CompService.layer)// Non-Effect code (e.g. an HTTP handler) can now run effects directly:async function handler(employeeId: string) { return await runtime.runPromise( Effect.flatMap(CompService, (comp) => comp.recommendRaise(employeeId)) )}// On shutdown, release the layer's resources (HRIS pool, ledger client, ...).async function shutdown() { await runtime.dispose()}
ManagedRuntime also implements Symbol.asyncDispose, so TypeScript's await using runtime = ManagedRuntime.make(layer) releases the runtime automatically at block exit. Use either that protocol or dispose()—never leave a long-lived runtime's layer scope open.
Note: Don't use ManagedRuntime when the whole app is Effect — use Layer.launch + NodeRuntime.runMain there. ManagedRuntime is for seams where Effect meets imperative or framework-driven code that calls in repeatedly.
A ManagedRuntime is a lifetime-bearing bridge, so every callback follows the same protocol.
Forward the host's cancellation. Every run method except runSync / runSyncExit takes RunOptions; pass the request's AbortSignal as { signal } and an aborted request interrupts the fiber, which in turn aborts the signal handed to your Promise adapters (section 8 of Core Runtime & Execution). Check signal.aborted yourself first: the runner consults the signal only after the fiber's first synchronous run.
Decide how outcomes cross the boundary.runPromise rejects with the squashed cause; use runPromiseExit when the host must tell a typed failure from a defect from a cancellation. Treat only an interruption-only Cause as ordinary cancellation: an interrupted run can also contain cleanup defects, which must not be hidden.
Stop admitting work before you dispose. Flip a draining flag, let in-flight callbacks finish or interrupt them, and only then call dispose(). After disposal every run dies with ManagedRuntime disposed. Disposal itself is idempotent — a second dispose() releases nothing twice, and a call made while a disposal is in progress waits for that disposal to finish — which keeps hot-reload and double shutdown hooks safe. Disposal runs uninterruptibly; interrupting a waiting call only stops the wait. runtime.disposeEffect is the same operation as an Effect, for shutdown that is itself composed in Effect.
The first run pays for the Layer. Services are built lazily on first use, so a startup failure surfaces on the first callback. A failed build is cached: later runs return the same failure without rebuilding, so retry transient failures inside the layer, or dispose the runtime and make a new one. Hosts that want to fail at boot warm the runtime with await runtime.context() (or one runPromise(Effect.void)).
Fragment · Type-checked
ts
import { Cause, Effect, Exit, Layer, ManagedRuntime } from "effect"declare const AppLayer: Layer.Layer<never>declare const handleRaiseRequest: (body: unknown) => Effect.Effect<{ readonly raise: number }, "BandViolation">const runtime = ManagedRuntime.make(AppLayer)let draining = falseexport const onRequest = async (body: unknown, signal: AbortSignal) => { if (draining || signal.aborted) return { status: 503 as const } const exit = await runtime.runPromiseExit(handleRaiseRequest(body), { signal }) if (Exit.isSuccess(exit)) return { status: 200 as const, body: exit.value } if (Cause.hasInterruptsOnly(exit.cause)) return { status: 499 as const } // cancellation without a cleanup fault return { status: Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause) ? (500 as const) : (422 as const) }}export const onShutdown = async () => { draining = true await runtime.dispose()}
Reach for it when embedding Effect into a non-Effect host — framework callbacks, library glue, incremental adoption — and a long-lived, dependency-injected runtime is needed to run effects on demand.
The low-level primitive powering streams and channels. A Pull<A, E, Done, R> is an Effect that, when evaluated, either: produces a value A, fails with an ordinary error E, or signals end-of-input via Cause.Done<Done> in the error channel. Repeatedly evaluating a Pull is how a Stream is consumed under the hood. Normal completion is encoded as a special failure (Cause.Done) so a single effect expresses "here's a chunk," "I errored," and "I'm finished" — carrying a leftover value at the end if needed. The module provides catchDone, filterDone, matchEffect to distinguish these cases.
Fragment · Type-checked
ts
import { Cause, Effect, Pull } from "effect"// Pulling the next page of an employee export out of the HRIS.declare const nextEmployeePage: Pull.Pull<ReadonlyArray<{ id: string }>, Error>// Distinguish "more rows", "real error", and "done" in one match.// Note: onFailure receives the full Cause, onDone receives the leftover.const step = Pull.matchEffect(nextEmployeePage, { onSuccess: (page) => Effect.succeed(`loaded ${page.length} employees`), onFailure: (cause) => Effect.succeed(`hris error: ${Cause.pretty(cause)}`), onDone: () => Effect.succeed("employee export complete")})
The user-facing entry point is Stream.toPull(stream): a scoped effect (run it under Effect.scoped) that returns a pull. Each evaluation yields the next non-empty array of elements, and completion arrives as a Cause.Done failure — which is how you hand a stream to an imperative while loop without collecting it. Official guide: Stream Operations.
Note: This is plumbing. Work with Stream, Channel, and Sink day to day; drop to Pull only when writing a custom stream source or low-level operator and need direct control over the produce/fail/done protocol.
Reach for it when implementing a custom Stream or Channel primitive and needing direct control over the element-by-element pull protocol, including the end-of-input signal. For everyday data flow, stay in Stream.
The effect package version string reported in OTLP resources, telemetry headers, and span scopes. Added in 4.0.2.
Self-contained source · Type-checked
ts
import * as Version from "effect/Version"// Read the version Effect reports in telemetry.const v: string = Version.getCurrentVersion() // installed package version// Override it — useful in a monorepo where the installed version// should differ from the one surfaced in traces and OTLP resources.Version.setCurrentVersion("custom-build")console.log(Version.getCurrentVersion()) // "custom-build"
Note:setCurrentVersion mutates only this copy of the module. Telemetry layers built before the call retain the version they read at construction time.
Reach for it when you need to read or pin the version that Effect reports in OTLP resources and span attributes.
Tip: Effects are descriptions; fibers run them; scopes decide how long resources live; exits and causes capture how things ended. Coordinate fibers with Deferred (one-time signal) and Latch (repeatable gate); supervise dynamic fibers with FiberHandle/Map/Set; read time through the Clock; bridge to the outside world with ManagedRuntime. Wrap foreign code with the constructor that matches its failure convention and forward the AbortSignal; give every fiber and resource a named owner; call runners only at owned edges. Everything else in this handbook builds on these pieces.
The R in Effect<A, E, R> is a typed set of required services. Context holds those services, Layer is the recipe for constructing them (with dependencies and lifecycles), and the runtime blocks execution until every requirement is satisfied.
Official examples: Effect's release-matched ai-docs service examples cover Context.Service, Context.Reference, Layer composition, and dynamically constructed Layers.
Official guides:Managing Services. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
A Layer graph builds dependencies first and each Layer once per memo map; when the owning Scope closes, everything it built is released in reverse order.
A type-safe, immutable map from service tags to implementations. Declare services with Context.Service to get the tag, the accessor, and a default layer attachment point; the type system tracks requirements in R.
Mental model. A Map<Tag, Impl> whose keys are tracked at the type level, so requirements accumulate in R until provided.
Contexts are implemented as immutable overlays: Context.add is constant-time and later bindings shadow earlier ones; Context.get also resolves a Context.Reference's default. After a bounded number of add overlays (8 by default) the context is rebased into one flat map; Context.makeUnsafe(map, { maxDepth }) tunes that bound for a context built from a raw Map — lower makes lookups cheaper, higher makes additions to a large base cheaper — and contexts derived with add, pick, omit, and merge keep it. Layers combine contexts with mergeAll, which uses the default, so set it on a final context rather than inside a layer. Compose through public add, merge, pick, and omit operations—the old mutation and unsafe-reference internals are not public APIs.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"// Define a tagged error for HRIS connectivity failures.class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { reason: Schema.String}) {}// The canonical v4 service: a class extending Context.Service.class Hris extends Context.Service<Hris, { readonly getEmployee: (id: string) => Effect.Effect< { id: string; name: string; level: number; baseSalary: bigint; departmentId: string }, HrisUnavailable > readonly listDepartmentEmployees: (departmentId: string) => Effect.Effect< ReadonlyArray<{ id: string; name: string; level: number }>, HrisUnavailable >}>()("hr/Hris") { // Hang the implementation on a static layer. static readonly layer = Layer.effect(Hris, Effect.gen(function*() { yield* Effect.log("connecting to HRIS") return Hris.of({ getEmployee: (id) => Effect.succeed({ id, name: "Alice Nguyen", level: 4, baseSalary: 145000n, departmentId: "eng" }), listDepartmentEmployees: (departmentId) => Effect.succeed([{ id: "e1", name: "Alice Nguyen", level: 4 }]) }) }))}// Consume it: `yield* Hris` reads it from context; R now includes Hris.const getEngineeringHeadcount = Effect.gen(function*() { const hris = yield* Hris const employees = yield* hris.listDepartmentEmployees("eng") return employees.length})
Use when defining any injectable capability.
Note: The string key ("hr/Hris") is the runtime identity: two classes that share a key resolve to the same context entry, so keep keys unique across the application and its libraries — a package/Name prefix is the usual convention.
yield* Service inside Effect.gen is the default. Every service class also carries two static accessors for single calls: Service.use(f) resolves the service and runs an effect-returning callback, and Service.useSync(f) does the same for a pure projection. All three forms add the service to R.
Fragment · Type-checked
ts
import { Context, Effect } from "effect"class CompBands extends Context.Service<CompBands, { readonly bandFor: (level: number) => Effect.Effect<{ readonly min: bigint; readonly max: bigint }> readonly currency: string}>()("hr/CompBands") {}// Effect<{ min; max }, never, CompBands>const levelFourBand = CompBands.use((bands) => bands.bandFor(4))// Effect<string, never, CompBands>const currency = CompBands.useSync((bands) => bands.currency)// Recover the implementation type for helper signatures and test doubles.type CompBandsShape = Context.Service.Shape<typeof CompBands>declare const auditBands: (bands: CompBandsShape) => Effect.Effect<void>
Use use for one-liners and adapters such as runtime.runPromise(CompBands.use(...)); inside a larger generator, yield* reads better and resolves the service once.
The service shape is the part of a capability that every caller, fake, and future implementation must agree on. Decide it before writing a Layer.
Name the service for a business capability and its methods with domain verbs — RaiseApprovals.submit tells a reviewer what may happen; Manager.execute or generic CRUD hides it.
Every method returns an Effect whose E lists the expected failures, and no method throws — a throw inside a method body becomes a defect, so an upstream Effect.catchTag never sees it. Fakes obey the same rule (Effect.fail(new HrisUnavailable(...)), not throw); otherwise tests exercise a different failure channel than production.
Public methods have R = never — configuration, clients, other services, and Scope are construction needs, so they belong to the Layer's inputs. A method typed Effect<A, E, PayrollClient> forces every caller and every test to provide PayrollClient, and an implementation that does not need it becomes a breaking change.
Do not leak the implementation through parameters or fields — no transaction handle, SQL client, logger, mutable state, or concrete class in the shape. If callers must pass one, the boundary is in the wrong place.
One service per capability, not per method — split when consumers use unrelated halves or implementations vary independently, not to make mocking easier.
Before adding a boundary, ask: which capability is this, which decisions hide behind it, would two honest implementations obey one contract, is substitution valuable (test, tenant, vendor), and does it point dependencies the right way? If most answers are "no", a plain function is enough.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"class PayrollRejected extends Schema.TaggedError<PayrollRejected>()("PayrollRejected", { employeeId: Schema.String}) {}class PayrollClient extends Context.Service<PayrollClient, { readonly post: (employeeId: string, amount: bigint) => Effect.Effect<void, PayrollRejected>}>()("hr/PayrollClient") {}class AuditLog extends Context.Service<AuditLog, { readonly record: (entry: string) => Effect.Effect<void>}>()("hr/AuditLog") {}// Leaky shape — every caller of `apply` would have to provide PayrollClient:// readonly apply: (...) => Effect.Effect<void, PayrollRejected, PayrollClient>class RaiseApprovals extends Context.Service<RaiseApprovals, { // Business input, business failure, R = never. readonly apply: (employeeId: string, amount: bigint) => Effect.Effect<void, PayrollRejected>}>()("hr/RaiseApprovals") { static readonly layer = Layer.effect(RaiseApprovals, Effect.gen(function*() { // Construction dependencies are captured once, here. const payroll = yield* PayrollClient const audit = yield* AuditLog return RaiseApprovals.of({ apply: Effect.fn("RaiseApprovals.apply")(function*(employeeId: string, amount: bigint) { yield* payroll.post(employeeId, amount) yield* audit.record(`raise applied for ${employeeId}`) }) }) }))}// The Layer's inputs list what construction needs; the method's type does not.const checked: Layer.Layer<RaiseApprovals, never, PayrollClient | AuditLog> = RaiseApprovals.layer
Review question: does any public method make its caller provide something only the implementation needs? If so, move that dependency into the Layer constructor.
Pick the cheapest seam that fits the implementation. Move to a Layer as soon as the implementation needs state, configuration, an effectful constructor, other services, or a lifetime.
Seam
Use it when
Effect on R
Effect.provideService(Service, value)
The implementation already exists as a value: a focused unit-test fake, a script, a per-request value set by middleware.
Removes exactly one identifier per call, so the type shows what is still unwired.
Effect.provide(context)
Several ready values travel together; build the bundle with Context.make(A, a).pipe(Context.add(B, b)).
Removes every key in the Context.
A test Layer (Layer.succeed, Layer.effect, Layer.mock)
The fake needs state, a constructor effect, or one shared instance for a whole test.
Removes the Layer's outputs and adds its inputs.
The live graph
The application edge: one composed Layer, provided once.
Closes R to never.
Self-contained source · Type-checked
ts
import { Context, Effect, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { reason: Schema.String}) {}class Directory extends Context.Service<Directory, { readonly managerOf: (employeeId: string) => Effect.Effect<string, HrisUnavailable>}>()("hr/Directory") {}class Notifier extends Context.Service<Notifier, { readonly notify: (employeeId: string, message: string) => Effect.Effect<void>}>()("hr/Notifier") {}const notifyManager = Effect.fn("notifyManager")(function*(employeeId: string) { const directory = yield* Directory const notifier = yield* Notifier const manager = yield* directory.managerOf(employeeId) yield* notifier.notify(manager, `raise pending for ${employeeId}`)})// One value at a time: R shrinks from Directory | Notifier to Notifier to never.const withDirectory = notifyManager("e42").pipe( Effect.provideService(Directory, Directory.of({ managerOf: () => Effect.succeed("m7") })))const closed = withDirectory.pipe( Effect.provideService(Notifier, Notifier.of({ notify: () => Effect.void })))// A failing fake still uses the typed channel.const hrisDown = Directory.of({ managerOf: () => Effect.fail(new HrisUnavailable({ reason: "maintenance window" }))})// Several ready values as one Context.const fakes = Context.make(Directory, hrisDown).pipe( Context.add(Notifier, Notifier.of({ notify: () => Effect.void })))const closedWithContext = Effect.provide(notifyManager("e42"), fakes)
Provide live implementations only at application or module edges, and fakes only at test edges. An Effect.provide(PayrollClient.layer) or Effect.provideService(PayrollClient, liveClient) buried inside a reusable function makes R look clean while hard-wiring production I/O: tests silently reach the network, callers cannot substitute a recorder or a retrying client, and each call is its own Layer build (see What is shared, and what is rebuilt). It is the Effect spelling of new HttpClient() inside a function body.
Effect.serviceOption(Service) returns Effect<Option<Shape>> and does not add the service to R. Use it for a capability the host may or may not install — an audit sink, a plugin, a telemetry hook — and handle both branches. Contrast it with a Context.Reference, which is always present because it has a default. The trade-off is that the compiler will not remind anyone to provide an optional service.
Self-contained source · Type-checked
ts
import { Context, Effect, Option } from "effect"class AuditSink extends Context.Service<AuditSink, { readonly write: (event: string) => Effect.Effect<void>}>()("hr/AuditSink") {}// Effect<void, never, never> — AuditSink is not a requirement.const recordApproval = Effect.gen(function*() { const sink = yield* Effect.serviceOption(AuditSink) if (Option.isSome(sink)) { yield* sink.value.write("raise-approved") }})
Context.Service<Self>()("key", { make }) infers the shape from the make effect and exposes it as a static, so the usual pair of Layers is one line each. Upstream code and the rest of this handbook use both styles; they produce the same kind of key.
Name the dependency-free Layer layerNoDeps and reserve layer for the variant with its unambiguous production dependencies provided. (The official guides call the first one layerWithoutDependencies; it is a naming convention, not an API.) Prefer the explicit shape parameter, as in Hris above, when the contract should be reviewed separately from any implementation.
Note: A few unstable library services — LanguageModel, EmbeddingModel, Chat, and Reactivity — have branded shapes that carry a [TypeId] field. Build custom implementations and fakes with the module's own constructors (for example LanguageModel.make) rather than an object literal, so the brand is present.
A recipe that builds one or more services (possibly from other services) with acquisition and release. Layers are memoized and composed into a single dependency graph.
Mental model. A constructor with a lifecycle. Layer.effect(Tag, build) builds a service from an effect; if build uses acquireRelease, the layer manages cleanup. Wire layers with:
Combinator
Use it to
Layer.effect / succeed / sync
Build a service from an effect / a ready value / a thunk.
Layer.provide(dep)
Satisfy a layer's dependencies — without re-exposing them to the rest of the app.
Layer.provideMerge(dep)
Same, but ALSO keep dep in the output (expose it upward).
Layer.merge / mergeAll
Combine independent layers side by side.
Layer.unwrap
Build a layer dynamically from an Effect/Config.
Layer.effectDiscard
Run a background/side-effecting layer with no service output.
Layer.launch
Turn a layer into a long-running program (your app entry point).
Layer.tap / tapError / tapCause
Observe a successful build (receives the built Context) or a failed one, without changing what the layer provides.
Layer.catch / catchTag / catchCause / orDie
Recover construction with a fallback layer, or turn a startup failure into a defect.
Layer.fresh
Build a private copy of a layer and its dependencies, outside the shared memo map.
Layer.build
Build a layer into a Context value for inspection or manual wiring. The result requires Scope, and the built services live only until that scope closes — use the Context inside the same Effect.scoped region.
Layer.withSpan(name, options?)
Trace a layer: the span starts with construction and ends when the layer's scope closes; onEnd receives the span and the scope's Exit. The usual span options apply in both call forms, including captureStackTrace (false, or a lazy stack string that points at your call site).
Read a layer type as Layer<Provides, ConstructionError, Requires>. A composed application layer should end with Requires = never.
Memoization is by Layer object identity within a build/MemoMap. Reuse one named layer value when two branches must share one pool or resource; reconstructing an equivalent layer expression creates a different identity. merge / mergeAll build independent branches concurrently and share any repeated dependency value. Layer.fresh(layer) deliberately opts out and builds a separate instance.
For tests, Layer.mock(Service, partial) lets you provide only the effectful methods a test uses; an omitted Effect/Stream/Channel method dies with UnimplementedError, while ordinary non-effect fields remain required. Layer construction failures can be handled before wiring with catchTag, catchCause, or orDie. The advanced makeMemoMap, forkMemoMap, and buildWithMemoMap APIs support dynamic runtimes: a child memo map can reuse parent entries while keeping its new allocations isolated.
Fragment · Type-checked with fixture
ts
import { Config, Effect, Layer } from "effect"// CompService depends on Hris and a config-driven PayrollClient.// Provide Hris beneath CompService; PayrollClient is wired separately.// The app only sees CompService + ReviewService in its R.const AppLayer = Layer.mergeAll( CompService.layer.pipe(Layer.provide(Hris.layer)), ReviewService.layer.pipe(Layer.provide(Hris.layer)))// Layer.unwrap: choose which HRIS layer to build based on config.const HrisLayer = Layer.unwrap( Effect.gen(function*() { const useSandbox = yield* Config.Boolean("HRIS_SANDBOX").pipe(Config.withDefault(false)) return useSandbox ? Hris.layerSandbox : Hris.layer }))// Run the compensation-planning server as the application entry point.const main = Layer.launch(CompPlanningServer.pipe(Layer.provide(AppLayer)))
Use when assembling a dependency graph or tying acquisition/release to a service's lifetime.
Official guides: Managing Layers (it names the dependency-free Layer layerWithoutDependencies; the actual property is layerNoDeps), Layer Memoization (its "providing locally" section describes only the sibling case; nested reuse and { local: true } are covered below).
A service that owns a connection, pool, subscription, or background fiber is built with Layer.effect(Service, Effect.gen(...)) whose constructor yields Effect.acquireRelease(open, close). acquireRelease requires Scope, and Layer.effect returns Layer<I, E, Exclude<R, Scope>>: the layer build owns that scope, so callers depend on the capability while the Layer owns the client's lifetime.
Layer.succeed packages a finished value, so it cannot express teardown. Anything that must be closed needs Layer.effect with a scoped constructor.
There is no Layer.scoped.Layer.effect already handles a Scope requirement.
Match the resource's lifetime to the Layer's owner. Building the client or repository stack inside a request handler closes correctly on every request and still turns a traffic spike into a connection spike. App-lifetime resources belong in the application graph; per-key resources belong in a LayerMap.
A memo map records each layer value it has built and hands the same result to every later request for that value. Entries are reference-counted: when the last scope using one closes, the entry is removed and the layer's finalizers run. "Is this pool shared?" therefore means "do both requests reach the same memo map, with the same layer value, while the first build is still alive?"
Every Effect.provide(layer) builds with a memo map forked from the fiber's current one — the map installed by an enclosing layer build — or with a new map when there is none. A fork reads its parent's entries and writes only to itself. The following counts were measured with an acquisition counter:
Situation
Builds of PoolLive
Why
One build reaches the same layer value through several branches (merge, provide, provideMerge, or Effect.provide([A, B]))
1
One memo map, one identity.
Two equivalent layer expressions (a layer-returning function called twice, an inline Layer.effect(...) repeated)
2
Different identities.
Two sibling Effect.provide(PoolLive) calls — sequential or concurrent, even under a shared outer provide of other layers
2
Each call writes to its own fork, siblings never see each other's entries, and a sequential sibling has already released its pool.
Effect.provide(PoolLive) nested inside a region whose enclosing build already built PoolLive: an outer Effect.provide, a ManagedRuntime, or a chained .pipe(Effect.provide(A), Effect.provide(B))
1
The inner build finds the live entry in the parent map — even when the outer graph kept the pool private with Layer.provide.
The same nested provide with { local: true }
2
A brand-new memo map: the whole provided graph, dependencies included, is rebuilt and then released when that effect ends.
Layer.fresh(layer) inside a build
one more
The wrapped layer is built with a new memo map, so it and its dependencies are private to that branch.
One composed layer value (the result of Layer.provide, provideMerge, merge, or mergeAll) referenced from several parents
1
Composed layers are memoized by identity like any other layer value, so the composition — including any Layer.fresh inside it — runs once per memo map. Write the composition once and reuse the value; calling a function that recomposes it each time creates new identities.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer } from "effect"class PayrollPool extends Context.Service<PayrollPool, { readonly id: number }>()("hr/PayrollPool") {}let opened = 0const PayrollPoolLive = Layer.effect( PayrollPool, Effect.acquireRelease( Effect.sync(() => ({ id: ++opened })), () => Effect.log("pool closed") ))const poolId = PayrollPool.useSync((pool) => pool.id)// Siblings: two builds, two pools — [1, 2].const siblings = Effect.all([ Effect.provide(poolId, PayrollPoolLive), Effect.provide(poolId, PayrollPoolLive)])// The same two provides under one enclosing build reuse its pool — [1, 1].const nested = siblings.pipe(Effect.provide(PayrollPoolLive))// Deliberate isolation: a private pool, released when this effect ends.const isolated = Effect.provide(poolId, PayrollPoolLive, { local: true })
Provide the application graph once, at the edge (or build one ManagedRuntime). "Build once, share, release at shutdown" comes from a single enclosing build, not from repeating Effect.provide(sameLayer) next to each use. A per-request or per-handler Effect.provide(DbLive) opens a pool per request.
Sharing is the resource-safety default. Without it every dependent service would open its own client and register its own finalizer: a connection storm under load and more to unwind on failure.
A build that is interrupted still completes its memo-map entry. Every requester already waiting on that layer value — including the one that triggered the build — receives the same interrupted Exit instead of hanging, and the shared entry is released once the owning scope closes.
{ local: true } and Layer.fresh are for required isolation — per-tenant, per-test, or per-transaction resources. Never reach for them to silence a type error; they duplicate pools, caches, and subscriptions.
Test build-frequency claims. Count acquisitions and assert 1 for a shared node and n only where isolation is intended. When you write "built once", name the scope and the memo map that make it true.
The Effect.provide API documentation says layers are "shared between provide calls" by default; that sentence describes the nested case in the table, not siblings. For dynamic runtimes, Layer.makeMemoMap, Layer.forkMemoMap, and Layer.buildWithMemoMap expose the same mechanism directly, and ManagedRuntime.make(layer, { memoMap }) lets several runtimes share one map.
Before composing, inventory each Layer: what it provides, what it requires, how often it should be built, and whether it is stateful, expensive, scoped, or deliberately fresh. Then apply one combinator at a time and restate the edge: required before, consumed by this step, still required, exposed.
Step
Provides
Still requires
RaiseApprovals.layer
RaiseApprovals
PayrollClient, AuditLog
.pipe(Layer.provide(PayrollClient.layer))
RaiseApprovals
AuditLog, plus whatever PayrollClient.layer requires
.pipe(Layer.provideMerge(AuditLog.layer))
RaiseApprovals, AuditLog
what PayrollClient.layer and AuditLog.layer require
Keep feature graphs honestly open and close them only at the composition root. A feature module exports a Layer that still requires the database or HTTP client; the root supplies them once.
Do not permute combinators until the compiler is quiet. That can hide an output another branch needs or build an unintended topology. Read the remaining Requires and wire exactly that.
Layer.merge does not feed siblings. A layer that must see another's output — including a ConfigProvider, logger, or tracer override — takes it through Layer.provide / provideMerge, not by sitting next to it.
Name feature Layers (const CompensationLive = ...) so inferred types and error messages stay readable, and so the value has one identity to share.
Layer construction is where startup failures surface: missing configuration, an unreachable database, a rejected credential. Layer.tap and Layer.tapError log those moments without changing the layer's type; Layer.catch, catchTag, and catchCause swap in a fallback layer; Layer.orDie declares the failure unrecoverable.
A tapError / tapCause observer must accept the layer's complete error type; a callback typed for one member of the union does not compile. Make a fallback an explicit, logged decision like the one above — never recover from a configuration error by silently switching to fake infrastructure (see Configuration & Secrets).
A test implementation honors the production contract, not just the happy value: same typed failures, same ordering and uniqueness guarantees the callers rely on. An always-succeeding fake cannot protect failure handling.
Keep fake state per test and observable through the fake itself (a recorded-calls Ref, a probe service) rather than module-level variables shared across tests.
Prove the substitution. A test Layer that is declared but never provided is a false green: assert on something only the fake can produce (a recorded call, a sentinel value), or make the live implementation unreachable in the fixture.
Remember that defaults hide missing wiring.ConfigProvider, Clock, and the other default services never appear in R, so forgetting to install a test override compiles and silently uses the real one.
A service that lazily builds, caches, and tears down layers keyed by a value. Creates resources on first use per key, releases them after an idle timeout.
Mental model. A Map<Key, Layer> with reference-counting and TTL: request key k, get its services; when k is idle long enough, its resources are finalized.
Fragment · Type-checked with fixture
ts
import { Effect, Layer, LayerMap } from "effect"// One compensation-data layer per department, idle-collected after 5 minutes.// CompData holds the department's comp bands and merit budget loaded from the HRIS.class DeptCompData extends LayerMap.Service<DeptCompData>()("hr/DeptCompData", { lookup: (departmentId: string) => CompBandLayer.pipe(Layer.provide(configForDepartment(departmentId))), idleTimeToLive: "5 minutes"}) {}// Process a merit-increase recommendation for an employee.// LayerMap.Service.get(key) returns a Layer — use Effect.provide to run// an effect with that department's comp-data context.const processMeritRaise = Effect.fn("processMeritRaise")( function*(employeeId: string, departmentId: string) { const employee = yield* Effect.provide( lookupEmployee(employeeId), DeptCompData.get(departmentId) ) return yield* Effect.provide( validateAgainstBand(employee), DeptCompData.get(departmentId) ) })
Use when you need dynamic, per-key dependency graphs — multi-tenant apps, per-shard connections, or any resource set not known up front.
Member
Behavior
get(key)
A Layer for that key's services; builds on first use and shares the entry while it is borrowed or within idleTimeToLive.
contextEffect(key)
The same entry as a scoped Context value, for manual wiring.
contextEffectOption(key)
Retains the entry only if it is already cached and returns Option.none() otherwise — no build is started, and an in-flight build is awaited. Use it for "flush this tenant's resources if they exist" paths.
invalidate(key)
Drops the entry; current borrowers keep their context until their scopes close.
preloadKeys / preload: true (layers form)
Builds those entries while the LayerMap layer itself is built, so a lookup failure also appears in the service layer's error type and fails startup; get, contextEffect, and invalidate keep the lookup error type as well. A key whose resolved idleTimeToLive is zero is skipped — including when no TTL was specified at all — so give preloaded keys an explicit, non-zero idleTimeToLive or they are built lazily on first use instead.
All keys of one LayerMap build against a single memo map forked from the one that built the LayerMap, so a dependency layer value that several keys share — and anything the enclosing application build already constructed — is built once, not per key.
The unkeyed counterpart to LayerMap: a refreshable, reference-counted cache for one layer-built service context. LayerRef.make(layer) builds lazily on first scoped borrow, shares the context, optionally keeps it alive while idle, and lets you invalidate or refresh it. Existing borrowers keep their old context until their scopes close; the next borrow receives the rebuilt one.
For application wiring, LayerRef.Service creates a named service with static .layer, .get, .contextEffect, .invalidate, and .refresh helpers. Use LayerRef for one database pool, credential set, or catalog that must be shared yet rotated; use LayerMap when the same pattern is keyed by tenant or shard, and Resource when callers only need a value rather than a whole service context.
The registry of built-in, fiber-scoped runtime settings: log annotations and levels, tracer flags/annotations/links, scheduler-yield controls, active loggers, and unhandled-error reporting. They are implemented as Context.References — values with defaults that flow down the fiber tree and can be locally overridden.
Mental model. Dynamically-scoped configuration. Unlike a service (which must be provided), a reference always has a default; an override applies only to the wrapped effect and its child fibers.
Fragment · Type-checked
ts
import { Context, Effect, References } from "effect"// Define an ambient review-cycle reference with a lazy default.// v4 form: Context.Reference is a plain function — pass the key and options directly.// Class-extension form keeps the ergonomics of yield* CurrentReviewCycle.class CurrentReviewCycle extends Context.Reference("hr/CurrentReviewCycle", { defaultValue: () => ({ cycleId: "default", year: new Date().getFullYear(), phase: "planning" as const })}) {}const annotateMeritLog = Effect.gen(function*() { const cycle = yield* CurrentReviewCycle // uses default unless overridden yield* Effect.log(`merit run for cycle=${cycle.cycleId} phase=${cycle.phase}`)})// Override for a specific review cycle when driving the annual merit run.const runAnnualMeritCycle = annotateMeritLog.pipe( Effect.provideService(CurrentReviewCycle, { cycleId: "2025-Q4", year: 2025, phase: "approval" }))// Concurrency is explicit: pass a number or "unbounded" to the operation.declare const employeeIds: ReadonlyArray<string>declare const fetchEmployee: (id: string) => Effect.Effect<{ readonly id: string }>const fetchPayrollBatch = Effect.forEach(employeeIds, fetchEmployee, { concurrency: 5 })// A real built-in reference: suppress logs below Warning for this subtree.const quietBatch = Effect.provideService( fetchPayrollBatch, References.MinimumLogLevel, "Warn")
Use when you want ambient, overridable context that is not a hard requirement — request correlation ids, feature toggles, log policy, tracing policy, or low-level scheduler tuning. Put operation-specific concurrency on Effect.forEach, Effect.all, stream combinators, and the other APIs that expose a concurrency option.
Five everyday capabilities are Context.References with live defaults. That is why reading the clock, printing, drawing random numbers, loading a Config, or opening a span leaves R as never — and why a missing test override is never a type error.
Override any reference for one effect with Effect.provideService(Ref, value), transform the current value with Effect.updateService(Ref, f), or hold an override until the surrounding scope closes with Effect.updateServiceScoped(Ref, f) (it requires Scope and restores the previous value on close). An override installed through a Layer follows the Layer rules above: it reaches the layers it is provided beneath and the effect the graph is provided to, not its Layer.merge siblings.
A scoped value that can refresh itself. Resource.auto(acquire, schedule) acquires a value and re-acquires it on a Schedule; Resource.get reads the latest successfully stored result. Resource.manual provides the same caching with explicit refreshes.
Mental model. A Ref whose contents are produced by an effect and rebuilt on a timer.
Fragment · Type-checked with fixture
ts
import { Effect, Schedule } from "effect"import { Resource } from "effect"// Fetch the full CompBand table from the HRIS and refresh it every hour.// Give the acquisition its own retry/recovery if automatic refresh must survive failures.const program = Effect.gen(function*() { const compBands = yield* Resource.auto( fetchCompBandsFromHris, // Effect<ReadonlyMap<number, CompBand>, HrisUnavailable> Schedule.spaced("1 hour") ) // Read the latest successfully stored comp bands. const bands = yield* Resource.get(compBands) // Validate an employee's proposed raise against the current band for their level. const employee = yield* hris.getEmployee("e42") const band = bands.get(employee.level) if (band && employee.baseSalary > band.max) { return yield* Effect.fail(new BandViolation({ employeeId: "e42", proposedSalary: employee.baseSalary })) }})
Use when a value must be kept current in the background — OAuth tokens, rotating signing keys, periodically-reloaded data snapshots.
Failure semantics: construction captures the initial acquisition as an Exit, so Resource.manual / auto can return a handle even when that acquisition fails; the first Resource.get then fails with the stored error. A later failed Resource.refresh fails that call but leaves the previously stored value intact. In Resource.auto, refresh is the effect repeated by the schedule, so an unhandled acquisition failure ends the automatic refresh fiber. Add retry/recovery to acquire when refreshing must continue through transient failures.
Config is an Effect, validated by Schema, read from a swappable provider. Three-part model: Config describes what you need and its shape. ConfigProvider decides where values come from. Redacted masks secret values; Redactable customizes rendering for consumers that honor Effect's redaction protocol.
Official guides:Configuration. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Config<T> extends Effect<T, ConfigError> — read config by yield*-ing inside Effect.gen; missing/invalid values become a typed ConfigError. Convenience constructors (Config.String, Config.Number, Config.Finite, Config.NonEmptyString, Config.Boolean, Config.Redacted, Config.LogLevel, and the rest of the built-in table) read a single key. Combinators (Config.all, Config.nested, Config.withDefault, Config.map, Config.mapEffect, Config.flatMap, Config.option) build structured config. Config.schema(schema, path) derives loading from the schema's encoded StringTree; opaque Any, Unknown, or JSON-shaped schemas must first be given a concrete string-tree boundary such as Schema.fromJsonString(Schema.Json).
Absence is structural, not merely falsy. A missing representation is decoded as undefined before withDefault or option decides what to do; a successfully decoded undefined or explicit empty structure is still a present value. In Config.all, any absent child makes the group absent unless another child fails validation or source loading. An outer default therefore replaces the whole group, even when some fields were supplied; an outer option returns None. Put defaults on individual fields to retain supplied values. Use a schema-level struct and explicit completeness checks when partially supplied groups must fail. For schema unions, Config.schema materializes each encoded StringTree member independently rather than guessing one mixed shape.
Self-contained source · Type-checked
ts
import { Config, Effect } from "effect"// CompService reads three keys: HRIS_URL, MERIT_CYCLE, and a redacted PAYROLL_API_KEY.// Config.all combines them; Config.nested("COMP") scopes them under a "COMP" prefix,// so the provider is expected to supply { COMP: { HRIS_URL, MERIT_CYCLE, PAYROLL_API_KEY } }.const CompServiceConfig = Config.all({ hrisUrl: Config.String("HRIS_URL"), meritCycle: Config.NonEmptyString("MERIT_CYCLE").pipe(Config.withDefault("2025-Q4")), payrollApiKey: Config.Redacted("PAYROLL_API_KEY") // arrives as Redacted<string>}).pipe(Config.nested("COMP"))const program = Effect.gen(function*() { const cfg = yield* CompServiceConfig // a Config IS an Effect — just yield* it yield* Effect.log(`Connecting to HRIS at ${cfg.hrisUrl}, cycle ${cfg.meritCycle}`) // cfg.payrollApiKey is Redacted<string> — safe to pass around, never logs plaintext})
Use for anything sourced from the environment — API endpoints, feature flags, credentials. Define once as a Config for validation and testability.
Every constructor takes an optional key name and is a shortcut for Config.schema(someSchema, name). Prefer these over hand-written parsers: each setting then carries its unit and its bounds in the config definition. The accept/reject column was probed directly against the schemas each constructor uses.
Constructor
Yields
Accepts / rejects
Config.String, Config.NonEmptyString
string
Any text. Blank values are already treated as missing by the built-in providers.
Config.Number
number
Also accepts NaN and Infinity — use Config.Finite for numeric settings.
Config.Finite
finite number
1.5, 1e3; rejects NaN, Infinity.
Config.Int
integer
8, -3; rejects 1.5. Add a range with Config.schema(Schema.Int.check(...), name).
Whatever Duration.fromInput parses from text: "5 seconds", "250 millis", "Infinity". Rejects "5s" and a bare "1500"; accepts negative spans, so bound it with a check.
Parse an untrusted duration once, at startup, into a Duration. A raw 5 does not say seconds, milliseconds, or attempts; Config.Duration("HRIS_TIMEOUT") (or Schema.DurationFromString inside a larger schema) makes malformed text a startup ConfigError, and the rest of the program passes a Duration around. Convert back to a number only where a foreign API demands one (Duration.toMillis). See Duration.
Environment variables are flat strings, so lists and maps usually arrive delimiter-separated. Config.Array and Config.Record accept either one separated string or a structural value, so the same definition works against environment variables and against a test object — and every element is validated by the schema, which a Config.String + split inside Config.map would bypass.
Both overloads take the path second (Config.Array(schema, "NAME", { separator: ";" })) or omit it and pass options directly; Config.Record adds keyValueSeparator (default "=") and, for string input, trim and keepEmptyValues (both default false). Without trim, whitespace around keys and values is kept, so " L4 = comp-eng " yields the key " L4 "; trim: true trims both before entries with an empty key are skipped. An entry with an empty value (L5=) is skipped unless keepEmptyValues: true keeps it as "", and an entry without the separator is always skipped. Numeric key schemas (Schema.Int, Schema.Number) select their entries as well. A bad element fails with its index in the path: PAYROLL_REGIONS=us,mars reports ["PAYROLL_REGIONS"][1].
Note: Environment-backed providers can also discover containers: ADMINS_0, ADMINS_1 form an array and TLS_CERT, TLS_KEY form a record for Config.schema(Schema.Struct(...), "TLS"). Discovery walks variable names split on _, so a container's own path segments must not contain _ — write Config.schema(schema, ["PAYROLL", "REGIONS"]) or Config.nested("PAYROLL"), not "PAYROLL_REGIONS". Leaf lookups join segments with _ and are unaffected. Only unpadded decimal indices count as array positions (ADMINS_1, not ADMINS_01).
Keep every rule inside the Config value so the error path (at ["COMP"]["WORKERS"]) and the parse(provider) boundary survive:
Field constraints — add a check to the schema: Config.schema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 64 })), "WORKERS").
Parsed-value rules — test the decoded value, never a string prefix: check url.protocol === "https:" on the URL, not startsWith("https") on the text.
Cross-field rules — decode a struct and check it as a whole (certificate and key together, a mode that requires an endpoint).
Effectful or fallible transformation — Config.mapEffect(f), where f fails with a ConfigError. Config.map is for total functions: a throw inside Config.map is a defect, not a ConfigError.
Self-contained source · Type-checked
ts
import { Config, Schema } from "effect"const HttpsUrl = Schema.URL.check( Schema.makeFilter((url) => url.protocol === "https:" ? undefined : "expected an https: URL"))const Tls = Schema.Struct({ CERT: Schema.optionalKey(Schema.String), KEY: Schema.optionalKey(Schema.String)}).check( Schema.makeFilter((tls) => (tls.CERT === undefined) === (tls.KEY === undefined) ? undefined : "CERT and KEY must be supplied together" ))const HrisUrl = Config.schema(HttpsUrl, "HRIS_URL")// TLS_CERT without TLS_KEY fails with: CERT and KEY must be supplied together at ["TLS"]const TlsConfig = Config.schema(Tls, "TLS").pipe(Config.withDefault({}))
A setting has four possible states, and only one of them may fall back:
State
Policy
Present and valid
Use it.
Absent
Apply the declared default or Option.none(), or fail if the key is required.
Present but malformed
Fail. Never fall back — a typo in production must not silently become the default.
Source unreadable (SourceError)
Fail, unless an explicit outage policy exists.
The three fallback tools differ in exactly this respect:
Tool
Falls back when
PORT=eighty
Config.withDefault(value), Config.option
The value is absent, including a Config.all group with an absent required child. Validation/source errors still fail.
ConfigError
ConfigProvider.orElse(primary, fallback)
The primary provider has no value at that path. A SourceError from the primary propagates, and a decoding error is never rescued.
ConfigError
Config.orElse(() => other)
Any pure ConfigError, including a malformed value or an unreadable source. A cause that mixes a ConfigError with a defect or interruption is not recovered — the mixed cause propagates.
the fallback
Self-contained source · Type-checked
ts
import { Config } from "effect"// PORT=eighty fails at startup; an unset or blank PORT becomes 3000.const port = Config.Port("PORT").pipe(Config.withDefault(3000))// Reserve Config.orElse for a deliberate alternative source, such as a renamed key.// It still masks a malformed PORT whenever HTTP_PORT is set, so remove it once the rename is done.const portWithLegacyKey = Config.Port("PORT").pipe( Config.orElse(() => Config.Port("HTTP_PORT")), Config.withDefault(3000))
Config.orElse(() => Config.succeed(3000)) would turn PORT=eighty into 3000 and hide a broken deployment. Blank is absent, but whitespace is not: PORT=" " is a present, malformed value. An explicit false or 0 is a present value too and survives withDefault.
Config.flatMap(self, f) reads one key to decide how to read the next: ConfigEnv.pipe(Config.flatMap((env) => env === "dev" ? DevHostConfig : ProdHostConfig)) picks a different, stricter sub-Config once the environment tag itself has been validated. Config.fail(sourceOrSchemaError) builds a Config<never> that always fails with the given SourceError/SchemaError — reach for it inside Config.orElse to re-raise a specific, informative error instead of silently falling through to an unrelated key.
The source a Config reads from. Default: process environment. It is a Context.Reference you can replace with an in-memory object for tests, a directory of files via ConfigProvider.fromDir, or chained providers via ConfigProvider.orElse.
Key constructors: ConfigProvider.fromUnknown(obj) — synchronous provider from any JSON-compatible object (ideal for tests). ConfigProvider.fromEnv() — reads process.env (runtime default). ConfigProvider.fromDir() — reads a directory tree (k8s secrets), requires Path and FileSystem in context. ConfigProvider.layer(provider) — inject a provider as a Layer. ConfigProvider.orElse(primary, fallback) — chain two providers.
All built-in providers treat a literal empty string as missing by default, so Config.option and Config.withDefault work for blank environment variables. Pass { preserveEmptyStrings: true } to fromEnv, fromEnvRecord, fromUnknown, fromDotEnv, or fromDir when blank is a meaningful value. fromEnvRecord(record) is the deterministic environment-style provider for restricted runtimes where reading global process.env is unavailable or undesirable. It captures discoverable keys and array lengths when constructed, while reads of those already-known keys observe later value changes; keys added afterward do not appear in parent discovery.
Fragment · Type-checked with fixture
ts
import { Config, ConfigProvider, Effect } from "effect"const CompServiceConfig = Config.all({ hrisUrl: Config.String("HRIS_URL"), meritCycle: Config.NonEmptyString("MERIT_CYCLE").pipe(Config.withDefault("2025-Q4")), payrollApiKey: Config.Redacted("PAYROLL_API_KEY")}).pipe(Config.nested("COMP"))// In tests, supply values explicitly as a nested object — no environment, no mocking.// ConfigProvider.fromUnknown is synchronous and takes any JSON-compatible object.const testProvider = ConfigProvider.fromUnknown({ COMP: { HRIS_URL: "http://hris.test", MERIT_CYCLE: "2025-Q4", PAYROLL_API_KEY: "test-tok-abc123" }})// Provide the layer so CompServiceConfig reads from testProvider instead of env.const tested = program.pipe(Effect.provide(ConfigProvider.layer(testProvider)))
Note: ConfigProvider.fromDotEnv() returns an Effect<ConfigProvider, PlatformError, FileSystem> — it is an effectful constructor, not a plain value — because it performs file I/O. Pass it to ConfigProvider.layer(effect) to use as a layer.
Use when config must come from somewhere other than env vars, or to inject a fixed in-memory provider in tests.
Also available: ConfigProvider.fromDotEnvContents(text, { expandVariables? }) parses .env text that is already in memory (no FileSystem; ${VAR} expansion is off unless requested, and expansion preserves replacement-pattern tokens such as $& inside expanded values rather than re-interpreting them). Without an { env } option, fromEnv() merges process.env with import.meta.env when the bundler defines it.
When expandVariables is enabled, expanded replacements are not rescanned: self and circular references terminate instead of overflowing the stack, escaped \$NAME stays literal, and a default is used when a reference expands to an empty value. Do not treat dotenv expansion as recursive shell evaluation.
Resolving one Config against an explicit provider
Every Config has .parse(provider), returning Effect<T, ConfigError>. It resolves that one definition against the given provider without installing the provider for anything else — the lightest way to unit-test a config definition or to read a bootstrap value from a specific source. ConfigProvider.layer is the other tool: it changes the provider for everything built or run beneath it.
Self-contained source · Type-checked
ts
import { Config, ConfigProvider, Effect } from "effect"const ServerConfig = Config.all({ host: Config.NonEmptyString("HOST"), port: Config.Port("PORT")})const provider = ConfigProvider.fromUnknown({ HOST: "localhost", PORT: 8080 })// { host: "localhost", port: 8080 }const server = Effect.runSync(ServerConfig.parse(provider))// Failure as data: the ConfigError names the path and the expectation.const invalid = Effect.runSync( Effect.result(ServerConfig.parse(ConfigProvider.fromUnknown({ HOST: "localhost", PORT: 0 }))))
Write precedence down, highest to lowest, next to the code that composes it — for example: explicit overrides, then environment, then a mounted secrets directory, then a local .env, then Config-level defaults. It is a deployment decision (some platforms want mounted secrets above the environment), so it should be reviewable in one place. Never implement it by merging JavaScript objects or by reading process.env in application code.
Fragment · Type-checked
ts
import { ConfigProvider } from "effect"declare const cliOverrides: Record<string, unknown>// Highest to lowest: CLI overrides > environment > checked-in defaults.const provider = ConfigProvider.fromUnknown(cliOverrides).pipe( ConfigProvider.orElse(ConfigProvider.fromEnv()), ConfigProvider.orElse(ConfigProvider.fromUnknown({ COMP: { PORT: 8080, WORKERS: 2 } })))// Replace the active provider for everything beneath this Layer.export const ConfigLive = ConfigProvider.layer(provider)// Or keep whatever is installed (the environment by default) and stack around it:export const DefaultsBehind = ConfigProvider.layerAdd( ConfigProvider.fromUnknown({ COMP: { PORT: 8080 } }))export const OverridesInFront = ConfigProvider.layerAdd( ConfigProvider.fromUnknown(cliOverrides), { asPrimary: true })
API
Effect
ConfigProvider.orElse(primary, fallback)
Consults fallback only for paths where primary has no value.
ConfigProvider.layer(provider)
Replaces the active provider. Accepts a provider or an Effect that produces one (evaluated once, when the layer is built).
ConfigProvider.layerAdd(provider)
Keeps the active provider as primary and adds provider as its fallback.
Puts provider in front; the previously active provider becomes the fallback.
ConfigProvider.nested(prefix)
Prefixes every lookup: ["HOST"] resolves APP_HOST for prefix "APP".
ConfigProvider.constantCase
Lets code ask for databaseHost while the environment holds DATABASE_HOST.
ConfigProvider.mapInput(f)
The general path transform behind the two above. Transforms compose in application order, and on an orElse chain they apply to every operand.
ConfigProvider.make(get)
A provider over a custom store. Return undefined for a missing path, build values with makeValue(string), and fail with SourceErroronly when the source cannot be read — a source failure must not look like absence.
Keep key mapping in one place (constantCase, nested, mapInput on the provider) so an operator can predict the external name of every setting.
A provider fallback and a Config default are different decisions. The first is a lower-priority source; the second is a semantic default in the typed contract. Do not fold them into one expression.
A provider Layer reaches only what is built or run beneath it.Layer.mergeAll(Hris.layer, ConfigLive) compiles, yet Hris.layer still reads the default environment provider, because ConfigProvider is a reference and never appears in R. Wire it as Hris.layer.pipe(Layer.provide(ConfigLive)), or provide ConfigLive last (outermost) at the program edge.
One Config value defines what a valid deployment looks like — required keys, defaults, numeric bounds, duration syntax, and which values are secrets. A second hand-written parser, or scattered process.env reads, creates two definitions of "valid" that drift.
Fragment · Type-checked
ts
import { ByteSize, Config, Context, Duration, Effect, Layer, Schema } from "effect"const Workers = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 64 }))const PollInterval = Schema.DurationFromString.check( Schema.makeFilter((interval) => Duration.between(interval, { minimum: Duration.seconds(1), maximum: Duration.minutes(10) }) ? undefined : "expected a duration between 1 second and 10 minutes" ))export const MeritCycleConfig = Config.all({ mode: Config.Literals(["live", "sandbox"], "MODE"), // explicit, required hrisUrl: Config.URL("HRIS_URL"), port: Config.Port("PORT").pipe(Config.withDefault(8080)), pollInterval: Config.schema(PollInterval, "POLL_INTERVAL"), workers: Config.schema(Workers, "WORKERS"), maxUpload: Config.ByteSize("MAX_UPLOAD").pipe(Config.withDefault(ByteSize.mebibytes(10))), auditEnabled: Config.Boolean("AUDIT_ENABLED").pipe(Config.withDefault(true)), payrollApiKey: Config.Redacted("PAYROLL_API_KEY"), // secret, required, no default slackWebhook: Config.option(Config.Redacted("SLACK_WEBHOOK")) // optional: both branches handled}).pipe(Config.nested("COMP"))// The typed result becomes a service, decoded once when the graph is built.export class AppConfig extends Context.Service<AppConfig, Config.Success<typeof MeritCycleConfig>>()( "hr/AppConfig") { static readonly layer = Layer.effect(AppConfig, MeritCycleConfig)}interface HrisPool { readonly close: Effect.Effect<void>}declare const openHrisPool: (url: URL, size: number) => Effect.Effect<HrisPool>export class HrisConnections extends Context.Service<HrisConnections, HrisPool>()("hr/HrisConnections") { // Depends on AppConfig, so no pool is opened until the whole contract has decoded. static readonly layer = Layer.effect(HrisConnections, Effect.gen(function*() { const config = yield* AppConfig return yield* Effect.acquireRelease( openHrisPool(config.hrisUrl, config.workers), (pool) => pool.close ) })).pipe(Layer.provide(AppConfig.layer))}
Inventory each setting: external name, type and constraints, required or not, who owns the default, secret or not, reloadable or not. Then:
Make it
When
Required
The promised capability cannot run safely without it.
Optional (Config.option)
Absence has a domain meaning and the code handles both branches.
Defaulted (Config.withDefault)
One safe value is valid in every environment, or a local/test profile owns it explicitly.
Some settings must never have a silent default: credentials, public bind addresses and exposure, production origins and CORS lists, destructive modes, durability switches, authentication, and telemetry destinations. Never ship placeholder credentials.
Select live versus fake infrastructure from an explicit mode (Config.Literals(["live", "sandbox"], "MODE")), not from whether a token happens to be present.
Decode every supplied field, even in a disabled branch. A disabled feature with a malformed endpoint is a deployment error, not something to skip.
Do not treat "", whitespace, "false", 0, and absence as equivalent. The built-in providers make only the empty string mean "missing"; everything else is a present value.
Install configuration before anything that depends on it
Order the startup: providers, then precedence and key mapping, then the typed application config and its cross-field checks, then configured clients, pools, and servers, then readiness.
A configuration failure must cause zero resource acquisitions, a non-zero exit, no readiness signal, and a diagnostic that names the path and the expected form. Layers merged side by side build concurrently, so a pool that does not depend on the typed config can open before a sibling's config error arrives (probed). Make resource Layers depend on the typed config service, as HrisConnections does above, and the ordering is structural.
Keep validation lazy. Decode inside the Layer that builds the app and validate options inside Effect-returning constructors; throwing at module load runs before any provider is installed and cannot be tested through a provider.
Do not re-read static config per request, and do not wrap individual consumers in their own provider Layers — that repeats decoding and blurs precedence. Decode once; hand each adapter the typed subset it owns rather than one giant object.
Sanitize custom diagnostics before logging ConfigError.Config parses without reportInput, so ordinary schema diagnostics omit rejected input. Custom schema messages and provider SourceError messages can still embed secrets. Test rendered errors with secret canaries rather than treating this default as a blanket log-safety guarantee.
Reloadable settings are a stateful service, not a second read. They need an owner (a watcher or poller with a scope), validate-then-atomically-publish, an explicit last-known-good or fail-closed choice, and tests. Resource and LayerRef are the building blocks.
Give each test its own in-memory provider through config.parse(provider) or ConfigProvider.layer(ConfigProvider.fromUnknown({...})). Never mutate process.env or inherit the developer's shell; use a temporary directory for fromDotEnv / fromDir adapters.
Case
Expected
Required key missing
ConfigError naming the path
Malformed value (PORT=eighty), with and without a default
ConfigError — never the default
Zero, negative, above the upper bound
ConfigError from the check
Fractional where an integer is required (WORKERS=1.5)
ConfigError
Explicit false and explicit 0 against a withDefault
Every pair of sources that operations can make collide
The documented precedence wins
Nested and constantCase key mapping, empty strings, URLs, literals
The documented external names resolve
At acceptance level, start the packaged build once per configuration case (complete, absent, unparseable, and conflicting values) and assert readiness, exit code, and that no secret canary appears in the output (see Redacted). Test-layer mechanics live in Testing & Dev Tooling and Testing an Effect Application.
Redacted<string> holds a secret value; stringifying, logging, or inspecting it prints <redacted>. The real value is only accessible via Redacted.value.
Self-contained source · Type-checked
ts
import { Redacted } from "effect"// Wrap the payroll API token the moment it enters the service.const payrollToken = Redacted.make("payroll-sk-9f3a...")console.log(`${payrollToken}`) // "<redacted>"console.log(JSON.stringify(payrollToken)) // "<redacted>"// Only unwrap at the call site that actually needs the raw bytes.const rawToken = Redacted.value(payrollToken) // "payroll-sk-9f3a..."
Use for any sensitive value — API keys, tokens, passwords. Pair with Config.Redacted so secrets are wrapped on entry, never stored as plain strings.
Warning:Redacted is accidental-disclosure hygiene, not secrecy. It keeps a value out of String(...), template literals, JSON.stringify, inspection, and loggers. It does not encrypt memory, files, or the environment, and it does not validate scope or expiry. The result of Redacted.value is an ordinary string that can be logged, serialized, or captured in an error cause like any other — and so can anything derived from it.
Call Redacted.value only as the argument of the narrow adapter that needs the raw value (the client constructor, the Authorization header builder). Do not store the result in a field, close over it, return it, interpolate it, or put it in an error payload, log annotation, or span attribute.
Never log the whole config at startup. Log the non-secret settings you chose to expose.
Test with a canary. Inject a unique marker as every secret, run startup and one failing request, and scan rendered ConfigErrors, pretty-printed Causes, captured logs, stdout/stderr, snapshots, and serialized payloads for it. String(redacted) === "<redacted>" alone proves nothing about the code around it. Also assert that the adapter did receive the raw value.
import { Equal, Equivalence, Redacted } from "effect"const token = Redacted.make("bootstrap-abc", { label: "BOOTSTRAP_TOKEN" })const rendered = String(token) // "<redacted:BOOTSTRAP_TOKEN>"// Compare secrets without unwrapping them at the call site.const sameToken = Redacted.makeEquivalence(Equivalence.strictEqual<string>())const matches = sameToken(token, Redacted.make("bootstrap-abc")) // trueconst alsoMatches = Equal.equals(token, Redacted.make("bootstrap-abc")) // true: Equal compares the hidden values// Shorten a credential's lifetime after the one call that needs it.const wiped = Redacted.wipeUnsafe(token) // true; Redacted.value(token) now throws
Redacted.wipeUnsafe removes the hidden value from the internal registry; a later Redacted.value throws Unable to get redacted value (with the label appended when there is one). Use it after exchanging a bootstrap token, and only when no other holder of the same Redacted instance still needs it.
A secret in a decoded payload — a login body, a webhook signing key, a stored credential — should never exist as a plain domain field.
Schema
Input
Encodes back to
Schema.RedactedFromValue(inner, options?)
The raw value; decodes it with inner, then wraps it.
The plaintext, unless { disallowEncode: true }.
Schema.Redacted(inner, options?)
A value that is already Redacted; decodes its contents with inner and rewraps the result.
A Redacted of the inner-encoded contents — but its JSON codec (Schema.toCodecJson) writes the plaintext, unless { disallowJsonEncode: true }.
The two option names really are different. Both schemas also accept label. Schema.Redacted keeps what inner transforms: Schema.Redacted(Schema.NumberFromString) decodes Redacted.make("42") to a Redacted<number> holding 42 and encodes it back to a Redacted<string>, preserving the label.
Self-contained source · Type-checked
ts
import { Config, Redacted, Schema } from "effect"const Login = Schema.Struct({ user: Schema.String, password: Schema.RedactedFromValue(Schema.NonEmptyString, { disallowEncode: true })})const login = Schema.decodeUnknownSync(Login)({ user: "ada", password: "correct-horse" })const safeToLog = JSON.stringify(login) // {"user":"ada","password":"<redacted>"}const raw = Redacted.value(login.password) // unwrap only at the call that verifies it// Schema.encodeSync(Login)(login) now fails with "Cannot encode Redacted" instead of// writing the password into a response, a queue message, or a database row.// Non-string secrets: decode, then seal.const BadgePin = Config.schema(Schema.RedactedFromValue(Schema.FiniteFromString), "BADGE_PIN")
Warning: Without disallowEncode / disallowJsonEncode, any response, persistence, or RPC codec derived from the same schema writes the secret back out in clear text. Set the option on every schema whose encoded side leaves the process, or keep secrets out of encodable models entirely.
Official guides: Redacted (its headings say unsafeWipe and getEquivalence; the actual names are Redacted.wipeUnsafe and Redacted.makeEquivalence), Effect Data Types (Schema; see its Redacted section, which does not mention that RedactedFromValue spells the option disallowEncode).
The protocol behind Redacted. Implement Redactable on your own types to customize their representation for consumers that invoke Effect's redaction protocol. The implementing method receives the current fiber's Context and returns a replacement value. This symbol alone is not a native JSON.stringify, String, or console-inspection hook. Redacted is the built-in implementer and also supplies safe serialization/inspection hooks.
The symbol to implement is Redactable.symbolRedactable (exported as a named constant, not as Redactable.symbol). The method receives a Context.Context<never>.
Self-contained source · Type-checked
ts
import { Context, Redactable, Redacted } from "effect"// Keep the stored token redacted, including during native JSON serialization.// Use Redactable.symbolRedactable (not Redactable.symbol) as the method key.class PayrollCredential { readonly serviceId: string private readonly token: Redacted.Redacted<string> constructor(serviceId: string, token: string) { this.serviceId = serviceId this.token = Redacted.make(token) } [Redactable.symbolRedactable](_ctx: Context.Context<never>) { // Safe representation: keep the service identifier, mask the secret. return { serviceId: this.serviceId, token: this.token } }}// Apply the protocol explicitly for a consumer that does not invoke it.const cred = new PayrollCredential("payroll-svc", "sk-live-abc...")const safeRepresentation = Redactable.redact(cred)
Use when domain types need a custom redacted representation. TypeScript private does not hide a property at runtime; storing a raw string there would expose it through native JSON serialization, regardless of the redaction symbol. Keep secret fields Redacted, and test every serializer/logger you actually use.
Tip: The combo to internalize: read secrets with Config.Redacted("PAYROLL_API_KEY") → they arrive as Redacted<string> → they stay sealed through your whole program → you only Redacted.value them at the exact moment you hand them to PayrollClient. The key never touches a log line by accident.
Effect treats failure as a typed value, not an exception. Option models absence, Result models success-or-failure, Filter models keep-or-reject, and Data builds structured comparable errors. Together they turn the error channel into ordinary control flow.
Option<A>, Result<A, E>, and Effect<A, E, R>'s E channel are the same idea at increasing power levels. Learn to move between them fluently.
Official examples: Effect's release-matched ai-docs error-handling examples cover tagged errors, catchTag/catchTags, and reason-based errors.
Official guides:Expected Errors, Two Types of Errors. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
A failed Exit carries a Cause with one or more reasons. Only Fail(E) is in the typed error channel; defects and interruptions travel in the Cause, and Effect.retry does not retry a Cause that contains a defect.
Decide what each unpleasant outcome is before writing a class for it. The channel it lands in determines who can see it, who may recover from it, and what retry and alerting code will do with it.
Outcome
Belongs in
Ask
Example
A correct negative answer that every caller treats as ordinary output
the success value A (a tagged Data/Schema value, an Option, or a Result)
"Would every caller branch on this identically as part of normal operation?"
an eligibility check answers Ineligible { reason }; a band lookup answers Option.none()
A condition a valid caller can act on: recover, retry, translate, or compensate
a typed failure in E
"Does some caller need its own policy for this?"
EmployeeNotFound, BandViolation, HrisUnavailable
A broken invariant or a bug
a defect (Effect.die, Effect.orDie, a throw inside Effect.sync)
"Could any caller do something sensible with it?" — no
a stored salary is negative although the schema forbids it
The caller went away
interruption
never modeled by hand
timeout, race loser, shutdown
Not everything unpleasant is a failure. If a service's job is to decide eligibility, "not eligible" is the product's answer, so the workflow succeeds with that classification and E stays reserved for outcomes callers must handle differently (invalid input, storage failure). Putting a correct negative answer in E makes retry schedules and alerts treat a right answer as a fault. Classifying at the layer that owns the question is also what legitimately produces E = never further up.
Fill in one row per failure before writing error classes. The columns are the decisions the classes must support:
Model caller decisions, not the library's exception classes. One variant per distinct policy; fields carry the facts the policy needs (retryable, employeeId, bandMax), never a message to parse.
Keep missing, conflict, unavailable, timeout, corrupt, forbidden, and unknown-infrastructure distinct whenever their policies differ, because collapsing them forces every caller to guess.
Only a query that succeeded and returned nothing is "not found". Timeouts, permission errors, pool exhaustion, malformed rows, and unknown driver errors must never become EmployeeNotFound or a 404, and a constraint violation is a specific conflict only after checking which constraint fired.
Translate where knowledge is added: foreign throwable → one stable adapter error (wrap the unknown once, at the adapter) → domain meaning → sanitized public representation. A layer that adds no knowledge passes the error through unrenamed. Cancellable adapters shows the adapter end of that chain, including dying on rejections the contract does not allow.
Interruption is cancellation. It is never a domain error, never a retry trigger, and not a fault to log by default.
Public error values are an output surface. A Schema.TaggedError declared on an HTTP endpoint or RPC encodes every field, so cause: Schema.Defect() publishes the wrapped error's name and message (stacks are omitted unless includeStack: true). Keep diagnostic causes on internal errors; give public errors stable tags plus safe identifiers, and never serialize a Cause, SQL text, a credential, or a Redacted.
The failure deep dive follows one operation through these decisions, including retry, timeout, and fallback.
The catch* family handles failures while keeping recovery visible in the effect's type.
Combinator
What it does
Effect.catch
Recover from any expected error E.
Effect.catchTag / catchTags
Recover from one (or several) tagged error variants by _tag — the workhorse. catchTag also accepts a non-empty array of tags.
Effect.catchIf / Effect.catchFilter
Recover when a predicate or refinement over E holds, or when a Filter matches (and narrows).
Effect.catchReason / catchReasons / unwrapReason
Recover at the level of a nested tagged reason field; see Core Runtime: error handling. An unmatched reason with no fallback re-fails with the original Cause.
Effect.catchCause / catchDefect
Reach below typed errors to the full Cause, or specifically to unexpected defects.
Effect.mapError / mapBoth / flip
Rewrite E without recovering, rewrite both channels, or swap A and E.
Effect.filterOrFail / filterOrElse
Turn an unacceptable success into a typed failure, or into another Effect.
Effect.match / matchEffect
Fold typed failure and success into one value; E becomes never (pure handlers) or the handlers' errors.
Effect.matchCause / matchCauseEffect
The same fold, but onFailure receives the whole Cause, including defects and interruption.
Effect.result / Effect.option / Effect.exit
Reify the outcome into a Result, an Option (the error value is discarded), or an Exit (the full Cause).
Effect.validate / Effect.partition
Run every element and accumulate all failures instead of stopping at the first.
Observe failures (log them) without handling them; the original failure is re-raised when the observer succeeds.
Effect.orElseSucceed / Effect.firstSuccessOf
Replace every typed failure with a plain value computed from the error, or try alternatives in order.
Effect.ignore / Effect.ignoreCause
Discard the success value and typed failures (ignore), or additionally defects and interruption (ignoreCause).
Effect.sandbox
Move the whole Cause<E> into the error channel so ordinary catch sees every reason.
Effect.orDie
Convert the typed failure into a defect and remove it from E.
Effect.fail / Effect.failSync / Effect.die
Create a typed failure (eagerly, or lazily so the error is built only on the failing path) or a defect.
Name each handler's intent. Every catch* should be exactly one of four things: recover (supply a truthful value for the handled condition, not merely a way to empty E), translate (add meaning at an abstraction boundary with mapError), compensate (undo prior work, then re-fail), or observe (tap*, failure unchanged). A handler that does none of these is hiding a failure.
Define caught errors as schema-backed tagged classes — typed constructor, _tag for matching, and free serialization:
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { employeeId: Schema.String}) {}class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { employeeId: Schema.String, proposedSalary: Schema.Finite, bandMax: Schema.Finite}) {}const lookupEmployee = Effect.fn("lookupEmployee")(function*(id: string) { if (id === "") return yield* new EmployeeNotFound({ employeeId: id }) if (id === "over-band") { return yield* new BandViolation({ employeeId: id, proposedSalary: 160_000, bandMax: 150_000 }) } return { id, name: "Priya Sharma", level: "L4", baseSalary: 120_000 }})const safeComp = lookupEmployee("").pipe( // Handle each tagged error by name; TypeScript narrows `e` per tag. Effect.catchTags({ EmployeeNotFound: (e) => Effect.succeed({ id: e.employeeId, name: "unknown", level: "L1", baseSalary: 0 }), BandViolation: (e) => Effect.logWarning(`salary ${e.proposedSalary} exceeds band max ${e.bandMax}`).pipe( Effect.as({ id: e.employeeId, name: "?", level: "L1", baseSalary: e.bandMax }) ) }))
import { Effect, Filter, Schema } from "effect"class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { employeeId: Schema.String}) {}class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { employeeId: Schema.String}) {}class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { status: Schema.Int}) {}declare const proposeRaise: Effect.Effect<string, EmployeeNotFound | BandViolation | HrisUnavailable>// One handler for several tags: E shrinks to HrisUnavailable.const skipped = proposeRaise.pipe( Effect.catchTag(["EmployeeNotFound", "BandViolation"], (error) => Effect.succeed(`skipped ${error.employeeId}: ${error._tag}`) ))// A Filter selects, and narrows, the failure to recover.const cached = proposeRaise.pipe( Effect.catchFilter(Filter.tagged("HrisUnavailable"), (error) => Effect.succeed(`served from cache after HTTP ${error.status}`) ))// A predicate over E: for a field test, or for errors that are not tagged classes.const restarting = proposeRaise.pipe( Effect.catchIf( (error) => error._tag === "HrisUnavailable" && error.status === 503, () => Effect.succeed("HRIS is restarting; try again shortly") ))
catchTag, catchIf, catchFilter, and catchReason take an optional trailing orElse handler for the failures that did not match, which empties E in one call. Prefer the narrowest selector that expresses the policy, because the remaining union in E is the record of what has not been decided yet. Compiling proves little here, since a broad Effect.catch compiles as well; to show that exactly the intended tag was removed, pin the post-recovery type with an annotation (const skipped: Effect.Effect<string, HrisUnavailable> = ...) next to the behavior test.
import { Effect, FileSystem, Schema } from "effect"// An internal error: the diagnostic cause never leaves the process.class CompBandsUnavailable extends Schema.TaggedError<CompBandsUnavailable>()("CompBandsUnavailable", { path: Schema.String, cause: Schema.Defect()}) {}class NoManagerOnRecord extends Schema.TaggedError<NoManagerOnRecord>()("NoManagerOnRecord", { employeeId: Schema.String}) {}// mapError: translate a platform failure into the error this module owns. Nothing is recovered.const loadBands = Effect.fn("loadBands")(function*(path: string) { const fs = yield* FileSystem.FileSystem return yield* fs.readFileString(path).pipe( Effect.mapError((cause) => new CompBandsUnavailable({ path, cause })) )})declare const findManagerId: (employeeId: string) => Effect.Effect<string | null>// filterOrFail: an unacceptable success becomes a typed failure; a refinement narrows A.const requireManager = (employeeId: string) => findManagerId(employeeId).pipe( Effect.filterOrFail( (managerId): managerId is string => managerId !== null, () => new NoManagerOnRecord({ employeeId }) ) ) // Effect<string, NoManagerOnRecord>
Effect.mapError(f) rewrites only E; use it at the layer that owns a dependency so driver and SDK errors do not leak upward. Effect.mapBoth({ onFailure, onSuccess }) rewrites both channels in one pass.
Effect.filterOrFail(predicate, orFailWith?) replaces flatMap + if + Effect.fail. Without orFailWith it fails with Cause.NoSuchElementError. Effect.filterOrElse runs a fallback Effect instead of producing an error.
Effect.flip swaps A and E. Its main use is a test that wants the typed error as a value (const error = yield* Effect.flip(effect)); in production code mapError or a catch states the intent better.
Map before you orDie. When a boundary deliberately promotes a failure to a defect, Effect.mapError first so the defect carries a meaningful error rather than a raw driver object.
Selective recovery keeps a workflow alive and leaves the rest of E for the next owner. Folding is the terminal move for an edge that must produce exactly one ordinary shape: an HTTP response, a CLI exit summary, a worker acknowledgement, a test observation.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { employeeId: Schema.String}) {}class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { bandMax: Schema.Finite}) {}declare const proposeRaise: (employeeId: string) => Effect.Effect<number, EmployeeNotFound | BandViolation>// Pure handlers. E is `never`: this boundary has accounted for every expected failure.const response = proposeRaise("e-42").pipe( Effect.match({ onFailure: (error) => error._tag === "EmployeeNotFound" ? { status: 404 as const, body: { employeeId: error.employeeId } } : { status: 422 as const, body: { bandMax: error.bandMax } }, onSuccess: (newSalary) => ({ status: 200 as const, body: { newSalary } }) }))// Effectful handlers may log, record a metric, or fail with a new error.const audited = proposeRaise("e-42").pipe( Effect.matchEffect({ onFailure: (error) => Effect.logWarning("raise rejected", { tag: error._tag }).pipe(Effect.as(false)), onSuccess: (newSalary) => Effect.logInfo("raise approved", { newSalary }).pipe(Effect.as(true)) }))
Fold only at a terminal boundary. A lower layer that folds steals policy from its callers.
match and matchEffect see typed failures only; a defect or interruption still fails the fiber. matchCause and matchCauseEffect hand onFailure the whole Cause, so they are process- or request-edge tools with the same caution as catchCause.
Effect.all and Effect.forEach stop at the first typed failure, which is wrong for form or batch validation where the caller needs every problem at once.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { employeeId: Schema.String}) {}declare const checkRaise: (employeeId: string) => Effect.Effect<number, BandViolation>const employeeIds = ["e-1", "e-2", "e-3"]// Runs every check. Succeeds with Array<number>, or fails with NonEmptyArray<BandViolation>.const allOrEveryViolation = Effect.validate(employeeIds, checkRaise, { concurrency: 4 })// Runs every check and never fails: [approvedAmounts, violations].const split = Effect.partition(employeeIds, checkRaise, { concurrency: 4 })// One Result per member, in the shape of the input.const perMember = Effect.all(employeeIds.map(checkRaise), { mode: "result" })
Need
Use
Outcome
Stop the batch at the first problem
Effect.all / Effect.forEach (default)
fails with the first E; when sequential, later elements never start
Array<B>, or fails with NonEmptyArray<E> (successes are dropped)
Act on both sides
Effect.partition(items, f, { concurrency? })
never fails: [passes: Array<B>, fails: Array<E>]
Per-member outcome in the input's shape
Effect.all(effects, { mode: "result" })
a Result per member
A defect in any element still fails the whole call. Accumulate as data rather than as several Fail reasons in one Cause, because typed handlers inspect only the first Fail reason (see below).
import { Effect } from "effect"declare const fromHris: Effect.Effect<number, "HrisUnavailable">declare const fromReplica: Effect.Effect<number, "ReplicaStale">declare const fromSnapshot: Effect.Effect<number, "NoSnapshot">// Sequential; the first success wins. If all fail, the error is the last one: "NoSnapshot".const bandMidpoint = Effect.firstSuccessOf([fromHris, fromReplica, fromSnapshot])
Effect.orElseSucceed(() => value) replaces every typed failure. The function receives the error ((error) => ...), matching Stream.orElseSucceed, so the fallback can depend on it; a zero-argument function still works. If only "not found" should default, narrow with catchTag first and keep the rest typed.
Effect.firstSuccessOf(effects) tries different effects in order; an empty iterable is a defect. When the same effect should run under different provided services, use ExecutionPlan instead.
Effect.option discards the error value, so use it only when every typed failure of that effect genuinely means "absent"; otherwise use Effect.result. Both leave defects and interruption as fiber failures.
Effect.ignore discards typed failures only — a defect or interruption still fails the fiber. Effect.ignoreCause also discards defects and interruption and can therefore hide bugs; reserve it for best-effort cleanup. Both accept { log: true | severity | "Unhandled", message } to log the Cause while ignoring it. log: "Unhandled" reads References.UnhandledLogLevel when the failure happens and logs nothing when that reference is undefined, so the application decides centrally how loudly swallowed failures are reported; the same option exists on the Stream and Channel variants.
A Cause is a flat list of reasons and may hold a typed failure and a defect or interruption at once: a failing operation whose finalizer dies, a concurrent sibling whose cleanup dies while being interrupted, or a race in which every contender fails.
A defect wins over a typed failure. When the runtime combines a typed failure with a defect — a finalizer that dies after the operation failed, or a sibling that dies — the typed failure is recorded as a defect too, so the cause reads [Die(error), Die(defect)]. And when a cause that still holds a Fail beside a Die reaches a typed recovery operator — catch, catchTag(s), catchIf, catchFilter, catchReason(s), orElseSucceed, firstSuccessOf, match, matchEffect, result, option, ignore, orDie, or retry — the operator does not recover: it converts every typed error to a defect, keeps the reason order and any interruptions, and propagates the cause. A crashing finalizer or dying sibling therefore cannot be swallowed by catchTag. Only catchCause, catchDefect, Effect.exit, and Effect.sandbox see such a cause as recoverable.
An interruption beside a typed failure does not block recovery. With reasons [Fail(e), Interrupt], the typed operators handle e and the handler's result becomes the whole outcome — the interruption is dropped, and retry retries. Typed recovery inspects only the firstFail reason, so catchTag("B") does not fire for [Fail(A), Fail(B)], and orDie keeps only Die(A). mapError is different from recovery: it maps every typed error in place and preserves defects, interruptions, and reason order. tapError and tapCause re-raise the original Cause, so they lose nothing.
Self-contained source · Type-checked
ts
import { Cause, Effect, Schema } from "effect"class ExportFailed extends Schema.TaggedError<ExportFailed>()("ExportFailed", { batchId: Schema.String}) {}// A typed failure whose finalizer then dies: reasons [Die(ExportFailed), Die(Error)].const exportBatch = Effect.fail(new ExportFailed({ batchId: "b-7" })).pipe( Effect.ensuring(Effect.die(new Error("ledger handle already closed"))))// Does not recover: the defect takes precedence, so the handler never runs.const stillDies = exportBatch.pipe( Effect.catchTag("ExportFailed", () => Effect.succeed("skipped")))// Recover deliberately only through the full Cause, and only for what you own.const careful = exportBatch.pipe( Effect.catchCause((cause) => Cause.hasDies(cause) || Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.succeed("skipped") ))
Migration: In earlier 4.0 releases a typed handler on a [Fail, Die] cause succeeded and dropped the defect. Code that relied on catchTag to absorb a failure whose cleanup also crashed now sees the crash; handle it with catchDefect or a guarded catchCause where that is genuinely intended.
Before choosing a catch operator, write down which boundary owns each variant: validation failures belong to the API edge, transient transport failures to the retry boundary, impossible invariants to defects rather than E. When one boundary must classify the whole union — a status code, a retry decision, a user message — finish the matcher with Match.exhaustive or Match.tagsExhaustive, never a switch with default, so that adding a variant fails compilation exactly where policy must be updated. A default branch silently assigns tomorrow's error to today's fallback.
Reserve Match.orElse for a deliberate fallback, and say in a comment why new variants may land there.
Match.fn((...args) => selected) builds a classifier that takes extra arguments (a locale, a request id): Match.tag handlers receive the narrowed value followed by the original arguments. Finish it with Match.exhaustive; Match.tagsExhaustive is typed for matchers without extra arguments.
A Schema.TaggedUnion carries its own exhaustive .match(value, cases); .matchOrElse(value, cases, orElse) is the partial form with a typed fallback (see Schema unions). Data.taggedEnum provides $match (below).
Completeness is mechanical. The compiler proves every tag has a row; it cannot prove a row is right. That needs domain review and a test per policy.
Option.some(a) or Option.none(). The typed replacement for null/undefined — absence is in the type, not an implicit convention.
Mental model. A list with zero or one element. map, flatMap, filter are no-ops on none, enabling chainable transforms without null checks.
Self-contained source · Type-checked
ts
import { Option } from "effect"// An employee record may or may not have a manager (top-level employees don't).interface Employee { id: string name: string managerId: string | null | undefined}const employee: Employee = { id: "e-42", name: "Priya Sharma", managerId: null }// Turn a nullable field into an Option, then transform safely.const managerDisplay = Option.fromNullishOr(employee.managerId).pipe( Option.map((mid) => `reports to ${mid}`), Option.getOrElse(() => "no direct manager (top-level)"))// managerDisplay: "no direct manager (top-level)"// Pattern-match both branches exhaustively.const describeManager = (opt: Option.Option<string>) => Option.match(opt, { onNone: () => "IC or department head — no manager on record", onSome: (mid) => `manager employee id: ${mid}` })
Use when a value is legitimately optional and the compiler must enforce handling of absence — optional config lookups, "find first" results, optional fields.
import { Option } from "effect"interface CompBand { readonly level: string readonly max: number}declare const findLevel: (employeeId: string) => Option.Option<string>declare const findBand: (level: string) => Option.Option<CompBand>declare const currentSalary: Option.Option<number>// flatMap: a dependent lookup that is itself optional, without nesting Options.const band = findLevel("e-42").pipe(Option.flatMap(findBand))// filter: keep the value only when the predicate holds.const roomyBand = band.pipe(Option.filter((b) => b.max > 120_000))// all: independent Options in a struct or tuple; any None collapses the whole result.const inputs = Option.all({ band, salary: currentSalary })// zipWith: exactly two values.const headroom = Option.zipWith(band, currentSalary, (b, salary) => b.max - salary)// gen: imperative style that stops at the first None.const headroomPercent = Option.gen(function*() { const b = yield* band const salary = yield* currentSalary return ((b.max - salary) / salary) * 100})
Option.gen evaluates eagerly, so keep its body pure; reach for Effect.gen plus Effect.fromOption when a step has side effects.
Option.partitionMap(self, f) applies a Result-returning function and splits the outcome: [passes: Option<C>, fails: Option<B>], successes before failures — the same successes-first convention as Effect.partition above.
import { Option } from "effect"declare const employeeOverride: Option.Option<string>declare const teamDefault: Option.Option<string>// The first present value wins: override, then team default, then the global default.const bandId = Option.firstSomeOf([employeeOverride, teamDefault, Option.some("L1")])// orElse takes a lazy alternative Option.const overrideOrTeam = employeeOverride.pipe(Option.orElse(() => teamDefault))// liftPredicate: a boolean test becomes an Option-returning function.const positiveRaise = Option.liftPredicate((percent: number) => percent > 0)positiveRaise(-5) // Option.none()positiveRaise(4) // Option.some(4)
Exit
Use it at
Option.getOrElse(() => fallback)
rendering and defaults that the boundary owns
Option.getOrNull / Option.getOrUndefined
JSON, SQL parameters, UI props — the mirror of fromNullOr / fromUndefinedOr / fromNullishOr
invariants only; it reintroduces the hidden crash the type removed
Keep absence visible until a real boundary. Carry an optional domain field as Option through the domain and collapse it only where rendering, JSON, SQL, or interop needs a concrete value. Use None when callers need no reason and Result when they must act on one. The quiet wrong turn is defaulting every branch to a plausible success (getOrElse(() => 0) for an unknown salary): it type-checks and is silently wrong.
Option.makeEquivalence and Option.makeOrder lift an Equivalence or Order for A to Option<A>, so optional fields can take part in sorting and de-duplication. None orders before every Some; Order.flip reverses the whole order, which puts missing values last and present values in descending order.
Official guides: Option (its statement that an Option can be yielded directly inside Effect.gen does not hold for this edition's tagged source; see Moving between Option, Result, and Effect), Effect Data Types (Schema) for nullable and optional wire shapes that decode to Option.
Result.succeed(a) or Result.fail(e). Synchronous, pure success-or-failure — Effect's error channel without async or requirements.
Mental model.Effect minus the runtime. Use Result for pure computations that can fail (validation, parsing); bridge into Effect with Effect.result to materialize an outcome.
Self-contained source · Type-checked
ts
import { Effect, Result } from "effect"interface CompBand { min: number; mid: number; max: number }// A pure validation — is a raise recommendation within the comp band?const validateRaise = ( currentSalary: number, proposedSalary: number, band: CompBand): Result.Result<number, string> => { if (proposedSalary < band.min) return Result.fail(`proposed salary ${proposedSalary} is below band minimum ${band.min}`) if (proposedSalary > band.max) return Result.fail(`proposed salary ${proposedSalary} exceeds band maximum ${band.max}`) if (proposedSalary <= currentSalary) return Result.fail(`raise must exceed current salary ${currentSalary}`) return Result.succeed(proposedSalary)}const band: CompBand = { min: 100_000, mid: 125_000, max: 150_000 }const approved = Result.getOrElse(validateRaise(120_000, 130_000, band), () => 120_000) // 130_000const rejected = Result.getOrElse(validateRaise(120_000, 160_000, band), () => 120_000) // 120_000 (capped)// Bridge the Effect error channel INTO a Result to inspect it without failing.const program = Effect.gen(function*() { const outcome = yield* Effect.result(Effect.fail("HrisUnavailable")) if (Result.isFailure(outcome)) { yield* Effect.log(`comp lookup failed: ${outcome.failure}`) }})
Use when you need a pure, eager "did it work?" value — validation logic, eligibility checks, or inspecting an effect's outcome before branching.
import { Result } from "effect"declare const salary: Result.Result<number, string>declare const levelMidpoint: Result.Result<number, string>// all: struct (or tuple) in, same shape out. The FIRST failure wins; nothing is accumulated.const compaRatio = Result.all({ salary, levelMidpoint }).pipe( Result.map(({ salary, levelMidpoint }) => salary / levelMidpoint), Result.flatMap((ratio) => ratio > 1.2 ? Result.fail("above the band ceiling") : Result.succeed(ratio)), Result.mapError((reason) => ({ _tag: "InvalidComp" as const, reason })))// match folds both branches into one value.const label = Result.match(compaRatio, { onFailure: (error) => `rejected: ${error.reason}`, onSuccess: (ratio) => `compa-ratio ${ratio.toFixed(2)}`})
Result.map / mapError / mapBoth transform one or both sides, flatMap chains a dependent check, and Result.gen is the imperative form. Result.all and Result.gen stop at the first failure; to collect every problem, validate each field to a Result and gather the failures yourself, or use Effect.validate. Like Option.gen, Result.gen runs eagerly and should stay free of side effects.
without the second argument, None fails with Cause.NoSuchElementError
Result → Effect
Effect.fromResult(result)
a Failure<E> becomes the typed failure E
nullable → Effect
Effect.fromNullishOr(value)
fails with Cause.NoSuchElementError
Effect → Result / Option / Exit
Effect.result / Effect.option / Effect.exit
result and option capture typed failures only; exit captures the full Cause
Fragment · Type-checked
ts
import { Data, Effect, Option, Result } from "effect"interface Employee { readonly id: string readonly managerId: string | null}declare const employees: ReadonlyArray<Employee>class NoSuchEmployee extends Data.TaggedError("NoSuchEmployee")<{ readonly employeeId: string }> {}class NoManager extends Data.TaggedError("NoManager")<{ readonly employeeId: string }> {}// Absence: callers need no reason.const findEmployee = (employeeId: string) => Option.fromNullishOr(employees.find((employee) => employee.id === employeeId))// Absence plus a reason: still pure, now a named failure.const requireEmployee = (employeeId: string) => Result.fromOption(findEmployee(employeeId), () => new NoSuchEmployee({ employeeId }))// A reason inside a workflow: convert explicitly, then yield the Effect.const loadManagerId = Effect.fn("loadManagerId")(function*(employeeId: string) { const employee = yield* Effect.fromResult(requireEmployee(employeeId)) return yield* Effect.fromOption( Option.fromNullishOr(employee.managerId), () => new NoManager({ employeeId }) )}) // Effect<string, NoSuchEmployee | NoManager>
Warning:Option and Result are not yieldable inside Effect.gen, and neither is a subtype of Effect. yield* someOption is rejected by TypeScript at the Effect.gen call, and if the types are bypassed the fiber dies with Fiber.runLoop: Not a valid effect: some(1). Convert with Effect.fromOption / Effect.fromResult (also before passing one to Effect.all), or match on it. Option.gen and Result.gen do yield their own type. The official Option and Result guides, and upstream migration/yieldable.md, say otherwise; the tagged source wins.
Pulling a value out early with Option.getOrThrow, or re-throwing result.failure, reintroduces exactly the hidden branch these types removed. For the three-way choice itself, see Option vs Result vs Effect.
Official guide: Result (the same caveat applies to its claim that a Result can be yielded inside Effect.gen).
A function (input) => Result<Pass, Fail> that decides whether a value passes (optionally refining or transforming it) or is filtered out. A predicate that can narrow the type and explain the rejection.
Mental model. A refinement built on Result. The pass branch can have a different type than the input, so filters act as type guards and mini-parsers that compose. They power Effect.catchFilter and stream filtering.
Self-contained source · Type-checked
ts
import { Filter, Result } from "effect"interface Employee { id: string; name: string; level: string; performanceRating: string; baseSalary: number }// A filter that keeps only employees eligible for a merit increase:// must be rated "exceeds" or "meets" and not already at band maximum.const BAND_MAX = 150_000const eligibleForMerit = Filter.make((emp: Employee) => { if (emp.performanceRating === "below") return Result.fail(emp) // filtered out — not eligible if (emp.baseSalary >= BAND_MAX) return Result.fail(emp) // filtered out — already at ceiling return Result.succeed(emp) // passes through for raise calculation})const priya: Employee = { id: "e-42", name: "Priya Sharma", level: "L4", performanceRating: "exceeds", baseSalary: 120_000 }eligibleForMerit(priya) // Result.succeed(priya)const atCeiling: Employee = { id: "e-99", name: "Dev Anand", level: "L5", performanceRating: "meets", baseSalary: 150_000 }eligibleForMerit(atCeiling) // Result.fail(atCeiling) — at band max// Built-in filters compose; turn one into a plain predicate when needed.const isNumber = Filter.toPredicate(Filter.number)isNumber(42) // true
Filter.tagged("Tag") is the ready-made filter for one member of a _tag union; pass it to Effect.catchFilter as shown in Selective recovery beyond one tag.
Use when you need a reusable, composable keep-or-drop rule that also refines types — selective error recovery with catchFilter, or validating-and-narrowing untrusted input.
Helpers for defining value types — classes, tagged classes, tagged enums (discriminated unions), and error classes. Two Data values with the same contents are Equal, usable as keys in HashMap/HashSet and comparable via Equal.equals.
Mental model.Equal.equals is already structural for plain objects, arrays, and instances of ordinary classes, so Data is not what gives you value equality. Data supplies the ergonomics around it: class syntax with a typed constructor argument, an automatic _tag, tagged-enum constructors with $is/$match, and yieldable Error subclasses. A plain factory function is a complete value-object constructor when you need none of that; Equal.byReference(value) opts one object back into reference equality.
Self-contained source · Type-checked
ts
import { Data, Equal } from "effect"// A tagged union for the state of a raise recommendation in a merit workflow.type RaiseState = Data.TaggedEnum<{ Pending: { readonly employeeId: string } Approved: { readonly employeeId: string; readonly newSalary: number } Rejected: { readonly employeeId: string; readonly reason: string }}>const { Pending, Approved, Rejected, $match } = Data.taggedEnum<RaiseState>()const a = Approved({ employeeId: "e-42", newSalary: 130_000 })const b = Approved({ employeeId: "e-42", newSalary: 130_000 })Equal.equals(a, b) // true — structural, not referenceconst describe = $match({ Pending: (s) => `awaiting approval for ${s.employeeId}`, Approved: (s) => `${s.employeeId} approved at $${s.newSalary}`, Rejected: (s) => `${s.employeeId} rejected: ${s.reason}`})describe(a) // "e-42 approved at $130000"
$is(tag) is the reusable type guard that pairs with $match, and Data.Class / Data.TaggedClass are the class forms — the ones that can carry getters and methods:
Self-contained source · Type-checked
ts
import { Data, Equal } from "effect"type RaiseState = Data.TaggedEnum<{ Pending: { readonly employeeId: string } Approved: { readonly employeeId: string; readonly newSalary: number }}>const { $is, Approved, Pending } = Data.taggedEnum<RaiseState>()const states = [Pending({ employeeId: "e-1" }), Approved({ employeeId: "e-42", newSalary: 130_000 })]const approved = states.filter($is("Approved")) // narrowed: newSalary is typedclass CompBand extends Data.Class<{ readonly level: string; readonly min: number; readonly max: number }> { get midpoint() { return (this.min + this.max) / 2 }}const l4 = new CompBand({ level: "L4", min: 100_000, max: 150_000 })const same = new CompBand({ level: "L4", min: 100_000, max: 150_000 })const sameReference = l4 === same // false: `===` is still reference equalityconst sameValue = Equal.equals(l4, same) // true// Update by replacement.const widened = new CompBand({ level: l4.level, min: l4.min, max: 160_000 })
Three caveats:
readonly is a TypeScript promise, not a runtime freeze.Data values are not frozen, so a cast can still mutate one.
=== remains reference equality. Use Equal.equals wherever value equality is meant: assertions, de-duplication, cache keys.
Never mutate a value after it has been compared, hashed, or used as a key.Equal.equals caches its result per object pair and Hash caches hashes, so a mutated value keeps its stale equality. Build a new value instead.
The Data module exports Class, TaggedClass, TaggedEnum / taggedEnum, Error, and TaggedError. Generic unions use Data.TaggedEnum.WithGenerics<N>.
Data.TaggedError builds an Error subclass that is also a tagged, value-equal effect failure — suitable for quick internal errors. For serializable errors, prefer Schema.TaggedError (shown above).
Self-contained source · Type-checked
ts
import { Data } from "effect"// Quick internal errors — no schema needed, but still tagged and value-equal.class BudgetExceeded extends Data.TaggedError("BudgetExceeded")<{ readonly requested: number readonly remaining: number}> {}class EmployeeNotFound extends Data.TaggedError("EmployeeNotFound")<{ readonly employeeId: string}> {}
Yieldable errors. Classes built with Data.Error, Data.TaggedError, Schema.Error, or Schema.TaggedError extend Cause.YieldableError, so yield* new BudgetExceeded({ ... }) inside Effect.gen is the same as yield* Effect.fail(new BudgetExceeded({ ... })); return yield* tells TypeScript the branch ends there. Data.Error is the untagged base: still an Error subclass with typed fields, but not selectable by catchTag.
Fragment · Type-checked
ts
import { Data, Effect } from "effect"class LedgerCorrupted extends Data.Error<{ readonly ledgerId: string }> {}// A field literally named `cause` becomes the native `Error.cause`, so `Cause.pretty`// and the Node inspector print the wrapped exception under `[cause]`.class PayrollExportFailed extends Data.TaggedError("PayrollExportFailed")<{ readonly batchId: string readonly cause: unknown}> {}declare const pushBatch: (batchId: string, signal: AbortSignal) => Promise<void>const exportBatch = (batchId: string) => Effect.tryPromise({ try: (signal) => pushBatch(batchId, signal), catch: (cause) => new PayrollExportFailed({ batchId, cause }) })const verifyLedger = Effect.fn("verifyLedger")(function*(ledgerId: string, checksumOk: boolean) { if (!checksumOk) return yield* new LedgerCorrupted({ ledgerId }) return ledgerId})
Warning:_tag strings must be unique across every error that can meet in one union. catchTag and TypeScript narrowing both trust the tag, and nothing stops two classes from reusing one: they become indistinguishable, with no compiler or runtime warning. Namespace tags that cross package boundaries ("Payroll/ExportFailed").
Use when you need value objects, discriminated unions with tidy constructors and a built-in matcher, or lightweight tagged errors.
A pluggable sink for reporting Causes — controls how unhandled failures are surfaced. Register reporters via a Context.Reference; annotate error types with severity and attributes for structured rendering.
Mental model. Logging is for messages; ErrorReporter is for errors as first-class artifacts — it understands Cause structure, severity, and per-error metadata.
Self-contained source · Type-checked
ts
import { Cause, Effect, ErrorReporter } from "effect"// Report a cause through the currently-installed reporters.// Here: a comp service failed during a merit cycle run.const program = ErrorReporter.report( Cause.fail("HrisUnavailable: timed out fetching employee roster"))// Mark a domain error's severity and structured attributes so reporters render it richly.class BandViolationError extends Error { override readonly [ErrorReporter.severity] = "Error" override readonly [ErrorReporter.attributes] = { employeeId: "e-42", proposedSalary: 160_000, bandMax: 150_000 }}
Use when you need centralized, structured error reporting (to a dashboard, Sentry-like sink, or custom channel) that understands causes and severity.
The typed error family for platform operations (filesystem, paths, child processes). Two shapes: BadArgument (invalid input) and SystemError (OS-level failure: ENOENT, EACCES, etc.), unified under PlatformError.
Mental model.FileSystem.readFileString fails with a PlatformError you can catchTag on, including the syscall, path, and reason — not a stringly-typed Error.
Self-contained source · Type-checked
ts
import { Effect, FileSystem } from "effect"// Load a comp-band configuration file. Recover gracefully if the file is missing.const loadCompBands = Effect.fn("loadCompBands")( function*() { const fs = yield* FileSystem.FileSystem return yield* fs.readFileString("./comp-bands.json") }, // PlatformError is tagged ("PlatformError"); its .reason holds BadArgument | SystemError. Effect.catchTag("PlatformError", (error) => error.reason._tag === "NotFound" ? Effect.logWarning("comp-bands file not found").pipe( Effect.as("{}") // fall back only for the expected missing-file case ) : Effect.fail(error) // preserve permission, timeout, invalid-input, and other failures ))
Use when handling I/O from platform modules (FileSystem, Path, process) and reacting to specific failure reasons — e.g., distinguishing a missing file from a permission error.
Tip:Expected problems (not found, out of band, budget exceeded) belong in the typed E channel as tagged errors you catchTag. Unexpected problems (bugs, "impossible" states) should be defects — surface them via Cause/ErrorReporter rather than modeling as recoverable errors.
Bucket
How it arises
Where it shows up
Who may recover
What a test asserts
Typed failure
Effect.fail, yielding an error instance, Effect.try / tryPromise (the { try, catch } form fails with what catch returns; the direct function form fails with Cause.UnknownError), a failed decode
E, and a Fail reason in the Cause
the narrowest owner with a meaningful policy (catchTag, Effect.match)
the tag and the fields, through Exit.findErrorOption(exit)
Defect
Effect.die, Effect.orDie, a throw inside Effect.sync, a rejection inside Effect.promise
not in E; a Die reason
a process or request boundary that reports it (ErrorReporter, tapDefect, catchDefect)
Exit.hasDies(exit), and that Exit.findErrorOption(exit) is None
Interruption
timeout, race loser, Fiber.interrupt, a closing scope, a host signal
not in E; an Interrupt reason
nobody: finalizers run and it propagates
Exit.hasInterrupts(exit) plus the cleanup effect, never a domain tag
Exit.findErrorOption returns None for defects and interruptions, so a typed-failure assertion cannot accept a defect by accident. Two gotchas: retrying or defaulting a defect hides a bug, and translating interruption into a user-facing error creates noise and can block shutdown. Where a boundary must survive a defect (a plugin host, a per-job worker), Effect.catchDefect should recover only the defect it recognizes and re-raise the rest with Effect.die(defect). The testing deep dive shows these assertions in context: Assert typed failures as data. For symptoms and fixes, see Typed failure versus defect and interruption.
Effect's coordination primitives let fibers share permits, queues, broadcasts, pooled resources, and replaceable scoped values without abandoning typed errors or structured concurrency. Start with Semaphore, Queue, or PubSub; use the partitioned, reference-counted, and scoped variants when ownership or lifecycle becomes the harder part.
Official guides: the Semaphore, Queue, and PubSub guides are linked from the matching sections below. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Fork variants and fiber ownership live in Core Runtime & Execution; stream-level buffering and backpressure live in Streaming & Channels. This page owns what happens between fibers: who waits, who is told "no", and what is lost.
A counting semaphore with a fixed permit pool. Fibers that need to do work acquire one or more permits; if insufficient permits are free they suspend until permits are released. Waiters are scanned in registration order and the first one whose request fits the free permits goes next; a new request that would fit is queued behind an earlier waiter that also fits rather than overtaking it. A smaller request can still overtake a larger earlier request whose permit count is unavailable, so do not assume strict FIFO fairness with mixed permit counts.
withPermits(n)(effect) acquires n permits, runs the effect, and releases them on success, failure, or interruption. withPermit is the single-permit mutual-exclusion alias. withPermitsIfAvailable is the non-blocking variant that runs only if permits are currently free.
For a lower-level protocol, take(n) manually acquires permits and release(n) returns them; takeIfAvailable(n) returns false immediately without acquiring when the count is unavailable. Prefer the bracketed with* helpers unless ownership genuinely spans multiple operations, because manual acquisition must be released on every exit. When the permits should live as long as a Scope — a lease held across several steps of a scoped workflow — use Semaphore.takeScoped(sem, n) (or sem.takeScoped(n)): it waits interruptibly, then takes the permits and registers their release on the scope in one uninterruptible step, so acquired permits are always returned when the scope closes.
Self-contained source · Type-checked
ts
import { Effect, Semaphore } from "effect"// Cap concurrent calls to the HRIS API at 5 — HRIS rate-limits at 10 rps// and we share the quota across multiple services.const program = Effect.gen(function*() { const sem = yield* Semaphore.make(5) // sem.withPermit(task) acquires 1 permit, runs the task, then releases. const fetchEmployee = (id: string) => sem.withPermit(Effect.gen(function*() { yield* Effect.log(`fetching employee ${id} from HRIS`) // ... real HRIS HTTP call here return { id, name: "Alice Example", level: 6 } })) // Fire 20 lookups at once; at most 5 hit the HRIS simultaneously. const ids = Array.from({ length: 20 }, (_, i) => `emp-${i}`) const employees = yield* Effect.all(ids.map(fetchEmployee), { concurrency: "unbounded" }) yield* Effect.log(`loaded ${employees.length} employees`)})
Two placement rules decide whether a semaphore enforces anything:
Share one semaphore value among every caller that participates in the limit. A semaphore constructed inside the job gives each job its own permits and limits nothing; build it once in a Layer or the wiring code and pass it down.
Wrap the scarce call only. Parsing, validation, and mapping that happen before or after the HRIS request do not consume the quota, so holding a permit across them lowers throughput without protecting anything.
Note:concurrency: "unbounded" is justified only when something else is the bound. Above, the collection is a fixed 20 elements and the semaphore caps the real work, so 20 mostly suspended fibers are harmless. Over input of unknown size the same option starts one fiber per element before any of them holds a permit. Give the traversal a number too, and derive both numbers from the resource being protected (vendor quota, pool size, sockets, CPU), not from whatever made a benchmark faster.
For the non-blocking variant:
Self-contained source · Type-checked
ts
import { Effect, Option, Semaphore } from "effect"// Try to push a real-time payroll recalculation — skip if the slot is taken.const tryRecalculate = (sem: Semaphore.Semaphore, employeeId: string) => sem.withPermitsIfAvailable(1)( Effect.log(`recalculating payroll for ${employeeId}`) )const program = Effect.gen(function*() { const sem = yield* Semaphore.make(1) const result = yield* tryRecalculate(sem, "emp-42") // Option.Some(void) if a permit was free; Option.None if the slot was busy yield* Effect.log(Option.isSome(result) ? "recalculation queued" : "skipped — already running")})
Use when you need global concurrency limiting — "at most N concurrent fibers" — across many fibers sharing one semaphore.
A semaphore with a shared permit pool where waiters are grouped by a partition key. Released permits are distributed to waiting partitions in round-robin order (not global FIFO), preventing any one busy partition from starving others. A waiter that needs several permits is completed before the rotation moves on, so multi-permit waiters in different partitions cannot deadlock by each holding part of what they need.
API mirrors plain Semaphore but every acquire/wrap call takes a partition key first. PartitionedSemaphore.make takes { permits }; the type parameter K is the partition key type.
Self-contained source · Type-checked
ts
import { Effect, PartitionedSemaphore } from "effect"// 10 shared HRIS API permits split fairly across department IDs.const program = Effect.gen(function*() { const sem = yield* PartitionedSemaphore.make<string>({ permits: 10 }) // sem.withPermit(key) acquires 1 permit for that partition key. const fetchPayrollForDept = (deptId: string, work: Effect.Effect<void>) => sem.withPermit(deptId)(work) // engineering and facilities share the same 10 permits fairly; // neither partition starves the other when releases occur. yield* Effect.all([ fetchPayrollForDept("engineering", Effect.log("eng: bulk adjustment")), fetchPayrollForDept("engineering", Effect.log("eng: another adjustment")), fetchPayrollForDept("facilities", Effect.log("fac: quick adjustment")) ], { concurrency: "unbounded" })})
sem.withPermits(key, n)(effect) acquires n permits for a key. withPermitsIfAvailable remains available for non-blocking checks against the shared pool without a partition key.
Note: The key buys fairness, not isolation. Every partition draws from the same permits total, so one tenant can still hold all ten permits while nobody else is waiting. When each tenant needs its own independent ceiling, keep one plain Semaphore per key instead.
Use when a shared resource has multiple independent consumer categories and fairness across groups (not a single FIFO line) is required.
A fiber-safe FIFO queue for passing values from producers to consumers: each value is delivered to exactly one taker. Supports bounded and unbounded variants, three overflow strategies, explicit end-of-stream signaling via Queue.end, and failure/interruption propagation.
Decide what happens when the queue is full before you pick a constructor. Overflow behavior is part of the queue's contract, not a tuning knob:
Constructor
When full
What the producer observes
What is lost
Choose when
Queue.bounded(n)
offer suspends until a consumer frees a slot
The producing fiber waits; offer then returns true
Nothing
Every value must be processed and the producer is an Effect that can wait
Queue.dropping(n)
The new value is rejected
offer returns false; offerAll returns the rejected remainder
The newest values
Shedding load is an accepted policy and you count what was shed
Queue.sliding(n)
The oldest buffered value is evicted
offer returns true — the eviction is not reported
The oldest values
Only the latest state matters (progress, presence, prices)
Queue.unbounded()
Never full
Nothing
Nothing, until memory runs out
The producer is already bounded by something else you can name
Queue.make({ capacity, strategy }) is the general constructor: omit capacity for an unbounded queue, and strategy defaults to "suspend". Queue.bounded(0) is a rendezvous queue — it buffers nothing, and an offer completes only when a consumer takes the value; an offerAll hands one value to each taker already waiting and suspends with the rest until more takers arrive. The other zero-capacity variants also hand values only to waiting takers: Queue.dropping(0) rejects an offer (false, or the remainder from offerAll) when nobody is waiting, and Queue.sliding(0) gives waiting takers the newest values and silently discards an offer nobody is waiting for — it still returns true. In every variant offer also returns false once the queue has ended, failed, or shut down. offerAll copies the values it buffers, so mutating the caller's array afterwards does not change what consumers receive.
Self-contained source · Type-checked
ts
import { Cause, Effect, Queue } from "effect"// Payroll batch work queue: producer loads employee IDs from HRIS,// consumers process each payroll calculation in parallel.const program = Effect.gen(function*() { // 500-slot bounded queue; producer back-pressures when full const queue = yield* Queue.bounded<string, Cause.Done>(500) // Producer fiber: enqueue employee IDs for this pay cycle, then signal done yield* Effect.forkChild(Effect.gen(function*() { const employeeIds = ["emp-001", "emp-002", "emp-003"] // from HRIS in practice yield* Queue.offerAll(queue, employeeIds) yield* Queue.end(queue) })) // Consumer: drain all items until the queue signals Done const processed = yield* Queue.collect(queue) yield* Effect.log(`payroll batch complete: ${processed.length} employees processed`)})
Queue splits into Enqueue (write-only) and Dequeue (read-only) interfaces. Use Queue.asEnqueue(q) for producers and Queue.asDequeue(q) for consumers. Consume as a Stream with Stream.fromQueue(queue); the stream ends when the queue ends.
Consuming: the consumer picks its waiting policy
Operator
Waits?
Returns
Queue.take(q)
Until one value is available
A; fails with the queue's terminal error (Cause.Done after end)
Queue.takeBetween(q, min, max)
Until min are buffered
At most max values; with min of 1 it is the "batch whatever is ready" operator
Queue.takeN(q, n)
As takeBetween(q, n, n)
n values once that many are buffered — fewer only while the queue is closing (see the note below)
Queue.takeAll(q)
Until at least one is available
A non-empty array of everything buffered (takeBetween(q, 1, Infinity))
Queue.poll(q)
Never
Option<A>; None when empty or finished
Queue.clear(q)
Never
Everything buffered, possibly [] — the non-waiting drain
Queue.peek(q)
Until one value is available
The head, without removing it
Queue.collect(q)
Until the queue ends
Every value until Cause.Done; a queue failure fails the effect
Note:takeBetween / takeN stay suspended on an open queue until the full min is buffered — they never resume early with a partial batch. Once Queue.end / Queue.fail puts the queue into its closing state, a pending batch take drains whatever remains even if that is fewer than min, so a batch consumer of a queue that is winding down still completes instead of hanging. After the queue finishes draining, the next take fails with the terminal error (Cause.Done after end, or the typed failure after fail). Batch consumers of a queue that can end should still check the returned array's length rather than assuming it is always min..max, because the final batch before the terminal error can be short.
Queue.size(q) and Queue.isFull(q) are snapshots for metrics and tests, not coordination: another fiber can change the answer before you act on it. After Queue.end, size keeps reporting the buffered values until consumers drain them.
Self-contained source · Type-checked
ts
import { Effect, Queue } from "effect"// A payroll exporter that writes whatever is ready, up to 50 rows per batch.const exportReadyRows = Effect.gen(function*() { const rows = yield* Queue.bounded<string>(500) yield* Queue.offerAll(rows, ["emp-001", "emp-002", "emp-003"]) const probe = yield* Queue.poll(rows) // Option.some("emp-001") — never waits const batch = yield* Queue.takeBetween(rows, 1, 50) // ["emp-002", "emp-003"] — waits only for the first const leftovers = yield* Queue.clear(rows) // [] — nothing buffered, returns immediately return { probe, batch, leftovers }})
Note:Queue.offerUnsafe appends synchronously and releases waiting takers on a scheduled task. Queue.flush(q) (or Queue.flushUnsafe(q)) runs that release pass immediately — useful in an adapter that offers from a synchronous callback and wants consumers woken before it returns.
Producers accept Queue.Enqueue<A, E>, consumers accept Queue.Dequeue<A, E>, and only the wiring code sees the full Queue.Queue.offer takes an Enqueue and Queue.take takes a Dequeue, so the compiler enforces the protocol: a scheduler cannot take work back, and a worker cannot quietly enqueue follow-up jobs. A full Queue is assignable to either role, so call sites need no conversion.
Stream.fromQueue and Queue.collect are the default consumers. When a worker needs a bespoke loop, take in a while (true) and close the loop on Cause.Done: Queue.end lets buffered values drain, the next take fails with Cause.Done, and Effect.catchIf(Cause.isDone, …) removes it from the error channel.
Self-contained source · Type-checked
ts
import { Cause, Effect, Fiber, Queue } from "effect"interface RaiseApproval { readonly employeeId: string readonly amountUsd: number}// Write-only role: this function cannot take from the queue.const produce = ( outbox: Queue.Enqueue<RaiseApproval, Cause.Done>, approvals: ReadonlyArray<RaiseApproval>) => Queue.offerAll(outbox, approvals).pipe( Effect.andThen(Queue.end(outbox)) )// Read-only role: this function cannot offer follow-up work.const consume = ( inbox: Queue.Dequeue<RaiseApproval, Cause.Done>, handle: (approval: RaiseApproval) => Effect.Effect<void>) => Effect.gen(function*() { while (true) { yield* handle(yield* Queue.take(inbox)) } }).pipe( // Done is the protocol's normal ending, not a failure of this worker. Effect.catchIf(Cause.isDone, () => Effect.void) )// Only the wiring code holds the full Queue.const program = Effect.gen(function*() { const queue = yield* Queue.bounded<RaiseApproval, Cause.Done>(64) const worker = yield* consume(queue, (approval) => Effect.log(`applying raise for ${approval.employeeId}`) ).pipe(Effect.forkChild) yield* produce(queue, [ { employeeId: "emp-001", amountUsd: 4_000 }, { employeeId: "emp-002", amountUsd: 2_500 } ]) yield* Fiber.join(worker) // join before the owning scope exits})
A suspend strategy only exerts pressure on a producer that is itself an Effect and can wait on Queue.offer. A synchronous callback — a driver hook, an event emitter, a webhook SDK listener — cannot wait. Queue.offerUnsafe on a full bounded queue does not suspend anyone; it returns false and the value is gone. Any bounded buffer in front of such a producer is therefore a loss policy whether or not it is named one, so do not describe that adapter as backpressured.
The practice: choose dropping or sliding explicitly, count what was shed, and document the loss.
Dropping: the boolean from offer / offerUnsafe is the signal.
Sliding:offer returns true even when it evicts, so check Queue.isFullUnsafe immediately before Queue.offerUnsafe in the same synchronous callback; a full queue means this offer evicts one value.
Fragment · Type-checked
ts
import { Effect, Metric, Queue } from "effect"interface HrisChange { readonly employeeId: string}// The HRIS SDK pushes changes through a listener it never awaits.declare const onHrisChange: (listener: (change: HrisChange) => void) => voidconst shed = Metric.counter("hris_changes_shed_total", { incremental: true })const hrisChanges = Effect.gen(function*() { const changes = yield* Queue.dropping<HrisChange>(1_024) const context = yield* Effect.context<never>() onHrisChange((change) => { if (!Queue.offerUnsafe(changes, change)) { shed.updateUnsafe(1, context) // loss is a metric, not a silent overflow } }) // Consumers only ever see the read side. return Queue.asDequeue(changes)})// An Effect producer can use the same signal without the unsafe API.const offerOrCount = <A>(queue: Queue.Enqueue<A>, value: A) => Queue.offer(queue, value).pipe( Effect.tap((accepted) => accepted ? Effect.void : Metric.update(shed, 1)) )
"No loss" plus "the producer cannot slow down" is inconsistent without durable storage or admission control upstream. Stream.callback builds the same kind of queue from its { bufferSize, strategy } options; see Streaming & Channels for the stream-side policy.
Queue lifecycle: who ends it, and what a failure does
Decide three things when you create a queue: who owns it and its worker fibers, who signals the end, and whether shutdown drains or discards.
A producer failure must not strand consumers. A consumer blocked in take learns nothing from a producer fiber that died. Propagate a terminal signal: Queue.end for normal completion, Queue.fail(q, error) for a typed failure (both let buffered values drain first), or wrap the producer with Queue.into(q), which ends the queue on success and fails it with the producer's cause otherwise.
Queue.shutdown discards the buffer. On an open queue it interrupts pending takers and Queue.await callers, but pending single offers succeed with false and batch offers return their unaccepted suffix. If the queue was already closing via end/fail, shutdown preserves that terminal cause instead of replacing it with interruption. Reserve it for abandoning work. It returns true if this call did the shutting down, false if the queue had already completed — useful for "am I the one who closed it?" cleanup races. Queue.shutdownUnsafe is the synchronous variant for callback contexts that cannot run an Effect. The full termination table is in Structured Concurrency Through a Bounded Worker.
Test with capacity 1. Large buffers hide deadlocks and ordering bugs that a one-slot queue exposes immediately. Also interrupt a blocked offer and a blocked take and assert the next value still reaches a live consumer.
An in-memory queue is lost with the process. Work that must survive a restart belongs in PersistedQueue or an outbox table.
Fragment · Type-checked
ts
import { Cause, Effect, Queue, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { status: Schema.Int }) {}declare const loadEmployeeIds: Effect.Effect<ReadonlyArray<string>, HrisUnavailable>const program = Effect.gen(function*() { const queue = yield* Queue.bounded<string, HrisUnavailable | Cause.Done>(100) // Success ends the queue; HrisUnavailable fails it. Either way consumers wake up. yield* loadEmployeeIds.pipe( Effect.flatMap((ids) => Queue.offerAll(queue, ids)), Queue.into(queue), Effect.forkChild ) // Every id, or the producer's HrisUnavailable — never a consumer that waits forever. return yield* Queue.collect(queue)})
Smells worth a second look in review: Queue.unbounded chosen because a test hung, "exactly once" inferred from one happy-path run, and a poison job re-offered to the same in-memory queue forever.
Use for producer-consumer decoupling with back-pressure inside a single process: batch pipelines, worker pools, actor-style mailboxes, rate-limited ingestion.
Official guides: Queue (its takeAll description and takeUpTo heading do not match this edition's tagged source — use the table above — and it predates the Queue<A, E> completion protocol); the callback constructor in Creating Streams drives the same offerUnsafe / endUnsafe / failCauseUnsafe API.
An in-process publish/subscribe bus. Producers call PubSub.publish; every active subscriber receives a copy. Unlike Queue (one message to one consumer), PubSub fans every message to all subscribers simultaneously. Late subscribers miss messages unless a replay buffer is configured.
Subscriptions are scoped: PubSub.subscribe returns a Subscription cleaned up when the surrounding scope closes. Use Stream.fromPubSub(pubsub) for managed subscribe/unsubscribe lifecycle.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, PubSub, Stream } from "effect"// Domain event for the annual merit cycletype MeritCycleEvent = | { readonly _tag: "CycleOpened"; readonly cycleId: string; readonly budgetUsd: number } | { readonly _tag: "RaiseApproved"; readonly cycleId: string; readonly employeeId: string } | { readonly _tag: "CycleClosed"; readonly cycleId: string }// Expose the PubSub as an Effect serviceexport class MeritCycleEvents extends Context.Service<MeritCycleEvents, { publish(event: MeritCycleEvent): Effect.Effect<void> readonly subscribe: Stream.Stream<MeritCycleEvent>}>()("hr/MeritCycleEvents") { static readonly layer = Layer.effect( MeritCycleEvents, Effect.gen(function*() { const pubsub = yield* PubSub.bounded<MeritCycleEvent>({ capacity: 256, replay: 50 // late subscribers see the last 50 events on connect }) // Shut down the bus when the layer is released yield* Effect.addFinalizer(() => PubSub.shutdown(pubsub)) const publish = Effect.fn("MeritCycleEvents.publish")(function*(event: MeritCycleEvent) { yield* PubSub.publish(pubsub, event) }) // Each Stream.fromPubSub call creates its own independent subscription const subscribe = Stream.fromPubSub(pubsub) return MeritCycleEvents.of({ publish, subscribe }) }) )}// Subscriber: notify managers when a raise for one of their reports is approvedconst managerNotifier = Effect.gen(function*() { const events = yield* MeritCycleEvents yield* events.subscribe.pipe( Stream.filter((e) => e._tag === "RaiseApproved"), Stream.tap((e) => Effect.log(`raise approved for employee ${e.employeeId}`)), Stream.runDrain )})
Name the delivery you need before choosing; most "missing event" and "duplicated work" bugs come from picking the wrong column.
Question
Queue
PubSub
Who receives a value?
Exactly one taker; competing consumers split the work
Every subscriber that is subscribed at publish time gets its own copy
A consumer joins late
It takes whatever is still buffered
It sees only later messages, plus the last replay messages if configured
Nobody is listening
Values wait in the buffer
publish returns true and the message is discarded (only a replay buffer keeps it)
One consumer is slow
The others keep taking
The slowest subscriber fills the shared buffer and triggers the overflow strategy for everyone
How it ends
end / fail let consumers drain, then takers see Cause.Done or the error
PubSub.end(pubsub, finalValue) is sticky: every current subscriber gets its buffered messages then finalValue, every future subscriber gets any replay then finalValue, and later publishes return false. It is a value of type A, not a typed completion signal — take/takeAll/takeBetween deliver it, but non-suspending takeUpTo does not. PubSub.shutdown instead interrupts every pending/future take with no final message
Durability
In memory; gone on restart
In memory; gone on restart — not an event log
A message is retained until every current subscriber has taken it, which is why one lagging subscriber is enough to fill a bounded PubSub.
Overflow strategies mirror Queue: PubSub.bounded suspends publishers while any subscriber lags by a full buffer; PubSub.dropping discards the new message for every subscriber and publish returns false; PubSub.sliding evicts the oldest message — only lagging subscribers miss it — and publish still returns true. PubSub.unbounded never pushes back and grows with the slowest subscriber. Use bounded for correctness (e.g., audit log), sliding for latest-state, dropping for acceptable load shedding.
Treat dropping and sliding as stated loss policies, never as performance switches, and make the loss visible. As with Queue, suspension only works for a publisher that is an Effect; PubSub.publishUnsafe from a synchronous callback returns false on a full bounded PubSub instead of waiting. publish also returns false after shutdown.
Stream.fromPubSub is the default consumer. Tests, batch readers, and load-shedding code sometimes need the lower-level protocol: open a scoped PubSub.Subscriptionfirst, then publish, then read. A subscription is not a Queue.Dequeue; read it with PubSub.take (waits for one), PubSub.takeAll (waits for at least one), PubSub.takeBetween(sub, min, max), PubSub.takeUpTo(sub, max) (never waits, may return []), and PubSub.remaining(sub). Wrap one as a stream with Stream.fromSubscription.
Self-contained source · Type-checked
ts
import { Effect, Metric, PubSub } from "effect"const dropped = Metric.counter("merit_events_dropped_total", { incremental: true })// Publish, and turn a shed message into a number someone can alert on.const publishOrCount = <A>(bus: PubSub.PubSub<A>, event: A) => PubSub.publish(bus, event).pipe( Effect.tap((accepted) => accepted ? Effect.void : Metric.update(dropped, 1)) )const program = Effect.scoped(Effect.gen(function*() { const bus = yield* PubSub.dropping<string>(1) const inbox = yield* PubSub.subscribe(bus) // subscribe before publishing const kept = yield* publishOrCount(bus, "cycle-opened") // true const shed = yield* publishOrCount(bus, "cycle-closed") // false: buffer full, counted const first = yield* PubSub.take(inbox) // "cycle-opened" const pending = yield* PubSub.remaining(inbox) // 0 return { kept, shed, first, pending }}))
PubSub.publishAll(bus, events) publishes a batch. PubSub.capacity(bus) is a plain number, while PubSub.size(bus) is an effect that reports messages still held for at least one subscriber. PubSub.shutdown interrupts every pending take; observe it with PubSub.isShutdown or PubSub.awaitShutdown. PubSub.isPubSub(u) narrows an unknown value. A capacity of Infinity on bounded/dropping/sliding behaves like PubSub.unbounded — it never pushes back. Passing NaN or a fractional capacity (e.g. 1.5) is rejected to prevent nonterminating batch publication; use a positive integer or Infinity.
A scoped subscription is a claim you can test: once the subscribing scope closes, the bus must hold nothing on behalf of the departed subscriber. PubSub.size returning to its baseline is a cheap regression test for listener-array style leaks.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, PubSub } from "effect"it.effect("a closed subscription retains nothing", () => Effect.gen(function*() { const bus = yield* PubSub.bounded<string>(16) yield* Effect.scoped(Effect.gen(function*() { yield* PubSub.subscribe(bus) yield* PubSub.publish(bus, "cycle-opened") assert.strictEqual(yield* PubSub.size(bus), 1) // held for the live subscriber })) yield* PubSub.publish(bus, "cycle-closed") assert.strictEqual(yield* PubSub.size(bus), 0) // nobody left to hold it for }))
Use for one-to-many event fan-out within a process where multiple independent consumers should each see every message.
Official guide: PubSub (its prose calls the subscription a Dequeue; this edition's tagged source returns a PubSub.Subscription read with PubSub.take, and the guide omits the { capacity, replay } constructor form).
A managed pool of scoped resources. A fixed pool preallocates its configured size asynchronously; an elastic pool preallocates min and grows toward max on demand. It lends items through a fiber's Scope and reclaims idle elastic items after a configurable TTL. Pool.invalidate removes a broken item so the next borrower gets a fresh one.
Constructor
When to use
Pool.make({ acquire, size })
Fixed-size pool. Items are acquired eagerly up to size. Requires a Scope.
Elastic pool. Grows to max under load; shrinks idle items after TTL. Requires a Scope.
Pool.makeWithStrategy({ ... })
Full control over resizing and reclamation via a custom Strategy. Requires a Scope.
Self-contained source · Type-checked
ts
import { Context, Duration, Effect, Layer, Pool, Scope } from "effect"// A thin wrapper around a live HRIS HTTP sessioninterface HrisConnection { readonly fetchEmployee: (id: string) => Effect.Effect<{ id: string; name: string }> readonly close: Effect.Effect<void>}const acquireHrisConnection: Effect.Effect<HrisConnection, never, Scope.Scope> = Effect.acquireRelease( Effect.succeed<HrisConnection>({ fetchEmployee: (id) => Effect.succeed({ id, name: `Employee ${id}` }), close: Effect.void }), (conn) => conn.close )// Service tag for the poolexport class HrisPool extends Context.Service<HrisPool, Pool.Pool<HrisConnection>>()("hr/HrisPool") { // Elastic pool: keep 2 warm connections, allow up to 10 under load, // reclaim idle connections after 30 s. static readonly layer = Layer.effect( HrisPool, Pool.makeWithTTL({ acquire: acquireHrisConnection, min: 2, max: 10, timeToLive: Duration.seconds(30) }) )}// One operation: Pool.use borrows an item, runs the effect, and returns the// item on success, failure, or interruption — no Scope required.const fetchEmployee = (id: string) => Effect.gen(function*() { const pool = yield* HrisPool return yield* Pool.use(pool, (conn) => conn.fetchEmployee(id)) })// Several steps on the same connection: Pool.get lends it to the current Scope// and returns it when that Scope closes.const fetchManagerAndReport = (managerId: string, reportId: string) => Effect.scoped( Effect.gen(function*() { const pool = yield* HrisPool const conn = yield* Pool.get(pool) const manager = yield* conn.fetchEmployee(managerId) const report = yield* conn.fetchEmployee(reportId) return { manager, report } }) )
Borrowing API
Lifetime of the loan
Requirements
Pool.use(pool, f)
Exactly the effect returned by f
none — prefer it for a single operation
Pool.get(pool)
Until the surrounding Scope closes
Scope
Pool.reserve(pool, item)
Takes an already-leased item out of shared circulation until the Scope closes; only meaningful when concurrency > 1
Scope
Both use and get wait when every item is busy and the pool is at max, and fail with the acquisition error E when creating a new item fails. After the pool's scope closes they are interrupted. The pool keeps its items in a child of that scope which closes only when the pool itself shuts down, so finalizers registered in the same scope after the pool was made — which run first, in reverse order — can still borrow from it, even when idle items have expired and a fresh one must be acquired.
The concurrency option allows multiple fibers to share a single pooled item simultaneously — useful for thread-safe libraries where serialization is not needed. Set targetUtilization to control how full existing items must be before a new one is created; it defaults to 1 and the implementation clamps it to the inclusive range 0.1–1.
timeToLive bounds idle capacity, not item health. With the default timeToLiveStrategy: "usage", each TTL interval reclaims items in excess of current demand and never shrinks below min. With "creation", every item — including the min ones — is retired timeToLive after it was acquired and replaced, which is the setting for credentials or connections that must be recycled by age. Neither says anything about whether a checked-out item still works.
Invalidate only a resource you believe is broken.Pool.invalidate(pool, item) is for a dead socket or a corrupted session. An ordinary query failure or domain error should surface as a typed error and leave the item in the pool; recycling on every failure turns one bad request into connection churn.
invalidate matches by identity (===), so pass the borrowed value itself. Invalidating an item that is still on loan starts its replacement immediately and runs the old item's finalizer once the last borrower returns it.
Validate pool bounds before constructing the pool. Decode min, max, and timeToLive from configuration into a typed startup failure; a nonsensical size should never reach acquire.
Test TTL with virtual time. Build the scoped pool under TestClock, borrow a burst, TestClock.adjust past the TTL, and assert on acquire/release counters.
Fragment · Type-checked
ts
import { Effect, Pool, Schema } from "effect"import type { Scope } from "effect"class ConnectionLost extends Schema.TaggedError<ConnectionLost>()("ConnectionLost", {}) {}class QueryRejected extends Schema.TaggedError<QueryRejected>()("QueryRejected", { reason: Schema.String}) {}interface HrisConnection { readonly query: (sql: string) => Effect.Effect<ReadonlyArray<unknown>, ConnectionLost | QueryRejected>}declare const connect: Effect.Effect<HrisConnection, ConnectionLost, Scope.Scope>const makeQuery = Effect.gen(function*() { const pool = yield* Pool.makeWithTTL({ acquire: connect, min: 2, max: 10, timeToLive: "30 seconds" }) return (sql: string) => Pool.use(pool, (conn) => conn.query(sql).pipe( // Only a broken transport retires the connection. // QueryRejected stays a typed failure and the connection stays pooled. Effect.tapErrorTag("ConnectionLost", () => Pool.invalidate(pool, conn)) ))})
Waiters are served in arrival order. Capacity freed by a release, an ended reservation, a new acquisition, or a strategy reclaim goes to the longest-waiting borrower, so a burst of late arrivals cannot starve a fiber that has been queued longer.
Sampling occupancy.Pool.stats(pool) (unstable) returns a Pool.Stats snapshot { idle, used, pending, min, max } for metrics such as connection-pool gauges. Only successfully acquired items count; an item is used while borrowed or reserved, and an invalidated item stays used until its last borrower returns it — its replacement is acquired meanwhile, so idle + used can briefly exceed max. A borrower that has been woken but has not yet taken its item is not counted in pending.
pool.config, pool.state, and Pool.PoolItem exist for custom Pool.Strategy implementations — the pool tracks a usage counter and a linked list of available items internally. Treat these fields as implementation detail; application code should not read them.
Use when expensive resource acquisition (connections, client handles, API sessions) must be amortized across many fibers with automatic lifecycle management.
A reference-counted handle for a single scoped resource. The resource is acquired lazily on the first RcRef.get, shared among all active borrowers, and finalized when the last borrower's scope closes. An optional idleTimeToLive keeps it alive after all borrows end to avoid churn.
Each RcRef.get increments the count; closing the borrowing scope decrements it; when the count hits zero the resource is released.
Self-contained source · Type-checked
ts
import { Duration, Effect, RcRef } from "effect"// One shared PayrollClient across many concurrent payroll calculations.// The client is expensive to create (auth handshake), so we share it.const program = Effect.scoped( Effect.gen(function*() { const clientRef = yield* RcRef.make({ acquire: Effect.acquireRelease( Effect.succeed({ run: (cmd: string) => Effect.log(`payroll> ${cmd}`) }), (_client) => Effect.log("PayrollClient disconnected") ), idleTimeToLive: Duration.seconds(30) // stay open 30 s after last borrow }) // Two fibers share the same client; it is acquired exactly once. yield* Effect.all([ Effect.scoped(Effect.gen(function*() { const client = yield* RcRef.get(clientRef) yield* client.run("PROCESS emp-001 cycle-2025") })), Effect.scoped(Effect.gen(function*() { const client = yield* RcRef.get(clientRef) yield* client.run("PROCESS emp-002 cycle-2025") })) ], { concurrency: 2 }) // After both scopes close, the idle timer starts. // "PayrollClient disconnected" is logged 30 s later (or immediately if no TTL). }))
Omitting idleTimeToLive is not the same as 0. With the option omitted, the scope that releases the last borrow runs the finalizer and waits for it, so "disconnected" is logged before that scope finishes closing. Any finite duration, including 0 or Duration.zero, instead schedules the release on a forked fiber that the closing scope does not wait for; an infinite duration keeps the idle resource until invalidation or until the RcRef's own scope closes. Nobody awaits that forked idle-expiry release, so if it fails the failure is logged at References.UnhandledLogLevel rather than lost; a release that a closing scope does wait for still fails that scope.
RcRef.invalidate(ref) forces the next get to acquire a fresh resource. Existing borrows are unaffected and keep their already-acquired value until their scope closes.
Use when multiple concurrent scopes need to share one expensive resource and you want automatic acquire-on-first-use and release-when-idle without a full pool.
Like RcRef, but keyed. An RcMap<K, A> runs a lookup effect the first time a given key is requested, shares the resource among all active borrows for that key, and releases it when the last borrow closes (with optional idle TTL). Multiple keys are fully independent with separate reference counts. An optional capacity caps entries, idle ones included; a new key beyond it fails with Cause.ExceededCapacityError — existing entries are never evicted to make room.
Self-contained source · Type-checked
ts
import { Duration, Effect, RcMap } from "effect"// One PayrollClient per region — clients authenticate against a regional endpoint.interface PayrollClient { readonly run: (cmd: string) => Effect.Effect<string> readonly close: Effect.Effect<void>}const connectToRegion = (region: string): Effect.Effect<PayrollClient, never, import("effect").Scope.Scope> => Effect.acquireRelease( Effect.succeed<PayrollClient>({ run: (cmd) => Effect.succeed(`[${region}] ${cmd} ok`), close: Effect.log(`disconnected payroll client for region ${region}`) }), (c) => c.close )const program = Effect.scoped( Effect.gen(function*() { const clients = yield* RcMap.make({ lookup: connectToRegion, idleTimeToLive: Duration.minutes(5), // keep idle regional clients warm capacity: 10 // at most 10 regional clients alive }) // Two fibers borrow the "us-east" client — one connection, shared yield* Effect.all([ Effect.scoped(Effect.gen(function*() { const client = yield* RcMap.get(clients, "us-east") return yield* client.run("PROCESS cycle-2025 batch-1") })), Effect.scoped(Effect.gen(function*() { const client = yield* RcMap.get(clients, "us-east") return yield* client.run("PROCESS cycle-2025 batch-2") })) ], { concurrency: 2 }) // "us-east" client stays live for 5 min after last borrow, then disconnects. }))
RcMap.keys(map) inspects active keys. RcMap.invalidate(map, key) forces re-acquisition on next use. touch resets a key's idle TTL without using the resource. Idle time, touch included, is measured on the Clock of the context the map was made in, and the idle-expiry fiber runs in that context rather than the last borrower's: to drive expiry with TestClock, build the map under the test clock; a borrower that provides another Clock does not change when its entry expires. RcMap.getOption(map, key) borrows an entry only if it already exists: it returns Option.none() without running lookup for an absent key, and otherwise retains the entry for the current Scope exactly like get — useful for "flush the regional client if one is open" paths that must not open a connection just to close it.
When the RcMap's owner scope closes, it attempts every entry's release, clears the map, and then fails with all release defects together (this also covers resources managed through LayerMap). Releases nobody observes — idle expiry, or the lookup of a caller interrupted before it received its entry — are logged at References.UnhandledLogLevel.
Use for per-key resource management where keys are dynamic and resources should be released when no longer needed.
A Ref whose value owns a Scope. Setting a new value first acquires the replacement in a fresh scope, then finalizes the old scope, and only then publishes the replacement. Reads are lock-free and synchronous; writes are serialized (one swap at a time).
Self-contained source · Type-checked
ts
import { Effect, ScopedRef } from "effect"interface PayrollClient { readonly endpoint: string readonly run: (cmd: string) => Effect.Effect<void>}const acquireClient = (endpoint: string): Effect.Effect<PayrollClient, never, import("effect").Scope.Scope> => Effect.acquireRelease( Effect.succeed<PayrollClient>({ endpoint, run: (cmd) => Effect.log(`[${endpoint}] ${cmd}`) }), (c) => Effect.log(`closing client for ${c.endpoint}`) )// ScopedRef.fromAcquire requires a Scope; wrap in Effect.scoped to provide one.const program = Effect.scoped( Effect.gen(function*() { // Start with the primary regional payroll endpoint const clientRef = yield* ScopedRef.fromAcquire(acquireClient("payroll-us-east.internal")) // Read the current value — lock-free and synchronous const current = yield* ScopedRef.get(clientRef) yield* Effect.log(`connected to ${current.endpoint}`) // Hot-swap to the DR endpoint — acquire new, close old, then publish new yield* ScopedRef.set(clientRef, acquireClient("payroll-us-east-dr.internal")) const updated = yield* ScopedRef.get(clientRef) yield* Effect.log(`failed over to ${updated.endpoint}`) // Logs: "closing client for payroll-us-east.internal" // "failed over to payroll-us-east-dr.internal" }))
The set operation is uninterruptible by default. If replacement acquisition fails, its fresh scope is closed and the old value remains current. During a successful swap the newly acquired resource and the still-current old resource can both be live briefly while the old scope closes; readers continue to see the old value until the final assignment. This is atomic visibility, not zero-overlap resource lifetime. If the ScopedRef's own owning scope closes while make, fromAcquire, or set is still acquiring the replacement, that call finishes by interrupting the fiber instead of publishing a value into an already-closed ref.
ScopedRef.make(() => value) for a plain initial constant. ScopedRef.fromAcquire(effect) when the initial value requires resource acquisition. Both constructors require a Scope in the environment — wrap with Effect.scoped or run inside a scoped layer.
Use when a long-lived, resource-backed value must occasionally be replaced and the swap must be atomic and leak-free.
Note: Every transactional operation runs inside a boundary created by Effect.tx. There is no Effect.atomic and no Effect.transaction — just Effect.tx(effect). The outermostEffect.tx opens the journal and commits (or rolls back) the whole thing; nested Effect.tx calls transparently join the parent transaction instead of starting a new one. To make a transaction block until some condition holds — say, until enough merit budget is free — call Effect.txRetry.
A transaction is an optimistic, composable, all-or-nothing block of reads and writes over transactional cells (TxRef and the collections built on it).
Journaled, not in-place. Reads and writes go to a per-transaction journal recording version + value of every TxRef touched. Other fibers never see uncommitted writes.
Optimistic commit. At commit time the runtime checks every journaled ref's version against the live ref. If nothing changed, it commits atomically (bumps versions, wakes waiters). If a ref changed underneath, the transaction is discarded and re-run from scratch.
Retry = block until change.Effect.txRetry suspends the transaction; it wakes only when one of the refs it read is committed by another fiber, then retries. Zero busy-waiting.
Optimistic state does not acquire locks. Transactions over TxRef and its collections resolve conflicts by retrying instead of waiting while holding a lock. Effect also exposes the explicit TxReentrantLock; once you coordinate several such locks, ordinary lock-ordering discipline still matters and deadlock is possible.
Failure discards the journal. A typed failure, defect, or interruption that escapes the outermost Effect.tx abandons every journaled write, so "credit the allocation, then discover the pool is short" leaves both cells exactly as they were — there is no torn state to repair and no compensating write to remember.
There are no savepoints. A failure that is caught inside the transaction keeps the writes made before it, including writes made by a nested Effect.tx (which only joined the parent). Let the failure escape the outermost boundary when you want the rollback.
Readers need a transaction too. A lone TxRef.get is its own one-shot transaction, so two of them in a row can straddle another fiber's commit and observe a combination no transaction ever produced. Read every related cell inside one Effect.tx; a body whose reads were overtaken by another commit is re-run instead of being reported, even if that stale run failed.
Scope. Reach for STM when one invariant spans several in-memory cells (pool + allocations, queue + counter, permit + registry). A single cell is a Ref; anything that must survive a restart or be visible to another process is a database transaction — see SQL and the transactional write with outbox recipe.
The canonical example: draw down a shared merit budget
Self-contained source · Type-checked
ts
import { Effect, TxRef } from "effect"const program = Effect.gen(function*() { // Department merit pool (in whole dollars) and one employee's allocation. const budget = yield* TxRef.make(50_000) const aliceRaise = yield* TxRef.make(0) // One atomic transaction: debit the pool + record the raise commit together. const recommendRaise = ( pool: TxRef.TxRef<number>, allocation: TxRef.TxRef<number>, amount: number ) => Effect.tx(Effect.gen(function*() { const remaining = yield* TxRef.get(pool) // Not enough budget yet? Suspend and retry when the pool next changes. if (remaining < amount) { return yield* Effect.txRetry } yield* TxRef.update(pool, (b) => b - amount) yield* TxRef.update(allocation, (b) => b + amount) })) yield* recommendRaise(budget, aliceRaise, 8_000) console.log(yield* TxRef.get(budget)) // 42000 console.log(yield* TxRef.get(aliceRaise)) // 8000})
if (remaining < amount) return yield* Effect.txRetry is the entire condition-variable mechanism — if the pool is exhausted the fiber parks and wakes when any fiber commits a change to that ref, then re-checks. Two concurrent transactions conflict: the optimistic engine retries the loser; the pool never goes negative.
Tip: Most Tx* operations are self-transactional: a lone yield* TxQueue.offer(q, rec) runs in its own implicit one-shot transaction. Group several under one Effect.tx to commit them together. Constructors like TxRef.make return an Effect (use yield*); the makeUnsafe variants build synchronously outside an Effect.
Failure rolls back; snapshots need one transaction
Self-contained source · Type-checked
ts
import { Data, Effect, TxRef } from "effect"class BudgetExceeded extends Data.TaggedError("BudgetExceeded")<{ readonly overBy: number}> {}const program = Effect.gen(function*() { const pool = yield* TxRef.make(10_000) const allocated = yield* TxRef.make(0) const allocate = (amount: number) => Effect.tx(Effect.gen(function*() { yield* TxRef.update(allocated, (n) => n + amount) // journaled first... const remaining = yield* TxRef.modify(pool, (n) => [n - amount, n - amount]) if (remaining < 0) { return yield* new BudgetExceeded({ overBy: -remaining }) // ...then the body fails } })) const rejected = yield* Effect.exit(allocate(12_000)) // Failure(BudgetExceeded { overBy: 2000 }) // Neither write survived: pool is still 10000 and allocated is still 0. yield* allocate(4_000) // One transaction = one consistent view of both cells: { pool: 6000, allocated: 4000 }. // Two separate `TxRef.get` calls could land on either side of a concurrent `allocate` // and report a total that never existed. const snapshot = yield* Effect.tx(Effect.gen(function*() { return { pool: yield* TxRef.get(pool), allocated: yield* TxRef.get(allocated) } })) return { rejected, snapshot }})
Inside Effect.tx, yield Effect.Transaction to inspect the current attempt. attempt starts at 1; retryReason is initially undefined, then "retry" after Effect.txRetry or "conflict" after a journal version conflict. start and now are millisecond timestamps; elapsed and elapsedSincePrevious are millisecond durations stamped at the start of each attempt, not continuously updated timers. Nested transactions share the outer boundary's metadata.
Self-contained source · Type-checked
ts
import { Effect } from "effect"const firstAttempt = Effect.tx(Effect.gen(function*() { const tx = yield* Effect.Transaction // Copy fields if retaining a snapshot: the service is reused across retries. return { attempt: tx.attempt, retryReason: tx.retryReason, elapsed: tx.elapsed }}))// Effect.runSync(firstAttempt) -> { attempt: 1, retryReason: undefined, elapsed: 0 }
Attempt metadata is diagnostic information, not an idempotency or durability guarantee. The body can be re-evaluated: keep external writes, notifications, and irreversible effects outside STM. Use a database transaction and outbox when a committed intent must survive a process restart.
The atom of STM: a single mutable cell whose reads and writes participate in a transaction. Every other Tx* structure is one or more TxRefs under the hood.
Mental model.Ref, but transaction-aware. TxRef.update inside Effect.tx is atomic across all refs in the block, with automatic conflict retry. Reading a TxRef records it in the journal, enabling txRetry to wake the fiber when that value changes.
Self-contained source · Type-checked
ts
import { Effect, TxRef } from "effect"const program = Effect.gen(function*() { // Remaining headcount slots for a department's req plan. const openReqs = yield* TxRef.make(5) // modify: claim a req AND return how many were left before, in one step. const before = yield* Effect.tx( TxRef.modify(openReqs, (n) => [n, n - 1]) ) console.log(before) // 5 (the returned value) console.log(yield* TxRef.get(openReqs)) // 4 (the committed value)})
The API is deliberately small — make, makeUnsafe, get, set, update, modify. There is no updateAndGet or getAndSet as on Ref; return whatever you need from modify, for example TxRef.modify(ref, (n) => [n + 1, n + 1]) for the new value.
Reach for it when two or more pieces of state must change together and stay mutually consistent under concurrency, or when building custom transactional data structures.
A transactional growable sequence — a Chunk wrapped in a TxRef — with append, prepend, take, drop, slice, map, filter, isEmpty/isNonEmpty, all transactional. TxChunk.isTxChunk narrows an unknown value.
Mental model. Transactional analog of Chunk/array. Storage layer beneath TxQueue; use directly when you want ordered, indexable transactional state without queue semantics.
Self-contained source · Type-checked
ts
import { Effect, TxChunk } from "effect"const program = Effect.gen(function*() { // An append-only audit trail of comp-plan changes. const auditLog = yield* TxChunk.empty<string>() // Append two entries atomically — reviewers see both or neither. yield* Effect.tx(Effect.gen(function*() { yield* TxChunk.append(auditLog, "budget:debit 8000") yield* TxChunk.append(auditLog, "raise:recorded E-1042") })) console.log(yield* TxChunk.size(auditLog)) // 2})
Reach for it when you need a transactional ordered buffer or change-log and queue blocking semantics would be overkill.
Transactional key/value map: HashMap behind a TxRef, with get, set, remove, modify, modifyAt, plus map, filter, reduce, findFirst, union.
Mental model. Transactional analog of HashMap. Use for shared in-memory indexes where multiple keys may need to update together atomically.
Self-contained source · Type-checked
ts
import { Effect, Option, TxHashMap } from "effect"const program = Effect.gen(function*() { // Remaining merit budget per department (whole dollars). const pools = yield* TxHashMap.make( ["engineering", 120_000], ["sales", 80_000] ) // Atomically reallocate budget from one department to another. yield* Effect.tx(Effect.gen(function*() { yield* TxHashMap.modify(pools, "engineering", (n) => n - 15_000) yield* TxHashMap.modify(pools, "sales", (n) => n + 15_000) })) const eng = yield* TxHashMap.get(pools, "engineering") console.log(eng) // Option.some(105000) console.log(Option.getOrNull(eng))})
Reach for it when you have a shared mutable map and updates across several keys must be consistent (reallocations, reconciliation, multi-key invariants).
Transactional FIFO queue with bounded, unbounded, dropping, and sliding strategies. Interface-segregated into TxEnqueue (write-only) and TxDequeue (read-only). isEmpty/isNonEmpty check depth without blocking.
Mental model. Transactional analog of Queue. TxQueue.take on an empty queue internally calls Effect.txRetry, blocking (by suspend-and-wake, not spin) until an item arrives. offer on a full bounded queue similarly blocks. Operations compose transactionally — debit the budget pool and enqueue atomically.
Batch takes have their own waiting rule: on an open queue, takeN(queue, n) waits until min(n, capacity) items are available and removes exactly that many, while takeBetween(queue, min, max) waits only for min. A closing queue can return a short final batch. Counts are normalised — a fractional count is floored, and on an open queue NaN or a non-positive count returns [] without removing anything. For non-transactional queues see Queue.
Self-contained source · Type-checked
ts
import { Effect, Fiber, TxQueue } from "effect"const program = Effect.gen(function*() { // A bounded approval queue: HRBPs can only review so many at once. const approvals = yield* TxQueue.bounded<string>(8) // Managers submit raise recommendations from a forked fiber. yield* Effect.forkChild( Effect.forEach( ["E-1042", "E-2087", "E-3119"], (id) => TxQueue.offer(approvals, id) ) ) // Reviewer: take blocks (retries) until a recommendation is available. const first = yield* TxQueue.take(approvals) const second = yield* TxQueue.take(approvals) console.log(first, second) // E-1042 E-2087})
Reach for it when you need a work queue with backpressure or blocking takes, especially when enqueue/dequeue must coordinate atomically with other transactional state.
Transactional publish/subscribe hub. Publishers call publish; each subscriber gets a scoped TxQueue receiving messages sent after subscription. Strategies: bounded, unbounded, dropping, sliding. Subscriptions are scope-bound — leaving the scope cleans up the subscriber queue. size, isEmpty/isNonEmpty, and isFull read the publish buffer without blocking.
Mental model. Transactional analog of PubSub. Fan-out broadcast where the publish step can be part of a larger transaction.
Self-contained source · Type-checked
ts
import { Effect, TxPubSub, TxQueue } from "effect"const program = Effect.gen(function*() { // Broadcast comp decisions to every downstream listener. const decisions = yield* TxPubSub.unbounded<string>() yield* Effect.scoped(Effect.gen(function*() { const payroll = yield* TxPubSub.subscribe(decisions) const ledger = yield* TxPubSub.subscribe(decisions) yield* TxPubSub.publish(decisions, "raise-approved:E-1042") // Each subscriber receives its own copy. console.log(yield* TxQueue.take(payroll)) // "raise-approved:E-1042" console.log(yield* TxQueue.take(ledger)) // "raise-approved:E-1042" }))})
Reach for it when you need transactional broadcast to many consumers and want publishing to commit atomically alongside other state changes.
Counting semaphore whose permit acquisition is transactional. acquire/acquireN block (retry) until enough permits are free; tryAcquire never blocks; withPermit/withPermits bracket an effect with auto-release.
Mental model. Transactional analog of Semaphore. Use scoped helpers — they acquire before the effect and release on success, failure, or interruption, so permits are never leaked. The wait for a permit is itself interruptible: a fiber interrupted while blocked on acquire leaves no partially-acquired permits behind.
Self-contained source · Type-checked
ts
import { Console, Effect, TxSemaphore } from "effect"const program = Effect.gen(function*() { // The HRIS allows at most 2 concurrent sync calls. const hrisLimiter = yield* TxSemaphore.make(2) const syncEmployee = (id: string) => TxSemaphore.withPermit( hrisLimiter, Effect.gen(function*() { yield* Console.log(`syncing ${id} to HRIS`) yield* Effect.sleep("100 millis") }) ) // Only two run at a time; the rest wait for a freed permit. yield* Effect.forEach( ["E-1042", "E-2087", "E-3119", "E-4201"], syncEmployee, { concurrency: "unbounded" } )})
Reach for it when you need to cap concurrency or model a finite pool of resources, and want acquisition to compose transactionally with other STM state.
Transactional reader-writer lock that is reentrant: the same fiber can re-acquire a lock it already holds. Multiple readers may share the read lock; a writer gets exclusive access. Helpers: withReadLock, withWriteLock, withLock, plus scoped readLock/writeLock.
Mental model. Transactional analog of a classic RW-lock. Use when optimistic retry is not the right shape — e.g., read-mostly state that many fibers read but only one rewrites, with reentrancy to prevent self-deadlock in nested calls. Waiting for a read or write lock is interruptible, so a fiber interrupted before it acquires the lock leaves no partial hold.
Self-contained source · Type-checked
ts
import { Effect, TxReentrantLock } from "effect"const program = Effect.gen(function*() { // Guards the published comp-band table during a cycle re-band. const bandLock = yield* TxReentrantLock.make() const result = yield* TxReentrantLock.withWriteLock( bandLock, Effect.succeed("comp bands re-published") ) console.log(result) // "comp bands re-published"})
Reach for it when you want explicit reader/writer access control with reentrancy rather than relying purely on optimistic transaction retry.
Write-once transactional cell for a value produced later. await retries until completed; succeed/fail/done complete it exactly once (returning true on first completion, false thereafter); poll inspects without blocking.
Mental model. Transactional analog of Deferred — a one-shot promise that participates in transactions. await is built on Effect.txRetry: if the cell is empty the transaction parks and wakes when filled.
Self-contained source · Type-checked
ts
import { Effect, Fiber, TxDeferred } from "effect"const program = Effect.gen(function*() { // Signalled exactly once when the comp cycle freezes (no more edits). const cycleFrozen = yield* TxDeferred.make<string>() // Workers await the freeze before finalizing their allocations. const worker = yield* Effect.forkChild(TxDeferred.await(cycleFrozen)) // The cycle admin freezes it exactly once. yield* TxDeferred.succeed(cycleFrozen, "2026-Q2") console.log(yield* Fiber.await(worker)) // Exit.succeed("2026-Q2")})
Reach for it when one fiber must wait for a single result or signal produced by another, and that handoff should compose with other transactional state.
Transactional priority queue ordered by an Order. take returns the smallest element by that order. Constructors (empty, make, fromIterable) take the Order up front. offer/offerAll insert in priority order (offerAll merges the batch in rather than re-sorting the whole queue). Also peek, takeUpTo, removeIf, retainIf, isEmpty/isNonEmpty.
Mental model. Transactional analog of a priority queue/heap. Use for scheduling where the next item to process is the highest-priority one and atomic offer/take across coordinated state is required. offerAll (and TxHashMap.fromIterable/setMany/removeMany, TxHashSet.fromIterable) preserve one-shot iterables across transaction retries, so passing a generator or iterator is safe even when the transaction is retried.
Self-contained source · Type-checked
ts
import { Effect, Order, TxPriorityQueue } from "effect"const program = Effect.gen(function*() { // Process raises by employee level: lowest level number = reviewed first. const queue = yield* TxPriorityQueue.fromIterable(Order.Number, [5, 3, 4]) console.log(yield* TxPriorityQueue.take(queue)) // 3 console.log(yield* TxPriorityQueue.take(queue)) // 4})
Reach for it when you need a transactional scheduler or work queue where ordering matters, not just FIFO arrival.
Transactional TxRef that also publishes its changes. Holds a current value (get/set/update/modify) and exposes committed updates as a Stream via changesStream (or a transactional queue via changes), always starting with the current value.
Mental model. Transactional analog of SubscriptionRef — observable shared state. Only committed values are broadcast; subscribers never see mid-transaction values.
Self-contained source · Type-checked
ts
import { Effect, Stream, TxSubscriptionRef } from "effect"const program = Effect.gen(function*() { // The merit cycle's lifecycle status, observable by dashboards. const status = yield* TxSubscriptionRef.make("planning") // Consume committed changes as a Stream (starts with current value). const seen = yield* Stream.runCollect( TxSubscriptionRef.changesStream(status).pipe(Stream.take(1)) ) console.log(seen) // ["planning"] yield* TxSubscriptionRef.set(status, "approvals")})
Reach for it when you have transactional shared state that other fibers must observe reactively, and they should only ever see consistent, committed snapshots.
Putting it together: a bounded approval pipeline with a freeze signal
Self-contained source · Type-checked
ts
import { Cause, Console, Effect, Option, TxDeferred, TxQueue } from "effect"const run = Effect.gen(function*() { const approvals = yield* TxQueue.bounded<number, Cause.Done>(4) // raise amounts, in dollars const cycleFrozen = yield* TxDeferred.make<void>() // Managers: submit 10 raise recommendations, then close the intake. const managers = Effect.gen(function*() { yield* Effect.forEach( Array.from({ length: 10 }, (_, i) => (i + 1) * 1_000), (amount) => TxQueue.offer(approvals, amount) // blocks (retries) while full ) yield* TxQueue.end(approvals) // intake closed for the cycle }) // Reviewer: clear the queue until intake closes, then signal the freeze. const reviewer = Effect.gen(function*() { let allocated = 0 while (true) { // take waits while open+empty, then reports Done only after the final drain. // Catch only normal completion; defects and external cancellation propagate. const next = yield* TxQueue.take(approvals).pipe( Effect.map(Option.some), Effect.catchIf(Cause.isDone, () => Effect.succeed(Option.none<number>())) ) if (Option.isNone(next)) break allocated += next.value } yield* Console.log(`total allocated: ${allocated}`) // 55000 yield* TxDeferred.succeed(cycleFrozen, undefined) }) yield* Effect.all([managers, reviewer], { concurrency: "unbounded" }) yield* TxDeferred.await(cycleFrozen) // wait for the reviewer to drain + freeze})
Warning: A transaction body can be re-run any number of times before it commits. Never put real-world side effects (network calls, Console output, anything observable) inside an Effect.tx block — they fire on every retry. Do pure state changes transactionally, then perform side effects after the transaction commits.
Tip: Reach for the smallest tool that fits: a single coordinated value → TxRef; keyed state → TxHashMap; membership → TxHashSet; ordered buffer → TxChunk; work queue with blocking/backpressure → TxQueue (priority ordering? TxPriorityQueue); broadcast → TxPubSub; observable value → TxSubscriptionRef; one-shot handoff → TxDeferred; concurrency cap → TxSemaphore; explicit reader/writer control → TxReentrantLock. They all compose under a single Effect.tx, so you can mix them in one atomic step.
Effect provides fiber-safe shared-state types (Ref, SynchronizedRef, SubscriptionRef) and unsynchronised in-place data structures (MutableRef, MutableList, MutableHashMap, MutableHashSet) for hot paths where Effect overhead is undesirable.
Official guides:Ref; section-specific guides are linked where they apply. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
An atomic mutable cell exposed as Effects. A Ref<A> holds one value; reads, writes, and transformations are Effect values — composable with fibers, timeouts, and retries. Internally wraps a MutableRef (a plain JS object with a .current field). Each pure update / modify runs synchronously without suspension, so another fiber cannot interleave its own operation inside that transition. The Effect wrapper makes the operation lazy and composable; it is not a lock around a sequence of separate calls.
modify atomically reads the current value, computes a result and a new value, and stores the new value in one step. update is the shortcut when no extra return value is needed.
Self-contained source · Type-checked
ts
import { Effect, Ref } from "effect"// Track remaining merit budget across concurrent raise recommendationsconst meritBudgetExample = Effect.gen(function*() { // Budget pool in basis points (e.g. 300 = 3.0% of payroll) const budget = yield* Ref.make(300) // Simulate 20 concurrent raise recommendations each consuming 15 bps yield* Effect.all( Array.from({ length: 20 }, () => Ref.update(budget, (remaining) => Math.max(0, remaining - 15)) ), { concurrency: "unbounded" } ) const remaining = yield* Ref.get(budget) console.log(`Remaining merit budget: ${remaining} bps`) // 0 — no lost updates})// modify: atomically claim a raise amount and return whether it was approvedconst claimBudget = Effect.fn("claimBudget")(function*( budgetRef: Ref.Ref<number>, requestedBps: number) { return yield* Ref.modify(budgetRef, (remaining) => { if (remaining >= requestedBps) { return [true, remaining - requestedBps] as const } return [false, remaining] as const })})
Ref.makeUnsafe(value) creates a Ref synchronously without wrapping in an Effect — for use inside class constructors or module top-levels before concurrent fibers have started.
A Ref is a cell, not a value, but it has no identity-based Equal: Equal.equals falls back to its structural rule for ordinary class instances, so two distinct refs holding equal contents compare equal and collapse into one HashMap key or HashSet member. Because Equal caches each pair's result and Hash caches each object's hash, a comparison made before a ref changes keeps its old answer afterwards. Do not use a Ref as a structural key or compare refs with Equal.equals: compare what they hold with Ref.get, and key by identity with a native Map / Set or ===.
Migration: Some earlier releases gave Ref and MutableRef identity equality. Code that relied on that — refs as HashMap keys or HashSet members, or Equal.equals(refA, refB) as a "same cell" test — now merges distinct refs with equal contents; switch to a native Map / Set keyed by the ref, or to ===.
Each Ref operation is atomic; a sequence of them is not.Ref.get followed by Ref.set is two transitions, and any suspension between them — an HRIS call, a log line, a sleep, even Effect.yieldNow — lets every fiber compute its write from the same stale read. Express the whole read-compute-write as one call and pick the call by what you need back:
You need back
Use
Updater shape
Nothing
Ref.update(ref, f)
(a) => a
The new state
Ref.updateAndGet(ref, f)
(a) => a
The previous state
Ref.getAndUpdate(ref, f) / Ref.getAndSet(ref, a)
(a) => a
A value derived from the old state (an id, an approve/deny decision)
Ref.modify(ref, f)
(a) => [result, next]
A change only in some states
Ref.updateSome / Ref.modifySome
return Option.none() to keep the current value
Self-contained source · Type-checked
ts
import { Effect, Ref } from "effect"const lostUpdates = Effect.gen(function*() { const approvedCount = yield* Ref.make(0) // Anti-pattern: two atomic steps with a suspension point between them. const racy = Effect.gen(function*() { const seen = yield* Ref.get(approvedCount) yield* Effect.yieldNow // stands in for any asynchronous work yield* Ref.set(approvedCount, seen + 1) }) yield* Effect.all(Array.from({ length: 5 }, () => racy), { concurrency: "unbounded" }) const afterRacy = yield* Ref.get(approvedCount) // 1 — four approvals were overwritten // One transition per approval: nothing can interleave inside `update`. const counted = yield* Ref.make(0) const safe = Effect.andThen(Effect.yieldNow, Ref.update(counted, (n) => n + 1)) yield* Effect.all(Array.from({ length: 5 }, () => safe), { concurrency: "unbounded" }) const afterSafe = yield* Ref.get(counted) // 5 // `modify` hands back a value computed from the state it replaced. const sequence = yield* Ref.make(7) const raiseId = yield* Ref.modify(sequence, (n) => [`raise-${n}`, n + 1] as const) // "raise-7" return { afterRacy, afterSafe, raiseId }})
Store immutable snapshots. A Ref protects the cell, not the object inside it. For a Map, array, or record, build a new value and install it in one update ((m) => new Map(m).set(dept, bps)); mutating the stored object in place bypasses the atomic transition and changes values other fibers already read.
Updaters are pure, synchronous functions. The moment the next state needs an Effect (a fetch, a decode, a log), move to SynchronizedRef rather than reading, running the effect, and writing back.
A Ref is a handle, not an Effect.yield* ref does not type-check, and the same holds for SynchronizedRef, SubscriptionRef, TxRef, Deferred, Queue, and Fiber handles. Yield the operation on the handle — Ref.get(ref), Deferred.await(deferred), Fiber.join(fiber) — not the handle itself.
To share one cell between separately written parts of a program, make the Ref the implementation of a service and build it once. Ref.make is an Effect, so provisioning is effectful: Layer.effect for an application, Effect.provideServiceEffect for a one-off program or test.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Ref } from "effect"class MeritBudget extends Context.Service<MeritBudget, Ref.Ref<number>>()("app/MeritBudget") { static readonly layer = Layer.effect(MeritBudget, Ref.make(300))}const spend = Effect.fn("spend")(function*(bps: number) { const budget = yield* MeritBudget return yield* Ref.updateAndGet(budget, (remaining) => remaining - bps)})// One cell for the whole program: [285, 270]const shared = Effect.all([spend(15), spend(15)]).pipe(Effect.provide(MeritBudget.layer))// Provided at each use site, `Ref.make` runs twice and the cells are unrelated: [285, 285]const separate = Effect.all([ spend(15).pipe(Effect.provideServiceEffect(MeritBudget, Ref.make(300))), spend(15).pipe(Effect.provideServiceEffect(MeritBudget, Ref.make(300)))])
Provide the cell once, at the edge that owns its lifetime, exactly like any other Layer; wrapping the Ref in a narrower service interface (spend, remaining) keeps callers from writing arbitrary values.
Use when multiple fibers share mutable state (counters, caches, toggles).
A separate reference type whose update operations are serialised even when the update is an Effect. It pairs a backing Ref with an internal Semaphore (single permit) so only one transition is in flight at a time. The API mirrors Ref and adds *Effect variants: updateEffect, modifyEffect, getAndUpdateEffect, updateSomeEffect, modifySomeEffect, etc.
Note:SynchronizedRef is not a subtype of Ref, so Ref.get(syncRef) and the other Ref.* combinators reject it at compile time. Call the SynchronizedRef.* function of the same name instead.
Self-contained source · Type-checked
ts
import { Effect, SynchronizedRef } from "effect"// Load comp bands from the HRIS once, then serve from cache.// On a refresh signal, any single fiber re-fetches; others wait for the result.interface CompBand { level: string; min: number; mid: number; max: number }type CompBandCache = ReadonlyArray<CompBand> | nullconst makeCompBandCache = Effect.fn("makeCompBandCache")(function*( fetchBands: Effect.Effect<ReadonlyArray<CompBand>>) { const cache = yield* SynchronizedRef.make<CompBandCache>(null) const get = Effect.fn("get")(function*() { // modifyEffect serialises access — no thundering herd on the HRIS return yield* SynchronizedRef.modifyEffect( cache, (current) => Effect.gen(function*() { if (current !== null) return [current, current] as const // Only ONE fiber will ever run this fetch at a time; // every other fiber that arrives during the fetch will wait, // then receive the already-populated cache on the next turn. const bands = yield* fetchBands return [bands, bands] as const }) ) }) const refresh = Effect.fn("refresh")(function*() { yield* SynchronizedRef.updateEffect(cache, () => Effect.map(fetchBands, (bands) => bands) ) }) return { get, refresh }})
The semaphore is held for the entire duration of the Effect inside updateEffect. If the updater performs a slow async call, other fibers queue and wait. This serialisation prevents two fibers simultaneously deciding "cache is empty, I'll fetch" and firing duplicate requests. For fast atomic swaps on pure values, prefer plain Ref.
Semantics worth knowing before you rely on it:
Every write takes the permit, reads never do.set, update, and modify queue behind an in-flight updateEffect; SynchronizedRef.get returns immediately with the last committed value, so a reader never blocks on a slow refresh and never sees a half-finished transition.
The new value is stored only if the updater succeeds. A failing or interrupted updater leaves the previous value in place, which is what makes "fetch, then install" safe to retry.
The permit is not reentrant. Writing to the same SynchronizedRef from inside its own updater waits for a permit the fiber already holds and never completes; read with get inside the updater, or return the final value from it.
*Some* variants can skip the write. The updater given to updateSomeEffect produces Option<A>, and the one given to modifySomeEffect produces [B, Option<A>]; Option.none() keeps the current value. Both have the usual data-first and pipeable (ref.pipe(SynchronizedRef.modifySomeEffect(f))) forms.
Use when the next state value depends on an asynchronous computation and transitions must be serialized: load-once caches, OAuth token refresh, connection pooling, lazy config loading, circuit-breaker state transitions. Serialization prevents overlapping updaters; it does not by itself make an external side effect exactly once across interruption or retry.
A serialised reference that can also be observed as a Stream. It is its own type — not a subtype of Ref or SynchronizedRef — with the same operation names (get, set, update, modify, the *Effect and *Some* variants). Every state change is published to an internal unbounded PubSub with replay: 1, and SubscriptionRef.changes(ref) returns a Stream<A> over it: a subscriber receives the value current at the moment it subscribes, then every later update. Writes hold a single-permit semaphore while they store and publish, so no update is lost between the two.
Self-contained source · Type-checked
ts
import { Deferred, Effect, Fiber, Stream, SubscriptionRef } from "effect"// Live headcount ref: write on every hire/departure, stream to dashboardsconst headcountDashboard = Effect.gen(function*() { type Headcount = { total: number; byDepartment: Record<string, number> } const headcount = yield* SubscriptionRef.make<Headcount>({ total: 0, byDepartment: {} }) const subscribed = yield* Deferred.make<void>() // A fiber that streams every headcount change to a dashboard sink const watcher = yield* SubscriptionRef.changes(headcount).pipe( Stream.tap((hc) => Effect.andThen( Effect.log(`Headcount updated: total=${hc.total}`), Deferred.succeed(subscribed, undefined) // first element = subscription is live ) ), // Initial value plus the two updates below; a bare changes stream is live // forever, so joining it without a bound would never complete. Stream.take(3), Stream.runDrain, Effect.forkScoped ) // A forked fiber has not run yet. Without this gate both updates could land // before the watcher subscribes; it would then see only the latest value and // `take(3)` would wait forever. yield* Deferred.await(subscribed) // Approve a new hire in Engineering — all subscribers see the update yield* SubscriptionRef.update(headcount, (hc) => ({ total: hc.total + 1, byDepartment: { ...hc.byDepartment, Engineering: (hc.byDepartment["Engineering"] ?? 0) + 1 } })) // A departure in Sales yield* SubscriptionRef.update(headcount, (hc) => ({ total: hc.total - 1, byDepartment: { ...hc.byDepartment, Sales: (hc.byDepartment["Sales"] ?? 0) - 1 } })) yield* Fiber.join(watcher)})
Tip: Each call to SubscriptionRef.changes creates a new independent subscriber to the underlying PubSub. Two calls yield two streams both receiving the same updates. Unsubscribing (finishing or interrupting the stream) is automatic.
Warning:changes replays the latest value, not history. A subscriber that starts after three updates receives one element (the current state) and then waits for the next change, so never size a Stream.take(n) by counting writes that may precede the subscription. Treat the stream as "current state, then deltas", and bound it with a condition (Stream.takeUntil) or the consumer's scope.
SubscriptionRef is a decoupling tool: the writer is typed against the ref, every reader against Stream<A> only. Put the ref inside a service, export changes plus the few transitions you allow, and no consumer can write state or even learn that a SubscriptionRef exists.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Stream, SubscriptionRef } from "effect"type CycleStatus = "planning" | "approvals" | "frozen"class MeritCycleStatus extends Context.Service<MeritCycleStatus, { readonly current: Effect.Effect<CycleStatus> readonly changes: Stream.Stream<CycleStatus> readonly advance: (next: CycleStatus) => Effect.Effect<void>}>()("app/MeritCycleStatus") { static readonly layer = Layer.effect( MeritCycleStatus, Effect.gen(function*() { const ref = yield* SubscriptionRef.make<CycleStatus>("planning") return { current: SubscriptionRef.get(ref), changes: SubscriptionRef.changes(ref), advance: (next: CycleStatus) => SubscriptionRef.set(ref, next) } }) )}// A dashboard only knows about a Stream. One that starts during "planning" collects// ["planning", "approvals", "frozen"]; one that joins during "approvals" collects// ["approvals", "frozen"].const untilFrozen = Effect.gen(function*() { const status = yield* MeritCycleStatus return yield* status.changes.pipe( Stream.takeUntil((s) => s === "frozen"), Stream.runCollect )})
Use when shared state must be subscribed to reactively: live data feeds for dashboards, feature flags driving live reconfiguration, status machines, or bridging Effect state into a streaming pipeline. For a transactional equivalent see TxSubscriptionRef; for fan-out of events rather than state, use PubSub.
Concurrency boundary: JavaScript fibers do not interleave inside a synchronous, non-suspending operation. A pure MutableRef.update is therefore atomic with respect to other fibers, just like the synchronous transition inside Ref.update. A read–suspend–write sequence can lose updates with either type. Mutable* APIs are eager and do not serialize effectful protocols or protect aliased mutable values. Prefer Ref for lazy, composable shared-state operations, SynchronizedRef for effectful transitions, and encapsulated Mutable* values for synchronous algorithms.
A tiny synchronous mutable box. Exposes a .current field for direct read/write plus a pipeable API: get, set, update, compareAndSet, numeric helpers increment/decrement, and toggle for booleans. No Effects, no fiber scheduler involvement. This is the backing store for Ref — Ref allocates a MutableRef internally. Like Ref, a MutableRef has no identity-based Equal: two boxes holding equal values compare equal under Equal.equals, and the cached result does not follow later writes, so never use one as a structural key.
Self-contained source · Type-checked
ts
import { MutableRef } from "effect"// Accumulate per-department raise totals in a tight synchronous loop —// no Effect allocation overhead, no fiber involvement.interface DeptSummary { raises: number; totalBps: number }function tallyRaises( recommendations: ReadonlyArray<{ department: string; bps: number; approved: boolean }>): DeptSummary { const approvedCount = MutableRef.make(0) const totalBps = MutableRef.make(0) for (const rec of recommendations) { if (!rec.approved) continue MutableRef.increment(approvedCount) MutableRef.update(totalBps, (n) => n + rec.bps) } return { raises: MutableRef.get(approvedCount), totalBps: MutableRef.get(totalBps) }}// compareAndSet: claim "first to process this merit cycle" in a single fiberconst processed = MutableRef.make(false)const claimed = MutableRef.compareAndSet(processed, false, true)// claimed === true if this fiber is first; false if already claimed
Use inside a synchronous, single-fiber algorithm when the pipeable Effect style is wanted without any Effect overhead.
A mutable linked-list-of-buckets optimised for high-throughput append/prepend and front-draining. Uses chunked arrays (buckets) internally: append is amortised O(1), batch takes are nearly free. Tracks .length. Supports append, prepend, take, takeN, takeAll, appendAll, prependAll, filter, remove, clear. take returns the special MutableList.Empty symbol (not null or undefined) when the list is empty. There is no modify — filter(list, predicate) prunes in place, and toArray / toArrayN copy without draining. Counts passed to takeN / toArrayN are normalised: a fractional count is floored, and NaN or a non-positive count takes nothing. appendAll and prependAll copy the values they receive, so later changes to the caller's array do not reach the list. This is the buffer Effect itself uses inside Queue and PubSub.
Self-contained source · Type-checked
ts
import { MutableList } from "effect"interface RaiseRecommendation { employeeId: string department: string bps: number}// Build up approved raise recommendations for a department in a tight loop,// then flush the whole batch to the payroll client in one shot.function collectApprovedRaises( recommendations: ReadonlyArray<RaiseRecommendation>, targetDept: string): ReadonlyArray<RaiseRecommendation> { const approved = MutableList.make<RaiseRecommendation>() for (const rec of recommendations) { if (rec.department === targetDept && rec.bps > 0) { MutableList.append(approved, rec) } } // takeAll drains the list in one shot — returns the internal array directly // when possible, avoiding a copy return MutableList.takeAll(approved)}// Chunk-process a large raise list — drain 50 at a time to batch-writeconst pending = MutableList.make<RaiseRecommendation>()// ... append all recommendations ...while (pending.length > 0) { const batch = MutableList.takeN(pending, 50) // hand batch to PayrollClient.submitRaises(batch) ...}
Use for an efficient, growable, front-drainable queue inside a single-fiber context.
An in-place mutable key/value map supporting both JS reference equality and Effect structural equality (for keys implementing Equal/Hash). Internally layers a native Map for ordinary keys with hash-bucket collision chains for structural keys. Is Iterable<[K, V]>.
modify(map, key, f) takes f: (v: V) => V and is a no-op when the key is absent. modifyAt(map, key, f) takes f: (Option<V>) => Option<V>: return Option.none() to delete, Option.some(newValue) to insert or update — handles upsert, increment, and conditional delete in one pass.
Self-contained source · Type-checked
ts
import { MutableHashMap, Option } from "effect"// Per-department raise tally: accumulate total approved bps by department// in a tight single-fiber loop across all raise recommendations.interface DeptTally { count: number; totalBps: number }function tallyByDepartment( recommendations: ReadonlyArray<{ department: string; bps: number }>): MutableHashMap.MutableHashMap<string, DeptTally> { const tally = MutableHashMap.empty<string, DeptTally>() for (const rec of recommendations) { // modifyAt handles both "first rec for dept" (None) and "subsequent" (Some) MutableHashMap.modifyAt(tally, rec.department, (current) => Option.some( Option.match(current, { onNone: () => ({ count: 1, totalBps: rec.bps }), onSome: (existing) => ({ count: existing.count + 1, totalBps: existing.totalBps + rec.bps }) }) ) ) } return tally}const recs = [ { department: "Engineering", bps: 150 }, { department: "Sales", bps: 200 }, { department: "Engineering", bps: 100 }]const result = tallyByDepartment(recs)for (const [dept, summary] of result) { console.log(`${dept}: ${summary.count} raises, ${summary.totalBps} bps total`)}// Engineering: 2 raises, 250 bps total// Sales: 1 raises, 200 bps total
Tip:modifyAt(map, key, f) passes Option.none() when the key is absent and Option.some(current) when present. Return Option.none() to delete the key, or Option.some(newValue) to insert or update. This is the single function that handles upsert, increment, and conditional delete in one pass. modify(map, key, f) is the simpler sibling — it takes f: (v: V) => V and is a no-op when the key is absent, so use it only when you know the key exists.
Use for a fast mutable accumulator map inside a single-fiber context: tallying per-key counts, building adjacency lists, grouping data during pipeline steps.
A mutable set built on MutableHashMap — each element is a map key pointing to true. Supports structural equality via Equal/Hash: elements are deduplicated by value, not reference. Is Iterable<V>. Supports add, has, remove, size, clear, make, fromIterable, empty.
Self-contained source · Type-checked
ts
import { MutableHashSet } from "effect"// Walk the approval chain for a raise recommendation, collecting each// approver's employee ID exactly once (cycles in the org graph are safe).function collectApprovalChain( reportsTo: ReadonlyMap<string, string>, // employeeId -> managerId startEmployeeId: string): ReadonlyArray<string> { const visited = MutableHashSet.empty<string>() const queue = [startEmployeeId] while (queue.length > 0) { const id = queue.pop()! if (MutableHashSet.has(visited, id)) continue MutableHashSet.add(visited, id) const managerId = reportsTo.get(id) if (managerId !== undefined) queue.push(managerId) } return Array.from(visited)}// Deduplicate employee IDs from a bulk-import event feed// (the HRIS sometimes emits duplicate change events for the same person).function deduplicateEmployeeIds( events: ReadonlyArray<{ employeeId: string; type: string }>): ReadonlyArray<string> { const seen = MutableHashSet.empty<string>() for (const ev of events) { MutableHashSet.add(seen, ev.employeeId) } return Array.from(seen)}
Use for fast deduplicated membership tracking inside a synchronous algorithm: visited sets during graph traversal, deduplication of IDs during bulk imports.
For a set that is shared across fibers, stored in a Ref, or returned from a function, use the immutable HashSet instead: every change produces a new value, so nobody observes a half-built set.
Official guide: HashSet (documents the immutable and mutable variants side by side).
Load-once comp band cache, HRIS refresh, state machines with async transitions
SubscriptionRef
Pure or effectful, serialised + published
Yes
Yes (changes)
Live headcount feed, reactive merit-cycle status, anything that drives a Stream
MutableRef
Synchronous, in-place
No
No
Single-fiber raise tallies, counters and flags in tight loops
MutableList
Synchronous, in-place
No
No
Raise recommendation batches, BFS of org hierarchy
MutableHashMap
Synchronous, in-place
No
No
Per-department raise tallies, comp band grouping, adjacency lists
MutableHashSet
Synchronous, in-place
No
No
Visited sets for org traversal, employee ID deduplication
Rule of thumb: Start with Ref for shared state in an Effect program; move to SynchronizedRef when the update itself is effectful, to SubscriptionRef when consumers need a stream, and to a Mutable* type for an encapsulated synchronous algorithm. None of these makes an arbitrary sequence of separate reads and writes atomic.
Stream<A, E, R> is a pull-based source: the consumer requests the next chunk, the stream computes it (possibly failing with E, needing services R), emits the chunk, and waits. This pull loop provides automatic back-pressure. Sink<A, In, L, E, R> folds chunks into a final answer. Channel is the bidirectional primitive both are built from. In practice: live in Stream 95% of the time; reach for Channel only when authoring a new operator.
Official examples: Effect's release-matched ai-docs Stream examples cover creation, transformation, consumption, and NDJSON encoding.
Official guides:Introduction to Streams, Sink introduction; section-specific guides are linked where they apply. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
A stream runs on demand: the sink pulls, and each operator pulls from its source. A push source needs a buffer between itself and that demand, with an explicit capacity and overflow strategy.
Stream<A, E, R> is a lazy, pull-based, possibly-infinite sequence of As that can fail with E and needs services R. Pulling provides automatic back-pressure and supports constant-memory pipelines when each stage keeps bounded state. Collecting, unbounded grouping/buffering, or letting producers outrun consumers can still consume memory proportional to the data. Combinators cover three operations — create, transform, run — and the later subsections cover combining streams, failure handling, resource ownership, and where buffering hides.
NodeStream.fromReadable from @effect/platform-node
Schedule outputs
fromSchedule
Manual seed-and-step
unfold
Counters / timers
range / iterate / tick
Async iterator cancellation has a host boundary.fromAsyncIterable calls the iterator's return() on early scope closure. If next() is still pending, it does not await that return: an async generator's own finally may not run until the pending pull settles. Stream.timeout / timeoutOrElse can therefore finish without hanging on an unresolved pull, but cannot force an arbitrary JavaScript Promise to settle. Make the iterator's underlying I/O independently abortable when cleanup must be prompt.
Self-contained source · Type-checked
ts
import { Array, Cause, Clock, Effect, Option, Queue, Schedule, Schema, Stream } from "effect"// In-memory headcount snapshot — the simplest constructor.const levels = Stream.fromIterable<string>(["IC3", "IC4", "IC5", "M1", "M2"])const bandLiterals = Stream.make("IC3", "IC4", "IC5") // varargs -> Stream<string>// Poll the HRIS health endpoint on a schedule.// (v4 name: fromEffectSchedule, NOT repeatEffectWith.)const hrisHeartbeat = Stream.fromEffectSchedule( Clock.currentTimeMillis.pipe( Effect.map((ts) => ({ status: "ok", ts })) ), Schedule.spaced("30 seconds"))// Walk the HRIS's cursor-paginated /employees endpoint.// paginate(initialCursor, f) where f returns [thisPage, Option<nextCursor>].const allEmployees = Stream.paginate( 0, // start at page 0 Effect.fn(function*(page: number) { yield* Effect.sleep("50 millis") // simulate network round-trip const rows = Array.range(0, 99).map((i) => ({ id: `emp_${page * 100 + i}`, name: `Employee ${page * 100 + i}`, level: "IC4" })) const next = page < 10 ? Option.some(page + 1) : Option.none() return [rows, next] as const }))// Any callback/event API: the Queue is the whole protocol — offer values,// end it to finish, fail it to fail the stream.class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { cause: Schema.Defect()}) {}const PayrollEvent = Schema.Struct({ runId: Schema.String, status: Schema.String })const decodePayrollEvent = Schema.decodeUnknownOption(Schema.fromJsonString(PayrollEvent))// Bridge a WebSocket that streams live payroll-run events into a typed Stream.const payrollEvents = Stream.callback<typeof PayrollEvent.Type, HrisUnavailable>( Effect.fn(function*(queue) { const ws = new WebSocket("wss://hris.example.com/payroll-events") const onMessage = (e: MessageEvent) => { // Decode at the boundary instead of casting JSON.parse output. const event = decodePayrollEvent(e.data) // A listener cannot wait, so it cannot use the suspending Queue.offer. if (Option.isSome(event)) Queue.offerUnsafe(queue, event.value) } const onClose = () => Queue.endUnsafe(queue) // buffered events drain, then the stream ends const onError = (cause: Event) => Queue.failCauseUnsafe(queue, Cause.fail(new HrisUnavailable({ cause }))) // The callback effect runs in the stream's scope: this release runs when the // consumer finishes, fails, stops early, or is interrupted. yield* Effect.acquireRelease( Effect.sync(() => { ws.addEventListener("message", onMessage) ws.addEventListener("close", onClose) ws.addEventListener("error", onError) }), () => Effect.sync(() => { ws.removeEventListener("message", onMessage) ws.removeEventListener("close", onClose) ws.removeEventListener("error", onError) ws.close() }) ) }), // Without bufferSize the buffer is UNBOUNDED. Status events supersede each // other, so keep the newest 256 and evict the oldest under pressure. { bufferSize: 256, strategy: "sliding" })
Warning:Stream.callback (and Stream.fromEventListener, which is built on it) buffers without bound unless you pass bufferSize: a fast emitter plus a slow consumer grows the heap silently. The strategy defaults to "suspend", but suspension only helps a producer that can yield* Queue.offer(...). A synchronous listener calls Queue.offerUnsafe, which never waits and returns a boolean instead.
strategy
offerUnsafe on a full buffer
What is lost
"suspend" (default)
returns false; the value is not enqueued
the newest value — silently, unless the listener checks the boolean
"dropping"
returns false; the value is not enqueued
the newest value — the stated policy
"sliding"
returns true; evicts the oldest buffered value
the oldest value
For a push source the real choices are a stated loss policy ("dropping" or "sliding", ideally with a counter on every false), pausing the source externally, or restructuring so the producer is an Effect that awaits a bounded Queue and the stream is Stream.fromQueue. "No loss" together with "the producer cannot slow down" needs durable storage, not a bigger buffer. fromEventListener accepts bufferSize but no strategy, so a full buffer drops the newest events; with { once: true } it ends the stream after the first event. Queue and PubSub overload semantics are covered in Concurrency & Coordination.
unfold vs paginate. The unfold step is always effectful and returns [element, nextState], or undefined to stop — exactly one element per step. paginate returns a whole page plus Option<nextState> and still emits the last page when the next state is None, which is why it fits page-shaped APIs. There is no unfoldEffect or paginateEffect.
Ending a repeated effect.Stream.fromEffectRepeat(effect) re-runs an effect forever, one element per run. Fail it with Cause.done() to end the stream normally — the way to drain an imperative iterator or cursor without carrying unfold state (see Pull for the Done signal).
Self-contained source · Type-checked
ts
import { Cause, Effect, Stream } from "effect"// Drain any iterator lazily: one `next()` per pull, normal end on `done`.const drainIterator = <A>(iterator: Iterator<A>): Stream.Stream<A> => Stream.fromEffectRepeat( Effect.suspend(() => { const next = iterator.next() return next.done ? Cause.done() : Effect.succeed(next.value) }) )
Official guide: Creating Streams (its callback example passes no buffer options, and its "void" heading is not an API — use Stream.succeed(undefined)).
as(value) replaces every element with a constant. filterMap takes a Filter (returns a Result), not an Option-returning function.
Per element, effectful
mapEffect / tap
mapEffect accepts { concurrency, unordered }; ordered output is the default.
Fan out per element
flatMap / switchMap / flattenIterable
flatMap runs every inner stream to completion. switchMap interrupts the previous inner stream when the outer emits again — stale work is cancelled, not queued. flattenIterable is the inverse of grouped.
Carry state
scan / mapAccum (scanEffect, mapAccumEffect)
scan(() => initial, f) emits the seed and every intermediate value — for an empty stream, just the seed is emitted. Its seed (and scanEffect's) is a thunk, like mapAccum's. mapAccum(() => initial, (state, a) => [next, outputs]) returns an array of outputs, so one input can emit zero, one, or many; { onHalt } flushes leftover state at the end. Both keep one caller-supplied accumulator; memory is bounded only if that accumulator is bounded.
takeWhile stops before the first failing element; takeUntilincludes the element that matched unless { excludeLast: true }. takeRight(n) must see the end, so it buffers n and never emits on an infinite source. haltWhen(effect) stops before the next pull; interruptWhen(effect) also interrupts the pull in progress.
grouped flushes only when n elements arrived or the stream ended. groupedWithin flushes on size or elapsed time, whichever is first — the right shape for live feeds. Its window starts with the first element of a batch: idle time before that element is excluded, but silence after a partial batch starts still advances its timer. For schedule-driven aggregation, schedule exhaustion can drain already-pulled leftovers into further batches without more upstream pulls. rechunk resizes the internal chunks without changing the element type.
throttle is a token bucket charged per chunk via cost(chunk): "shape" delays, "enforce" drops the whole over-budget chunk (rechunk(1) first for per-element dropping), burst raises the bucket to units + burst. debounce emits only the last value after a quiet period. schedule spaces every element by a Schedule.
Keyed sub-streams
groupByKey(f) / groupBy
Emits [key, Stream] pairs; consume them with flatMap(..., { concurrency: "unbounded" }) or a finite bound. Each key owns a queue (bufferSize, default 4096 elements); idleTimeToLive retires quiet keys, which matters when the key space is large. If a substream consumer stops early, the underlying queue is shut down so the source is not left hanging; when the upstream ends or fails, every open group ends too.
Dedupe
changes
Drops consecutive elements that are Equal.equals.
Runs of equal keys
groupAdjacentBy(f)
Emits [key, NonEmptyArray] for each run of consecutive elements whose keys are Equal.equals; a later run with the same key is a separate group. It holds only the current run, and when upstream fails the run in progress is emitted before the error.
Text framing
decodeText / splitLines / encodeText
decodeText decodes incrementally, so a multi-byte character may straddle chunks; on normal completion an incomplete trailing character becomes U+FFFD (Channel.decodeText(encoding, { fatal: true }) turns it into a defect instead). splitLines accepts \n, \r\n, and a lone \r, and carries an incomplete line to the next pull.
Shape the output
drain / intersperse
drain keeps a stream's effects but emits nothing, so it can be merged in as a background side-stream. intersperse inserts a separator between elements.
Fragment · Type-checked
ts
import { Effect, Stream } from "effect"interface Employee { readonly id: string readonly level: string readonly baseSalary: number readonly active: boolean}interface CompBand { readonly level: string readonly min: number readonly mid: number readonly max: number}declare const lookupCompBand: (level: string) => Effect.Effect<CompBand>// Process a payroll batch: filter active employees, enrich with comp bands,// throttle to avoid hammering the CompService, then batch for bulk writes.const payrollBatch = (employees: Stream.Stream<Employee>) => employees.pipe( // pure filter: active headcount only Stream.filter((e) => e.active), // pure transform: tag employees outside their band Stream.map((e) => ({ ...e, flagged: false as boolean })), // effectful enrichment with bounded concurrency (v4 sweet spot: one operator, one option) Stream.mapEffect( Effect.fn("enrichWithBand")(function*(e) { const band = yield* lookupCompBand(e.level) const inBand = e.baseSalary >= band.min && e.baseSalary <= band.max return { ...e, band, flagged: !inBand } }), { concurrency: 8 } ), // rate-limit: charge 1 unit per element, cap at 100/second, shape (don't drop) Stream.throttle({ cost: (chunk) => chunk.length, units: 100, duration: "1 second", strategy: "shape" }), // batch into arrays of up to 200 for a bulk DB upsert Stream.grouped(200) )
Tip:mapEffect, flatMap, and mergeAll all accept { concurrency: n } or { concurrency: "unbounded" }, but only mapEffect has unordered: its output keeps input order unless { unordered: true } is passed. flatMap and mergeAll take { concurrency, bufferSize }; above a concurrency of 1 their inner streams interleave as elements arrive, and there is no flag to restore a cross-stream order. In-flight fibers are interrupted when downstream stops pulling.
Ordered does not mean serialized. Ordered mapEffect with concurrency: 8 still runs eight effects at once and only emits in input order, so a slow head element holds back finished successors. Choose unordered: true when downstream does not care, and serialize only the stage whose order is contractual.
Batch by size or time on live sources. A partial grouped(n) batch waits for more input indefinitely, so on a queue- or socket-backed stream latency becomes unbounded. groupedWithin(n, duration) is aggregateWithin(Sink.take(n), Schedule.spaced(duration)) underneath; reach for Stream.aggregateWithin directly when the batch boundary is a custom Sink.
Fragment · Type-checked
ts
import { Stream } from "effect"declare const auditEvents: Stream.Stream<{ readonly id: string }>// Flush at 200 events or after 2 seconds of accumulation, whichever is first.const auditBatches = auditEvents.pipe(Stream.groupedWithin(200, "2 seconds"))
Official guide: Stream operations (its "mergeWith" heading and the switch option it mentions for flatMap are not current APIs — use Stream.merge over mapped inputs and Stream.switchMap).
Gathers all elements into an array (bounded streams only).
runDrain
Executes for effects, discards output.
runForEach
Runs an effect per element. runForEachArray runs it once per pulled chunk.
runForEachWhile
Runs an Effect<boolean> per element and stops pulling on the first false. v4 has no early-exit fold, so this plus local state is the replacement.
runFold
Reduces to one value; the initial state is a thunk. runFoldEffect for an effectful step.
runHead / runLast / runCount / runSum
One-value shortcuts. runHead stops after the first element; the other three consume the whole stream.
mkString / mkUint8Array / mkArrayBuffer
Concatenate a text or byte stream into one value — a full materialization, like runCollect.
run(sink)
Hands the stream to an arbitrary Sink.
Fragment · Type-checked
ts
import { Effect, Sink, Stream } from "effect"interface RaiseRecommendation { readonly employeeId: string readonly newSalary: number readonly approved: boolean}declare const recommendations: Stream.Stream<RaiseRecommendation>declare const persistRaise: (r: RaiseRecommendation) => Effect.Effect<void>const program = Effect.gen(function*() { // collect — bounded only; use for small review batches const allRaises = yield* Stream.runCollect(recommendations) // drain — run for side effects, discard output yield* recommendations.pipe( Stream.tap((r) => Effect.logInfo(`processing raise for ${r.employeeId}`)), Stream.runDrain ) // fold — reduce approved raises to a total payroll delta const totalDelta = yield* recommendations.pipe( Stream.filter((r) => r.approved), Stream.runFold(() => 0, (acc, r) => acc + r.newSalary) ) // run into a Sink — the general escape hatch const approvedCount = yield* recommendations.pipe( Stream.filter((r) => r.approved), Stream.run(Sink.count) ) return { totalRaises: allRaises.length, totalDelta, approvedCount }})
Limit demand, not the result.Stream.take(n) placed before the runner stops pulling after n elements and finalizes the source. runCollect followed by slice(0, n) has already drained the source — and never returns for a live one. Against a six-row counting source, take(2) before runCollect performs 2 reads; runCollect followed by slice(0, 2) performs all 7 (six rows plus the read that discovers the end). The finalizer runs once either way, so only a read counter tells the two apart.
Fragment · Type-checked
ts
import { Effect, Stream } from "effect"declare const employeeIds: Stream.Stream<string> // live HRIS feed: never ends on its owndeclare const loadProfile: (id: string) => Effect.Effect<{ readonly id: string }>// Demand-limited: ten ids pass `take`, so exactly ten profiles are loaded.const firstTen = employeeIds.pipe( Stream.take(10), Stream.mapEffect(loadProfile, { concurrency: 4 }), Stream.runCollect)// Same ten results, but take sits AFTER the concurrent stage: its window stays// full, so extra lookups have already started when the tenth result arrives.// They are interrupted, but the HRIS has already seen the requests.const overshoots = employeeIds.pipe( Stream.mapEffect(loadProfile, { concurrency: 4 }), Stream.take(10), Stream.runCollect)
Three details keep this honest. Demand is per chunk, not per element: Stream.fromIterable reads up to chunkSize items (default 4096) from a lazy iterable per pull, so take(2) over it still advances the iterator by a whole chunk — pass { chunkSize } or use unfold/paginate when each read is expensive. The deciding element has already been processed: takeUntil, takeWhile, and runForEachWhile see an element before they can stop, so "stop before the budget is exceeded" must test the projected total. take treats NaN and non-positive counts as zero and returns an empty stream.
For byte streams, Stream.limitBytes(limit, onLimitReached) emits chunks until the next one would cross limit (any ByteSize.Input), drops that crossing chunk, and switches to the fallback stream — pass a fallback that is Stream.fail(...) to make an oversized body a typed error, or () => Stream.empty to truncate silently. Stream.mkArrayBuffer collects an ArrayBuffer without losing the concrete backing-buffer type. Web Streams are first-class: Stream.fromReadableStream bridges a browser/WHATWG source, while the Channel layer below also supports writable and transform streams. In Node, NodeStream.fromReadable({ evaluate, onError, closeOnDone? }) lazily evaluates a node:streamReadable, maps its errors into the typed channel, and closes it when done by default; see Platform & Runtime Hosts.
Arrival order; each side keeps its own order. Default haltStrategy is "both": merging a finite stream with an infinite ticker never ends unless you pass "left", "right", or "either".
Pair positionally
zip / zipWith
Ends with the shorter side, so the faster side is back-pressured to the slower one.
Pair with the latest
zipLatest / zipLatestWith
Emits when either side produces, after both have produced once. "Latest" is tracked per pulled chunk, so only the last element of each chunk is paired.
Pair with neighbors
zipWithIndex / zipWithPrevious / zipWithNext
The neighbor is an Option; no manual counter or mapAccum needed.
Alternate deterministically
interleave
Unlike merge, the order does not depend on timing.
Every combination
cross
Re-runs the right stream once per left element — expensive if the right side does I/O.
Two branches by a rule
partition(filter) / partitionEffect(filter)
Returns a scoped Effect of two queue-backed streams. Both yield [passes, fails] (the passing branch first) and take a capacity option: default 16 for partition, 4096 for partitionEffect. Swapped names still type-check when both branches share a type, so double-check the destructuring order against the tuple position, not the variable name. A consumer that stops early shuts down its queue so the other branch and the source are not left hanging.
Same elements to several consumers
broadcastN({ n, capacity }) / broadcast / share
Running one Stream value twice runs its source twice. These run it once behind a PubSub: with the default "suspend" strategy the source advances at most capacity chunks ahead of the slowest consumer. share is the ref-counted variant: upstream starts with the first subscriber and is finalized after the last by default; configured idleTimeToLive retains it until expiry or owner-scope closure.
Fragment · Type-checked
ts
import { Effect, Filter, Stream } from "effect"interface RaiseRequest { readonly employeeId: string readonly percent: number}declare const requests: Stream.Stream<RaiseRequest> // finite: one merit cycledeclare const approve: (request: RaiseRequest) => Effect.Effect<void>declare const escalate: (request: RaiseRequest) => Effect.Effect<void>// A progress ticker must not keep the merged stream alive after the data ends.const withProgressTicks = Stream.merge( requests.pipe(Stream.map((request) => ({ _tag: "Request" as const, request }))), Stream.tick("5 seconds").pipe(Stream.map(() => ({ _tag: "Tick" as const }))), { haltStrategy: "left" })const withinPolicy = Filter.fromPredicate((request: RaiseRequest) => request.percent <= 10)const triage = Effect.scoped( Effect.gen(function*() { // The passing branch comes first: [passes, fails]. const [inPolicy, overPolicy] = yield* Stream.partition(requests, withinPolicy, { capacity: 64 }) // Both halves are bounded queues fed by one source: drain them concurrently, // or the branch nobody reads fills up and stalls the other one too. yield* Effect.all( [Stream.runForEach(inPolicy, approve), Stream.runForEach(overPolicy, escalate)], { concurrency: 2, discard: true } ) }))
Use when one pipeline must feed two policies (partition), two independent consumers (broadcastN), or must be joined with a clock, a config feed, or a fallback (merge, zipLatest, concat). For fan-out across fibers that outlive one pipeline, use a PubSub directly.
A stream failure is terminal for the failed region. Recovery never resumes the broken source: it appends a different stream after the elements that were already delivered, so a non-idempotent consumer has already seen them.
Operator
Recovers from
Notes
catch
every typed failure
Removes E; the handler returns the fallback stream.
catchTag / catchTags
tagged failures by _tag
Other failures stay in E. catchTags rejects keys that are not tags of E, as Effect.catchTags does.
catchIf / catchFilter
failures selected by a predicate, refinement, or Filter
Optional trailing orElse for the rest, as on Effect.catchIf.
catchCause / catchCauseFilter
the full Cause, defects included
Use when defects must be handled too.
catchDefect
defects only
Typed failures and interruption pass through untouched — the narrow tool for "a parser threw".
orElseSucceed / orElseIfEmpty
any typed failure / an empty stream
Append one element computed from the error, or switch streams when nothing was emitted.
mapError / mapBoth / orDie
—
Translate the error (mapBoth({ onElement, onError }) maps elements too), or turn it into a defect.
Observation only: run an effect, then re-raise. tapErrorTag and tapDefect mirror their Effect namesakes.
unwrapReason(tag)
—
Replaces a tagged error with its nested reason, so catchTag can target each reason, as Effect.unwrapReason does.
retry(schedule)
typed failures the schedule accepts
Re-runs the entire upstream region, re-acquiring its resources. The schedule resets as soon as the restarted stream emits one element, so upTo({ times: 5 }) means five consecutive failed attempts, not five over the feed's lifetime.
timeout(duration)
—
Ends the stream with no error when one pull waits longer than duration.
timeoutOrElse({ duration, orElse })
—
Switches to orElse() instead: Stream.fail(...) makes silence a typed failure; any other stream is a fallback source.
Fragment · Type-checked
ts
import { Effect, Schedule, Schema, Stream } from "effect"class FeedUnavailable extends Schema.TaggedError<FeedUnavailable>()("FeedUnavailable", { reason: Schema.String}) {}class HeartbeatLost extends Schema.TaggedError<HeartbeatLost>()("HeartbeatLost", {}) {}interface Approval { readonly employeeId: string readonly approved: boolean}declare const liveApprovals: Stream.Stream<Approval, FeedUnavailable>declare const cachedApprovals: Stream.Stream<Approval>const resilientApprovals = liveApprovals.pipe( // Silence is a failure for this feed, not a normal end. Stream.timeoutOrElse({ duration: "30 seconds", orElse: () => Stream.fail(new HeartbeatLost()) }), // Observe and re-raise; onError never recovers. Stream.onError((cause) => Effect.logWarning("live approvals failed", cause)), // Reconnect: re-runs everything above, including the socket acquisition. Stream.retry(Schedule.exponential("1 second").pipe(Schedule.jittered, Schedule.upTo({ times: 5 }))), // Still failing: append the cache. Approvals already emitted stay emitted. Stream.catchTag("FeedUnavailable", () => cachedApprovals))// Stream<Approval, HeartbeatLost>
Warning:Stream.timeout does not behave like Effect.timeout. It is timeoutOrElse with Stream.empty as the fallback, so downstream cannot tell "the source finished" from "the source went quiet". The deadline is an idle timeout per pull, not a total budget — a feed that emits every 30 ms runs forever under timeout("50 millis") — and the fallback stream itself is not timed.
Two placement rules follow from "retry re-runs the upstream region". Place retry directly after the source it should reconnect, upstream of any non-idempotent write — everything above it in the pipe runs again on each attempt (see the streaming deep dive). Put per-element recovery inside the element's effect — Stream.mapEffect((row) => write(row).pipe(Effect.catchTag(...))) keeps the stream alive, whereas a Stream.catch* after it can only replace the rest of the stream. Retry classification and backoff policy are ordinary Schedule material.
Official guide: Error handling in streams (its "timeoutFail", "timeoutFailCause", and "timeoutTo" headings are stale names; the code under them uses Stream.timeoutOrElse).
A file handle, database cursor, or subscription behind a stream must stay open until the consumer stops pulling — and must close on completion, failure, interruption, and early stop. Acquire inside the stream, never before it: a handle opened outside and closed "when the consumer is done" leaks on the first take(n) or decode failure. There is no Stream.acquireRelease; compose Effect.acquireRelease with one of these:
Tool
Shape
Scope lifetime
Stream.unwrap(effect)
an Effect that returns a Stream
The effect's Scope is removed from R and lives as long as the returned stream. The default choice.
Stream.scoped(stream)
a stream whose stages need Scope
Opens a scope for the wrapped stream and closes it when that stream ends.
Stream.ensuring(finalizer) / Stream.onExit(f)
no resource, just cleanup
Runs after the stream's own finalizers on every exit path. An early stop such as take reports a Success exit.
Fragment · Type-checked
ts
import { Cause, Effect, Option, Schema, Stream } from "effect"class ExportUnavailable extends Schema.TaggedError<ExportUnavailable>()("ExportUnavailable", { path: Schema.String}) {}interface PayrollExportCursor { // One read per pull. The reader itself is lazy: None means end of export. readonly nextRow: Effect.Effect<Option.Option<string>, ExportUnavailable> readonly close: Effect.Effect<void>}declare const openPayrollExport: ( path: string) => Effect.Effect<PayrollExportCursor, ExportUnavailable>// The cursor opens on the first pull and closes exactly once: on completion,// on failure, on interruption, and when a consumer stops early with take(n).const payrollExportRows = (path: string): Stream.Stream<string, ExportUnavailable> => Stream.unwrap( Effect.acquireRelease(openPayrollExport(path), (cursor) => cursor.close).pipe( Effect.map((cursor) => Stream.fromEffectRepeat( Effect.flatMap( cursor.nextRow, Option.match({ onNone: () => Cause.done(), onSome: (row) => Effect.succeed(row) }) ) ) ) ) ).pipe(Stream.ensuring(Effect.logInfo("payroll export stream finished")))// Stream.scoped: wrap EVERY stage that uses the handle.declare const openCursor: Effect.Effect<PayrollExportCursor, ExportUnavailable>declare const readAll: (cursor: PayrollExportCursor) => Stream.Stream<string, ExportUnavailable>const scopedRows = Stream.scoped( Stream.fromEffect(Effect.acquireRelease(openCursor, (cursor) => cursor.close)).pipe( Stream.flatMap(readAll) ))
Warning: Scope placement is the whole contract. Stream.scoped(Stream.fromEffect(acquire)).pipe(Stream.flatMap(readAll)) wraps only the one-element stream, so the handle closes as soon as that stream is exhausted. With a sequential flatMap the pull order happens to hide it; with { concurrency: 2 } the release runs before the first row is read.
Two more rules. The reader must itself be lazy: a "stream" over an array produced by reading the whole file only disguises the all-at-once read. Treat explicit completion as end-of-stream, not one successful pull, and never reuse a possible element (or undefined) as an internal "done" sentinel — end with Cause.done(), Option.none(), or the constructor's own protocol. To prove the contract, assert the release flag rather than the values; the streaming deep dive has the three tests.
Pull-based back-pressure bounds a pipeline only if every stage is bounded. Each row is a place where elements wait; peak memory is roughly the sum of capacity × largest item over all of them, and one unbounded row voids the claim.
Stage
What it retains
Default
How to bound it
Stream.callback, Stream.fromEventListener
values pushed but not yet pulled
unbounded
bufferSize (+ strategy on callback)
Stream.fromQueue, Stream.fromPubSub
whatever the queue or subscription holds
the capacity it was built with
construct it bounded / dropping / sliding; see Queue
Stream.buffer({ capacity })
up to capacityelements, plus what is in flight on either side
required; "unbounded" must be spelled out
finite capacity; "suspend" (default) back-pressures, "dropping" / "sliding" lose data
Stream.bufferArray({ capacity })
up to capacitychunks
required
bound is capacity × max chunk size
mapEffect(f, { concurrency })
up to concurrency inputs and results in flight
sequential
finite concurrency; "unbounded" is unbounded memory
flatMap / mergeAll with concurrency above 1
the running inner streams plus one output queue
bufferSize: 16; sequential flatMap has no queue
finite concurrency and bufferSize
grouped(n), groupedWithin(n, d)
the batch under construction
n
choose n from the destination's bulk limit
groupByKey / groupBy
one queue per live key
4096 per key, keys never retired
bufferSize, idleTimeToLive
partition / partitionEffect
two queues
16 / 4096
capacity
broadcast, broadcastN, share
a PubSub
capacity is required
finite capacity; the slowest consumer sets the pace
Buffer capacity is not batch size.Stream.buffer({ capacity: 3 }) sets flow-control depth: the arrays a downstream Sink.forEachArray or runForEachArray receives are whatever happened to be queued — one element at a time behind a slow producer, up to the capacity behind a fast one. Effectful stages reshape chunks too: everything after mapEffect arrives in chunks of one. When the destination needs batches of n, put Stream.grouped(n) (arrays as elements) or Stream.rechunk(n) (chunk size) immediately before the consumer.
buffer also runs ahead of demand.source.pipe(Stream.buffer({ capacity: 64 }), Stream.take(1)) still reads dozens of elements from source; take(1) before the buffer reads one. Place take upstream of buffers and concurrent stages when each read costs something.
Use when you need back-pressured, incrementally-produced data with typed errors and bounded concurrency; choose bounded-state operators when constant-memory behavior matters.
Sink<A, In, L, E, R> consumes elements of type In, may fail with E, needs R, and produces a result A plus unconsumed leftover L. The leftover slot enables early termination without discarding unused elements — two sinks can be sequenced so the second picks up exactly where the first stopped.
Key APIs: Sink.sum, Sink.count, Sink.head(), Sink.last(), Sink.take(n), Sink.fold, Sink.reduce, Sink.forEach, Sink.drain. The collect-all sink is Sink.collect() (function call, not Sink.collectAll).
All but forEachWhile report leftovers (L = In). fold(initial, continueWhile, step) has a lazy seed and an effectful step; reduceWhile is the pure form and also covers size-capped set/map collection; foldUntil(initial, max, step) stops after max inputs.
A sink's error handlers see only the sink's own failures. In Stream.run, Stream.peel, and Stream.aggregate / aggregateWithin, an upstream stream failure reaches the caller unchanged: Sink.mapError, Sink.catch, Sink.catchCause, and Sink.orElse do not remap or recover it, and Sink.onExit observes it as an interruption of the sink. Handle source failures on the stream (Stream.catch*, Stream.retry) before it reaches the sink.
Sink.mapInput adapts the input; Sink.map adapts the result. Write the aggregation once over a primitive and reuse it across streams of different shapes.
Leftovers are the rest of the chunk already pulled — not the rest of the stream. A sink finishes with an End tuple [result, leftover?]. Sink.mapEnd can read and rewrite both halves, Sink.ignoreLeftover narrows L to never, and Sink.flatMap hands the first sink's leftovers to the second, so "parse a header, then fold the body" composes. Because leftovers depend on chunking, Sink.take(3) over Stream.make(1, 2, 3, 4, 5) (one chunk) leaves [4, 5], but over chunks [1, 2], [3, 4], [5] it leaves [4]. Ignoring leftovers never pulls more input.
Sink.takeUntil(predicate) and takeUntilEffect include the matching element, stop there immediately, and return the rest of that chunk as leftovers. They do not consume and drop an extra element after the match; this matters when composing parsers or repeatedly transducing a delimiter-based sink.
Stream.transduce(sink) re-applies a sink as an operator.Stream.run(sink) applies it once; transduce runs it repeatedly, feeds each run's leftovers into the next, and emits every result — this is why L exists. transduce(Sink.take(n)) is fixed-size batching; a Sink.fold whose predicate looks at accumulated cost gives weighted batching (there is no Sink.foldWeighted). Two edges: the element that crosses the limit is already in the batch, and an empty trailing result can be emitted when the input ends on a batch boundary, so filter empties.
Fragment · Type-checked
ts
import { Effect, Sink, Stream } from "effect"interface Raise { readonly employeeId: string readonly delta: number}// One generic sink, adapted to a domain record.const totalRaiseDelta = Sink.sum.pipe(Sink.mapInput((raise: Raise) => raise.delta))// Header row first, then count the body: flatMap passes the leftovers along.const headerThenRowCount = Sink.take<string>(1).pipe( Sink.flatMap(([header]) => Sink.count.pipe(Sink.map((rows) => ({ header, rows })))))// Flush once roughly 1 MiB of UTF-8 row payload has accumulated.// The last row can overshoot the threshold; framing bytes are not counted.const encoder = new TextEncoder()const upToOneMiB = Sink.fold<{ readonly rows: ReadonlyArray<string>; readonly bytes: number }, string>( () => ({ rows: [], bytes: 0 }), (state) => state.bytes < 1_048_576, (state, row) => Effect.succeed({ rows: [...state.rows, row], bytes: state.bytes + encoder.encode(row).byteLength })).pipe(Sink.map((state) => state.rows))declare const exportRows: Stream.Stream<string>const byteWeightedBatches = exportRows.pipe( Stream.transduce(upToOneMiB), Stream.filter((batch) => batch.length > 0))
Sink.forEachArray does not create batches. It receives whatever arrays the stream happens to pull, and neither it nor Stream.buffer({ capacity }) sets a batch size — see Where buffering hides. Put Stream.rechunk(n) (or Stream.grouped(n) with runForEach) directly before it when the destination needs batches of n.
Sink.fromWritableStream({ evaluate, onError }) adapts a WHATWG WritableStream into a back-pressured Sink. Construction is scoped and cancellation/close follows the Sink lifecycle, so use it for browser responses, compression streams, or other host-native writable targets.
Official guides: Creating sinks (its HashSet/HashMap and "foldWeighted" headings are stale; the code folds with Sink.reduce, Sink.reduceWhile, and Sink.fold), Sink operations, Leftovers (its [4, 5] leftover appears only because the input is a single chunk).
Use when the consumption logic is itself a reusable, composable unit — domain aggregations or writers that should be swappable independently of the stream feeding them.
The primitive underlying Stream and Sink. Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env> — emits OutElem, may fail OutErr, finishes with OutDone; accepts upstream InElem that may fail InErr and finish InDone; needs Env. Stream is a channel that only outputs; Sink is a channel that consumes and produces a single done value.
Channels pipe (output of one becomes input of the next), sequence, and concatenate.
Self-contained source · Type-checked
ts
import { Channel } from "effect"// The shape, annotated. Most params default sensibly — a plain source is just// Channel<A>.type EmployeeSource = Channel.Channel<{ id: string; level: string }>// outputs employee objects, never fails, done = voidtype GrantCodec = Channel.Channel< { employeeId: string; shares: number }, // OutElem — decoded grant objects Error, // OutErr — how emission can fail void, // OutDone — terminal value when done Uint8Array, // InElem — raw bytes from upstream Error, // InErr — how upstream can fail unknown, // InDone — upstream's terminal value never // Env — required services>// You consume a channel by running it or, far more often, by wrapping it back// into a Stream — which is exactly what the encoding codecs hand you.const drained = Channel.runDrain(Channel.fromArray([{ id: "e1", level: "IC4" }]))// Efficiently concatenate a channel of byte chunks into one Uint8Array.// Unlike repeated pairwise concatenation, collection is linear.const bytes = Channel.mkUint8Array( Channel.fromArray([ [new Uint8Array([1, 2])], [new Uint8Array([3, 4])] ] as const))
Two details for code that runs channels directly. Channel.runDrain returns the channel's done value (Effect<OutDone, OutErr, Env>); there is no separate Channel.runDone — use runDrain when only the terminal value matters. Channel.catchDefect (and Stream.catchDefect above it) recovers from defects only — typed failures and interruption pass through — which keeps a throwing codec step from taking down a long-lived channel without hiding real cancellation.
The Web Streams interop set is complete at this level: fromReadableStream, fromWritableStream, and fromTransformStream adapt host streams, while pullIntoWritableStream exposes a channel that writes into an existing target. Each constructor takes an explicit host-error mapper so failures stay typed and interruption cancels outstanding I/O.
Note: The common reason to touch Channel directly is Stream.pipeThroughChannel. The Sse, Ndjson, and SchemaBinary modules are channels spliced into stream pipelines via that combinator.
Use when authoring a new stream/sink operator, writing a stateful byte codec, or implementing a genuinely bidirectional protocol. For normal data flow, stay in Stream.
Adapter layer that attaches a Schema to a channel boundary. ChannelSchema.encode(schema)() converts typed values to the schema's encoded form; ChannelSchema.decode(schema, parseOptions?)() validates the inverse, and takes optional SchemaAST.ParseOptions such as { onExcessProperty: "error" } (as does decodeUnknown). duplex wraps a bidirectional channel so callers see typed I/O while the inner channel speaks the wire format.
Schema failures surface as SchemaError in the error channel. Encoding/decoding service requirements propagate as channel requirements. The Ndjson.decodeSchema and Sse.decodeDataSchema helpers stack ChannelSchema.decode internally — typically consumed transitively. SchemaBinary is different: it compiles its own binary layout from the schema instead of validating an already-parsed value.
Fragment · Type-checked
ts
import { ChannelSchema, Schema, Stream } from "effect"// A typed EquityGrant that comes in over the wire in encoded form.const EquityGrant = Schema.Struct({ employeeId: Schema.String, shares: Schema.Natural, grantDate: Schema.String, strikePrice: Schema.Finite})// A channel that validates+decodes encoded EquityGrant chunks into typed grants.// Note the thunk: decode(schema) returns a function you call () to specialize// the input-error / done type params.const decodeGrants = ChannelSchema.decode(EquityGrant)()// Splice it into a stream of already-parsed JSON values to get typed, validated// grants (SchemaError lands in the stream's error channel).declare const rawGrants: Stream.Stream<{ employeeId: string; shares: number; grantDate: string; strikePrice: number }>const grants = rawGrants.pipe(Stream.pipeThroughChannel(decodeGrants))
Use when building a custom typed codec over a channel boundary. For standard wire formats, prefer the *.decodeSchema helpers which wire this up automatically.
Take<A, E, Done> is a reified single-pull result: either a NonEmptyReadonlyArray<A> (a batch), or an Exit that is a failure (E) or successful completion carrying Done. Used to store or transport "what the stream produced in one step" — e.g. bridging a stream through a Queue or PubSub.
Take.toPull converts it back into a live pull step. Paired with Stream.toPubSubTake / fromPubSubTake and Stream.flattenTake to ferry chunks-plus-termination across concurrency primitives intact.
Self-contained source · Type-checked
ts
import { Effect, Exit, Take } from "effect"// A Take carries one pull's worth of news about a merit-cycle approval stream.// It's a NonEmptyReadonlyArray when values arrive, or an Exit when the stream ends/fails.const approvals: Take.Take<{ employeeId: string; approved: boolean }> = [{ employeeId: "e1", approved: true }, { employeeId: "e2", approved: false }]const failed: Take.Take<never, string> = Exit.fail("ReviewServiceUnavailable")const ended: Take.Take<never> = Exit.succeed(undefined) // stream completed// Interpret a stored Take as a live pull step.const step = Take.toPull(approvals)// Pull<NonEmptyReadonlyArray<{ employeeId: string; approved: boolean }>, never, void>const _ = Effect.runSync(step)// [{ employeeId: "e1", approved: true }, { employeeId: "e2", approved: false }]
Use when routing a stream's output through a Queue or PubSub and the end/error signal must be preserved alongside values, or when implementing custom buffering.
Wire codecs: streaming bytes ↔ typed values.
The streaming codecs below live under effect/encoding and are unstable or experimental (API may change; each label line says which). Each is a channel spliced via Stream.pipeThroughChannel. Decode: bytes/text in, typed objects out. Encode: objects in, bytes/text out. The record formats (Ndjson, Sse, Csv, JsonArray) have a plain variant and a *Schema* variant that validates against a Schema at the boundary; Xml streams events, and the archive formats (Tar, Zip) stream entries.
Newline-delimited JSON codecs as channels. Ndjson.decodeString() splits on newlines and JSON.parses each line. Ndjson.decode() takes Uint8Array input: it splits on raw bytes, decodes each line as strict UTF-8, and skips a leading BOM. Both accept \n, \r\n, and a bare \r as line endings. Failures are a tagged NdjsonError with kind: "Pack" (encoding) or "Unpack" (decoding); decoders also set reason ("InvalidJson", "InvalidUtf8", or "LineTooLarge") and unterminated when the bad line is the final line without a terminator. The lines before a bad line are emitted before the channel fails. decodeSchemaString(Schema)() fuses split → parse → validate in one channel.
Self-contained source · Type-checked
ts
import { DateTime, Schema, Stream } from "effect"import { Ndjson } from "effect/encoding"// An equity-grant record exported by the EquityLedger as NDJSON.class EquityGrant extends Schema.Class<EquityGrant>("EquityGrant")({ employeeId: Schema.String, grantDate: Schema.DateTimeUtcFromString, shares: Schema.Natural, strikePrice: Schema.Finite}) {}// Decode a raw NDJSON export of equity grants → validated EquityGrant objects.const decodeGrants = Stream.make( `{"employeeId":"e1","grantDate":"2023-01-15T00:00:00Z","shares":1000,"strikePrice":42.50}\n` + `{"employeeId":"e2","grantDate":"2024-03-01T00:00:00Z","shares":500,"strikePrice":61.00}\n`).pipe( Stream.pipeThroughChannel(Ndjson.decodeSchemaString(EquityGrant)()), Stream.runCollect)// Round-trip: decode NDJSON export → filter recently granted → re-encode to NDJSON.const recentGrants = Stream.make( `{"employeeId":"e1","grantDate":"2023-01-15T00:00:00Z","shares":1000,"strikePrice":42.50}\n` + `{"employeeId":"e2","grantDate":"2024-03-01T00:00:00Z","shares":500,"strikePrice":61.00}\n`).pipe( Stream.pipeThroughChannel(Ndjson.decodeSchemaString(EquityGrant)()), Stream.filter((g) => g.shares >= 750), Stream.pipeThroughChannel(Ndjson.encodeSchemaString(EquityGrant)()), Stream.runCollect)// Build a grant to round-trip through the encoder (DateTime.makeUnsafe accepts ISO strings).const sampleGrant = new EquityGrant({ employeeId: "e3", grantDate: DateTime.makeUnsafe("2025-06-01T00:00:00Z"), shares: 2000, strikePrice: 75.00})
Warning: Blank lines raise NdjsonError by default. Pass { ignoreEmptyLines: true } to any decoder (decode, decodeString, decodeSchema, decodeSchemaString, and the duplex variants) to skip them; a line holding only spaces or tabs counts as blank. Handle failures with Stream.catchTag("NdjsonError", ...).
Both text lines and UTF-8 code points may straddle incoming chunks: the decoder buffers either boundary correctly. You do not need to align network chunks to newlines or character boundaries.
Warning: Lines are unbounded by default: a decoder retains an incomplete line until its terminator arrives, so one newline-free upload is one unbounded allocation. For untrusted bytes, pass maxLineBytes to decode, decodeSchema, duplex, or duplexSchema; a longer line fails with reason: "LineTooLarge" as soon as the limit is passed, without reading the rest of the line. The string decoders have no such option, so cap their input first, for example with Stream.limitBytes(limit, () => Stream.fail(...)) on the byte stream before decoding text.
Use when consuming or producing a streaming JSON HTTP body, tailing a JSON log file, or processing bulk exports line by line.
Server-Sent Events codec. Sse.decode() parses SSE text chunks into Event values with id, event, and data fields. An SSE retry: directive surfaces as a Retry failure in the error channel, making reconnect logic straightforward error handling. Sse.encode() renders Events as SSE wire text. Sse.decodeDataSchema(schema) JSON-decodes the data payload while preserving event name and id. Sse.decodeSchema(schema, options?, parseOptions?) validates the whole { event, data, id? } envelope; the third argument passes Schema parse options.
Self-contained source · Type-checked
ts
import { Schema, Stream } from "effect"import { Sse } from "effect/encoding"// Parse a raw SSE stream of merit-cycle approval events.const approvalEvents = Stream.make( "event: approved\ndata: {\"employeeId\":\"e1\",\"newSalary\":110000}\n\n", "event: rejected\ndata: {\"employeeId\":\"e2\",\"newSalary\":105000}\n\n").pipe( Stream.pipeThroughChannel(Sse.decode()), // A `retry:` directive arrives as a Retry failure — perfect hook for reconnect. Stream.catchTag("Retry", () => Stream.empty), Stream.runCollect)// JSON-decode just the `data` field against a schema, keep id/event metadata.// This models live approval decisions streamed from the ReviewService.const ApprovalDecision = Schema.Struct({ employeeId: Schema.String, newSalary: Schema.Finite})const meritApprovals = Stream.make( `data: {"employeeId":"e1","newSalary":110000}\n\n`, `data: {"employeeId":"e2","newSalary":120000}\n\n`).pipe( // decodeDataSchema decodes the `data` field and preserves the SSE envelope Stream.pipeThroughChannel(Sse.decodeDataSchema(ApprovalDecision)), // e.data is typed as { employeeId: string, newSalary: number } Stream.filter((e) => e.data.newSalary > 100_000), Stream.runCollect)
An omitted or empty event: field decodes as the standard event type "message". Sse.decodeSchema omits the id key when an event carries no ID, so declare it as Schema.optional(Schema.String): a Schema.UndefinedOr(Schema.String) field fails with a missing-key error. Under { onExcessProperty: "error" }, the schema must also declare event (it is always present) and id whenever the stream sends IDs, including IDs inherited from an earlier event.
Fragment · Type-checked
ts
import { Schema, Stream } from "effect"import { Sse } from "effect/encoding"// A strict envelope schema: every key the decoder can produce is declared.const PayrollRunEvent = Schema.Struct({ event: Schema.String, // "message" when the server sends no `event:` id: Schema.optional(Schema.String), // absent IDs are omitted, not `undefined` data: Schema.String})declare const payrollRunFeed: Stream.Stream<string>const runEvents = payrollRunFeed.pipe( Stream.pipeThroughChannel( Sse.decodeSchema(PayrollRunEvent, undefined, { onExcessProperty: "error" }) ))
Decoding limits the pending event to 10 MiB of string code units by default, not UTF-8 bytes; set { maxEventSize } on decode / decodeDataSchema when the protocol needs a different bound, and handle an oversized event as SseError with an EventTooLarge reason. Line endings may be \n, \r\n, or \r, mixed freely within one stream. Encoding also splits all three forms into separate data: lines, so a lone carriage return cannot discard the rest of the payload, and it removes CR and LF from event and id values (and NUL from id), so a caller-supplied event name or ID cannot inject extra fields or events into the stream. Generated HttpApiClient methods accept the same decode options per call as sseOptions.
By default, a named event with no data: line is dropped, as in the WHATWG algorithm. Opt into Sse.decode({ dispatchEmptyNamedEvents: true }) for protocols such as graphql-sse that use event: complete\n\n; it emits { event: "complete", data: "" } (plus any inherited ID). This is distinct from an explicit empty data: line, which already dispatches an empty payload. Long unterminated lines split across chunks are accumulated and joined at the line ending rather than repeatedly rescanned; keep the size limit even with that parsing improvement.
Use when consuming an SSE endpoint for live typed events with built-in reconnect signalling.
Streaming RFC 4180 CSV over text (decodeString / encodeString) or UTF-8 bytes (decode / encode). Cells are strings kept exactly as written; quoted fields may contain delimiters, line breaks, and doubled quotes. Decoders accept LF, CRLF, and CR and strip a leading BOM. With { headers: true } the first record supplies unique field names and every later record becomes an object of the same width; a duplicate header or a row of a different width fails with CsvError (kind: "Header", plus one-based record and line); malformed quoting is kind: "Syntax" with a column. Records completed before the failing one, including those in the same input chunk, are emitted before the CsvError. delimiter is one character (default ","), maxRecordSize bounds one record in UTF-16 code units (default 1 MiB, exceeding it is kind: "RecordSize"; Infinity disables it), and ignoreEmptyLines skips blank records instead of reading them as one empty cell. Invalid options throw when the channel is created.
decodeSchemaString(schema)(options?, parseOptions?) and encodeSchemaString(schema)(options?) wrap the schema in Schema.toCodecStringTree by default, so columns can be Schema.Number, Schema.Boolean, or Schema.Date; with header records, an empty cell for an optional property decodes as a missing key. Pass disableCodecs: true to use the schema exactly as given. The encoder writes "\r\n" after every record unless newline: "\n", takes columns from a struct's encoded keys, and writes them as the first record with headers: true.
Self-contained source · Type-checked
ts
import { Effect, Schema, Stream } from "effect"import { Csv } from "effect/encoding"const PayrollRow = Schema.Struct({ employeeId: Schema.String, salary: Schema.Number, active: Schema.Boolean})const export_ = "employeeId,salary,active\r\ne1,110000,true\r\ne2,95000,false\r\n"// Text → typed rows. Cell conversion comes from Schema.toCodecStringTree.const rows = Stream.make(export_).pipe( Stream.pipeThroughChannel(Csv.decodeSchemaString(PayrollRow)({ headers: true })), Stream.runCollect)// [{ employeeId: "e1", salary: 110000, active: true }, { employeeId: "e2", salary: 95000, active: false }]// Typed rows → CSV text with a header record.const csv = Stream.make({ employeeId: "e3", salary: 120000, active: true }).pipe( Stream.pipeThroughChannel(Csv.encodeSchemaString(PayrollRow)({ headers: true })), Stream.mkString)// "employeeId,salary,active\r\ne3,120000,true\r\n"const program = Effect.all([rows, csv])
A schema failure is a Schema.SchemaError whose path starts at the one-based record number, so [2]["salary"] names the first data row after the header.
Use when importing or exporting spreadsheets and bulk HR/payroll files without buffering the whole file.
Streams the elements of one JSON array — the root, or the array an RFC 6901 pointer selects inside an envelope such as {"items":[...],"total":n} — without buffering the whole document. Each element is buffered only until complete, then JSON.parsed; the rest of the document is validated and discarded. Use Ndjson instead when the producer writes one value per line. (It is unrelated to Schema.JsonArray, the type of a JSON array value.) The encoders write a stream of values as one array; an empty stream encodes as [].
Self-contained source · Type-checked
ts
import { Schema, Stream } from "effect"import { JsonArray } from "effect/encoding"const Employee = Schema.Struct({ id: Schema.String })// Chunks may split an element anywhere; `pointer` selects the nested array.const employees = Stream.make(`{"total":2,"items":[{"id":"e1"},{"i`, `d":"e2"}]}`).pipe( Stream.pipeThroughChannel(JsonArray.decodeSchemaString(Employee)({ pointer: "/items" })), Stream.runCollect)// [{ id: "e1" }, { id: "e2" }]const body = Stream.make({ id: "e1" }, { id: "e2" }).pipe( Stream.pipeThroughChannel(JsonArray.encodeString()), Stream.mkString)// '[{"id":"e1"},{"id":"e2"}]'
Failures are a JsonArrayError with kind"Syntax", "Limit", "Pointer" (missing target, non-array target, or a non-array root without a pointer into it), or "Encode"; decoding errors carry an offset in UTF-16 code units. maxDepth (default 1000) and maxElementSize (default 16 MiB of UTF-16 code units) bound every value, including the ones outside the selected array.
Use when a large HTTP response or file is one JSON document and its items should be processed one at a time.
Streaming XML 1.0 over text (decodeString / encodeString) or UTF-8 bytes (decode / encode). Decoders emit Xml.Events (Declaration, Doctype, StartElement, EndElement, Text, Comment, ProcessingInstruction) and check well-formedness. Xml.elements(path) collects every element at a root-anchored path ("*" matches any name) into a small { name, attributes, children } tree, so a large feed or export is processed one record at a time.
The decoder never reads external resources and never expands entities declared in a DOCTYPE — a reference to one fails with an UnsupportedXmlError — so XXE and entity-expansion attacks do not apply. It does not validate against a DTD or schema and reports names as written, without resolving namespaces. Failures are an XmlError with kind"Syntax", "Unsupported", "Limit", or "InvalidEvent", and decoder errors carry a one-based line and column. Pass { positions: true } to decode / decodeString to put the same line and column of each tag's < on its StartElement event, for diagnostics that point into the source document; the fields are absent by default and the encoders ignore them. maxTokenSize (default 10 MiB), maxDepth (default 1024), and elements' maxElementSize (default 16 MiB) bound memory; lower them for untrusted input.
Use when consuming RSS/Atom feeds, sitemaps, SOAP-era exports, or other XML too large to parse in one piece.
A compact binary codec derived from a Schema rather than from the runtime shape of a value. It replaced the MessagePack codec (Msgpack, RpcSerialization.layerMsgPack, and the msgpackr dependency have been removed), and it is now what EventLog persistence, EventLog remote messages, and TCP cluster transports put on the wire.
The layout is compiled once from the encoded side of the schema, so field names are not repeated per value: an array of structs is written as a row run that declares its shape once and back-references repeated strings. There are two wire modes:
Default — tolerant of compatible schema evolution. Struct fields are identified by a hashed field id, so peers may add optional fields independently. Pin an id with SchemaBinary.fieldId(n) to survive a property rename or to resolve a hash collision.
{ fingerprint: true } — positional layout plus an 8-byte layout hash. Frames are smaller, but both peers must use the same schema definition; a mismatch is rejected instead of being misread.
Fragment · Type-checked
ts
import { Schema, Stream } from "effect"import { SchemaBinary } from "effect/encoding"// Payroll-run telemetry frame: compact binary between internal services.const PayrollFrame = Schema.Struct({ // fieldId pins the wire identity, so renaming `runId` later stays compatible. runId: Schema.String.pipe(SchemaBinary.fieldId(1)), employeeId: Schema.String, grossPay: Schema.Finite, netPay: Schema.Finite})// One value ↔ one frame: toCodec is an ordinary Schema codec to Uint8Array.const codec = SchemaBinary.toCodec(PayrollFrame)const oneFrame = Schema.encodeUnknownSync(codec)({ runId: "run_2025_06", employeeId: "e1", grossPay: 8333.33, netPay: 6100})const roundTripped = Schema.decodeUnknownSync(codec)(oneFrame)// Streams: encode typed frames to bytes for inter-service transport.const packed = Stream.make( { runId: "run_2025_06", employeeId: "e1", grossPay: 8333.33, netPay: 6100.00 }, { runId: "run_2025_06", employeeId: "e2", grossPay: 10000.00, netPay: 7300.00 }).pipe( Stream.pipeThroughChannel(SchemaBinary.encode(PayrollFrame)()), Stream.runCollect // Array<Uint8Array>)// Decode incoming bytes back into typed records. Frames may be split across// chunks or concatenated within one; bound the buffered frame for untrusted peers.declare const binaryFrames: Stream.Stream<Uint8Array<ArrayBuffer>>const payrollFrames = binaryFrames.pipe( Stream.pipeThroughChannel(SchemaBinary.decode(PayrollFrame, { maxFrameSize: 1024 * 1024 })()), Stream.runCollect)
Fixed-width integers. Numbers and bigints use variable-length encodings by default, so small values stay small. SchemaBinary.int32 and uint32 (decoding to number) and int64 and uint64 (decoding to bigint) opt a field into four- or eight-byte little-endian integers, which is smaller for values that regularly need many varint bytes, such as hashes and full-range ids. They reject non-integers and out-of-range values instead of wrapping them. Switching an existing field between these schemas, Schema.Int, and Schema.Number changes its wire encoding: in the default mode the peer may silently decode a different value, while fingerprint mode rejects the mismatched layout.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { SchemaBinary } from "effect/encoding"const AuditRecord = Schema.Struct({ contentHash: SchemaBinary.uint32, // always four bytes on the wire sequence: SchemaBinary.uint64, // a bigint in memory, eight bytes on the wire employeeId: Schema.String})const auditCodec = SchemaBinary.toCodec(AuditRecord)const frame = Schema.encodeUnknownSync(auditCodec)({ contentHash: 0xdeadbeef, sequence: 42n, employeeId: "e1" })
Every failure is a Schema.SchemaError — there is no separate codec error type, and a value that does not match the schema (a string inside a number array, an out-of-range fixed-width integer) fails encoding rather than being coerced. The decoder keeps one frame parser for the life of the channel: values completed before a bad frame are still emitted, and an incomplete trailing frame fails when upstream ends instead of being dropped silently. maxFrameSize is unset by default, so set it whenever the peer is not trusted. SchemaBinary.duplex({ inputSchema, outputSchema }) wraps a bidirectional byte channel the same way Ndjson.duplexSchema does.
Two ownership details matter in practice. Encoded results are arena-backed views that may share a larger buffer, so call bytes.slice() before retaining a frame beyond the current step. And for one long-lived connection, SchemaBinary.encoder(schema, { dictionary: true }) with the matching SchemaBinary.parser(...) shares a string dictionary across frames: repeated strings cost one reference after first use, but frames no longer stand alone and must be decoded in order by the parser that saw the earlier ones.
Warning: Because the layout comes from the schema, the schema is the wire contract. In the default mode, evolve it compatibly (add optional fields, pin ids before renaming). In fingerprint mode, deploy both peers together. Data persisted by a pre-SchemaBinary EventLog journal is MessagePack and is not readable by the SchemaBinary codec.
Use when you need a compact, schema-validated binary frame format over a socket, worker, or file where human readability is not required and both ends share Effect schemas. Prefer Ndjson when the other side is not an Effect program or when frames must be inspectable.
Tip: Every codec is a channel composed the same way: stream.pipe(Stream.pipeThroughChannel(Codec.decode…(MySchema)())). Bytes in, typed objects out — or reverse with the encoder. Ndjson, Sse, Csv, JsonArray, and SchemaBinary are the same shape with different wires.
Archive formats.Tar and Zip are channels from bytes to entries ({ header, body }, where body is a Stream<Uint8Array>) and back. Neither touches the file system, and both share the same consumption rules.
Warning: Read each entry's body while the entry stream is running — typically inside Stream.mapEffect — and before pulling the next entry. Pulling the next entry skips the rest of the current body, a body read afterwards fails with a BodyConsumed error, and every body fails that way once the entry stream has ended (after Stream.runCollect, Stream.take, or Stream.runHead). Operators that pull ahead, such as Stream.buffer, therefore cannot sit between decode and the body reads. Paths come back exactly as archived — they can be absolute or contain .. — so validate them before writing anything to disk.
Tar.decode() reads v7, USTAR, PAX extended headers (including global headers), GNU long names and links, and base-256 numbers; GNU sparse entries fail with an UnsupportedTarError. Tar.encode() writes USTAR, adding a PAX header only for what USTAR cannot hold, and streams bodies without buffering them. Build entries with Tar.file(path, content), Tar.fileStream(path, size, body) (note that size comes before the body), Tar.directory, Tar.symlink, and Tar.hardlink; unset options default to fixed modes, uid/gid 0, and an epoch mtime, so archives are reproducible. It does not compress.
Self-contained source · Type-checked
ts
import { Effect, Stream } from "effect"import { Tar } from "effect/encoding"const archive = Stream.make( Tar.directory("reports/"), Tar.file("reports/q1.csv", "employeeId,salary\ne1,110000\n")).pipe(Stream.pipeThroughChannel(Tar.encode()))// Read each body inside mapEffect, while the entry stream is still running.const listing = archive.pipe( Stream.pipeThroughChannel(Tar.decode()), Stream.mapEffect((entry) => Stream.mkString(Stream.decodeText(entry.body)).pipe( Effect.map((text) => ({ path: entry.header.path, type: entry.header.type, bytes: text.length })) ) ), Stream.runCollect)// [{ path: "reports/", type: "Directory", bytes: 0 }, { path: "reports/q1.csv", type: "File", bytes: 28 }]
A body that produces any byte count other than header.size fails encoding with a SizeMismatchTarError, so a streamed entry's size must be known up front. Other TarError kinds are InvalidHeader, Truncated, Unsupported, and BodyConsumed.
Streaming zip with stored and deflated entries and ZIP64 when sizes, offsets, or counts need it. Zip.decode() reads entries in archive order from their local headers — so an archive can be decoded as it arrives — and checks every body against its CRC-32 and sizes; it never reads the central directory, so mode, comments, and entries only the central directory lists are not reported. Zip.encode() writes each entry as it arrives and the central directory at the end. Build entries with Zip.file(path, content, { method? }) (in memory, default "Deflate"; use "Store" for already-compressed content), Zip.fileStream(path, body, options?), and Zip.directory(path). Compression uses the runtime's CompressionStream("deflate-raw"). Encryption, other methods, and split archives are not supported.
Self-contained source · Type-checked
ts
// @effect-diagnostics experimentalApiUsage:offimport { Effect, Stream } from "effect"import { Zip } from "effect/encoding"const archive = Stream.make( Zip.directory("reports"), // a trailing "/" is added Zip.file("reports/q1.csv", "employeeId,salary\ne1,110000\n")).pipe(Stream.pipeThroughChannel(Zip.encode()))const listing = archive.pipe( Stream.pipeThroughChannel(Zip.decode()), Stream.mapEffect((entry) => Stream.mkString(Stream.decodeText(entry.body)).pipe( Effect.map((text) => `${entry.header.path} (${entry.header.method}): ${text.length} chars`) ) ), Stream.runCollect)// ["reports/ (Store): 0 chars", "reports/q1.csv (Deflate): 28 chars"]
A stored fileStream requires size; for deflated streams it is optional and checked. Deflated data can expand roughly a thousandfold and pulling the next entry inflates the rest of the current one, so for untrusted archives check header.size, count the bytes of bodies without one, and end the stream at an oversized entry rather than skipping it. Every ZipError (InvalidHeader, InvalidData, Truncated, Checksum, SizeMismatch, Unsupported, BodyConsumed) ends the archive.
Configuration formats. The remaining parsers (Ini, Toml, Yaml, Json5, Jsonc) are synchronous, non-streaming functions that decode human-authored configuration text into unknown data. Toml, Json5, and Jsonc return a Result with an EncodingError; Ini and Yaml return the value directly, and Yaml throws on invalid input. Schema-decode their results before trusting them at an application boundary.
A small, dependency-free INI decoder used by the CLI configuration-file primitive. Ini.parse(text) returns a null-prototype record: dotted section names become nested records, key[] repetitions become arrays, and true, false, and null become scalars. Other values — including numbers — remain strings.
Use for conventional INI configuration input. Parse is synchronous and deliberately returns unknown values; decode the result with Schema before using it as application config.
A focused TOML 1.0 parser covering tables, dotted keys, arrays and inline tables, arrays of tables, multiline strings, numeric formats, and TOML date/time forms. Toml.parse(text) does not throw: it returns Result<Record<string, unknown>, EncodingError>, failing with an EncodingError (module: "Toml", kind: "Decode", and a message carrying the line and column) for invalid input. Tables are null-prototype records. Offset date-times become JavaScript Dates; local dates and times remain strings. The parser rejects what TOML 1.0 forbids: duplicate keys and tables, extending an inline table or a statically defined array, out-of-range dates and times such as 1979-02-30 or 24:00:00, integers outside JavaScript's safe range, raw control characters (including a bare carriage return), and non-scalar Unicode escapes.
Self-contained source · Type-checked
ts
import { Effect, Result } from "effect"import { Toml } from "effect/encoding"const parsed = Toml.parse(`title = "Merit service"ports = [8000, 8001][database]enabled = truecredentials = { user = "service", roles = ["reader", "writer"] }`)if (Result.isSuccess(parsed)) { console.log(parsed.success.title) // "Merit service"}// Inside an effect, lift the Result: a failure becomes the typed EncodingError.const loadConfig = (text: string) => Effect.gen(function*() { const config = yield* Effect.fromResult(Toml.parse(text)) return config })
Migration:Toml.parse used to throw SyntaxError. Code that wrapped it in try/catch or Effect.try now receives a Result instead; branch on it, or lift it with Effect.fromResult to fail the effect with the EncodingError.
Use when the CLI or another trusted boundary accepts TOML. Validate the parsed record with Schema before trusting it.
A focused YAML 1.2 configuration parser. Unlike Toml.parse, Yaml.parse(text) returns unknown and throws on invalid input. It supports block and flow collections (flow collections may span lines), quoted and block scalars, anchors (including anchors inside flow collections), aliases, and YAML 1.1 merge keys: an unquoted << key merges a mapping, or a sequence of mappings, into the enclosing mapping, with explicit keys winning over merged ones and earlier merge sources over later ones; quote it ("<<") to keep an ordinary key. Invalid indentation, duplicate keys, malformed collections, and unknown aliases throw SyntaxError. The parser rejects three inputs that resemble valid YAML but are not: a plain (unquoted) scalar with a colon followed by a space or the end of the value (description: Use when: deploy, description: Deploy:), a compact nested sequence (- - value), and a stream of several documents separated by ---. Colons without a following space, as in url: http://x.com or time: 12:30, still parse as plain text.
import { Yaml } from "effect/encoding"// Quote any value that contains ": " — unquoted, this line throws SyntaxError.const reviewStep = Yaml.parse(`step: calibrationdescription: "Use when: a manager disputes a merit rating"`)
Self-contained source · Type-checked
ts
import { Yaml } from "effect/encoding"// A merge key reuses shared settings; the explicit `size` wins over the merged one.const environments = Yaml.parse(`defaults: &defaults region: eu-west-1 size: 1production: <<: *defaults size: 3`)// { defaults: { region: "eu-west-1", size: 1 },// production: { region: "eu-west-1", size: 3 } }
This is a configuration-focused parser, not a promise of every YAML feature. Treat parsed values as untrusted and schema-decode them before application use.
A dependency-free JSON5 parser for hand-edited configuration. Json5.parse(text) returns Result<unknown, EncodingError>, failing with an EncodingError (module: "Json5", kind: "Decode") whose message gives the line and column but never repeats the input. Beyond JSON it accepts comments, trailing commas, unquoted identifier keys, single-quoted strings, hexadecimal numbers, Infinity, and NaN. A duplicate key keeps its last value, and a __proto__ key becomes an ordinary own property instead of replacing the prototype. There is no reviver argument.
Self-contained source · Type-checked
ts
import { Effect, Result } from "effect"import { Json5 } from "effect/encoding"const parsed = Json5.parse(`{ // reviewers per cycle service: 'merit-review', ports: [8000, 8001,],}`)if (Result.isSuccess(parsed)) { console.log(parsed.success) // { service: "merit-review", ports: [8000, 8001] }}Result.isFailure(Json5.parse("{ port: }")) // true: "Invalid JSON5 at line 1, column 9"// Inside an effect, lift the Result so the EncodingError lands in the error channel.const loadConfig = (text: string) => Effect.fromResult(Json5.parse(text))
JSON with comments, the format of tsconfig.json and editor settings files. Jsonc.parse(text) returns Result<unknown, EncodingError> (module: "Jsonc") and accepts exactly what JSON.parse accepts once line and block comments are removed, plus one leading BOM. Unlike JSON5 it rejects trailing commas and every other extension, and duplicate keys and __proto__ follow JSON.parse. Error positions are one-based lines and columns in UTF-16 code units, and the message does not include the input.
Self-contained source · Type-checked
ts
import { Result } from "effect"import { Jsonc } from "effect/encoding"Jsonc.parse(`{ "strict": true /* required */ } // trailing comment`) // Result.succeed({ strict: true })Result.isFailure(Jsonc.parse(`{ "strict": true, }`)) // true: trailing commas are not JSONC
Use Json5 when people write the file by hand and expect JavaScript-like syntax, Jsonc when the file must stay readable by JSON.parse-based tools after comments are stripped. Both return unknown: decode the result with Schema before using it as application config.
Effect provides a composable time stack: typed duration values, a testable clock-aware date/time system, a cron parser, an effect-native PRNG, and Schedule, the algebraic policy engine powering retry and repeat.
Official companions: Effect's release-matched ai-docs corpus has executable Schedule and DateTime examples.
Official guides:Using schedules introduces Effect.repeat, Effect.schedule, and Effect.retry; Choosing and combining schedules walks through the constructors, limiters, and combinators; the Schedule cookbook has complete retry and polling programs. Section-specific guides are linked where they apply. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
What it is. A Schedule<Output, Input, Error, Env> is a composable recurrence policy. At each step it decides: keep going or stop? If continuing, how long to wait? The policy can inspect the input (error when retrying, success value when repeating) and emit any output. Effect.retry and Effect.repeat are built on this primitive.
Mental model. A Schedule is a composable state machine from (now, input) to (output, delay) — or done. Most built-in policies are pure, but the type's Error and Env parameters are real: effectful predicates/transforms may fail or require services. Like parser combinators for timing policies, you build primitives and pipe them together rather than hand-writing the state machine.
import { Schedule, Duration } from "effect"// Retry/repeat up to N additional times (after the initial attempt)const fiveTimes = Schedule.recurs(5)// Wait a fixed gap after each completion — delays are relative to when the// previous run finished. Good for polling.const everySecond = Schedule.spaced("1 second")// Fixed cadence measured from this schedule's first step. If work overruns,// the next recurrence is immediate; missed ticks are not replayed.const every30s = Schedule.fixed("30 seconds")// Divide elapsed time into 30-second windows and sleep to the nearest next// boundary after each step.const every30sWindow = Schedule.windowed("30 seconds")// Exactly one recurrence after one minute; unlike `during`, this is a delay.const oneFollowUp = Schedule.duration("1 minute")// Recurs immediately once (no delay), outputting void. Shorthand for a// single follow-up where `duration`'s wait is unwanted.const exactlyOnce = Schedule.once// Pure exponential backoff. Second argument is the multiplier (default 2).const expBackoff = Schedule.exponential("200 millis")// Fibonacci growth — slower than exponential, gentler on stressed backends.// The base delay repeats once: 100, 100, 200, 300, 500 ms, ...const fibBackoff = Schedule.fibonacci("100 millis")// An elapsed-time budget. It adds no delay by itself, so combine it with a// cadence or backoff rather than using it as a timer.const thirtySecBudget = Schedule.during("30 seconds")// Recurs without end and without delay, outputting 0, 1, 2, ... It is the// base that the `{ times, while, until }` options object builds on.const noDelayForever = Schedule.forever// Recurs without end and outputs its input unchanged — the starting point for// a policy whose delay is derived from the input via `modifyDelay`.const echoStatus = Schedule.identity<"Pending" | "Approved" | "Rejected">()
Warning: A schedule with no stopping condition retries or repeats forever, and Schedule.forever does so in a hot loop. Every policy that reaches production needs a bound (recurs, upTo, during) and, for remote calls, a delay.
Schedule.max([...]) continues only while all schedules recur and waits for the slowest delay. Schedule.min([...]) continues while any schedule recurs and waits for the fastest delay. Schedule.concat sequences one policy after another, and Schedule.upTo bounds an existing policy by elapsed duration, recurrence count, or both.
Self-contained source · Type-checked
ts
import { Schedule, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { retryable: Schema.Boolean }) {}// === HRIS retry policy ===// Exponential backoff starting at 250 ms, each delay capped at 10 s via// min picks the shorter delay, jitter spreads callers after an outage,// and upTo hard-stops after 6 schedule recurrences.const hrisRetryPolicy = Schedule.min([ Schedule.exponential("250 millis"), Schedule.spaced("10 seconds")]).pipe( Schedule.jittered, Schedule.upTo({ times: 6 }))// === Merit-cycle sync policy ===// Retry aggressively at first (3 quick attempts), then back off to a slow// steady heartbeat — useful for a quarterly merit-cycle data sync.const warmThenSteady = Schedule.exponential("100 millis").pipe( Schedule.upTo({ times: 3 }), Schedule.concat(Schedule.spaced("5 seconds")))
max and min output the selected Duration, so add Schedule.passthrough later if the retry input must become the output.
concatResult(first, second) preserves which phase emitted an output: first-phase values are Result.Failure, second-phase values are Result.Success. Use it instead of concat when downstream logic must distinguish warm-up from steady state.
upTo({ times: n }) counts schedule recurrences, not the initial evaluation: a retry/repeat effect can therefore run up to n + 1 times. Schedules may also fail—for example an effectful predicate or an invalid Schedule.cron—and Effect.schedule / scheduleFrom expose that schedule error alongside the wrapped effect's own error.
Schedules receive the error (for retry) or success value (for repeat) as input. Use Schedule.while to short-circuit on non-retryable failures, avoiding burning retry budget on permanent errors.
Fragment · Type-checked
ts
import { Duration, Effect, Schedule, Schema } from "effect"class HrisError extends Schema.TaggedError<HrisError>()("HrisError", { message: Schema.String, status: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })), retryable: Schema.Boolean}) {}// Only retry when the HRIS says the failure is transient (e.g. 503, not 404).const hrisRetry = Schedule.exponential("250 millis").pipe( (backoff) => Schedule.min([backoff, Schedule.spaced("10 seconds")]), Schedule.jittered, Schedule.setInputType<HrisError>(), Schedule.while(({ input }) => input.retryable))// `tap` observes the complete metadata object without changing behavior.const instrumented = hrisRetry.pipe( Schedule.tap(({ duration, input }) => Effect.logDebug( `Retrying HRIS after ${input.status}: ${input.message}; next attempt in ${Duration.format(duration)}` ) ))declare const fetchEmployee: (id: string) => Effect.Effect<{ name: string }, HrisError>const loadEmployee = fetchEmployee("emp-42").pipe( Effect.retry(instrumented), Effect.orDie)
The complete schedule metadata is { input, output, duration, attempt, start, now, elapsed, elapsedSincePrevious }. tap, addDelay, and modifyDelay callbacks all receive that same object, so instrumentation and adaptive delays can use attempt and elapsed-time context without reconstructing it.
addDelay adds an effectfully computed duration to the policy's selected delay; modifyDelay replaces that delay. A provider's Retry-After value is therefore usually a modifyDelay lower bound:
Schedule.while also accepts a type guard over the metadata object — (meta): meta is Schedule.Metadata<Output, NarrowedInput> => … — and then narrows the resulting schedule's input and output types. When the predicate belongs to one call site rather than to a shared policy, the options object is shorter than setInputType plus while.
Effect.repeat repeats on success and stops on failure. Combined with Schedule.passthrough, poll for a terminal state and get the final value back.
Fragment · Type-checked
ts
import { Effect, Schedule } from "effect"type ApprovalStatus = "Pending" | "Approved" | "Rejected"declare const getMeritApprovalStatus: ( cycleId: string) => Effect.Effect<ApprovalStatus>const pollUntilSettled = Schedule.spaced("10 seconds").pipe( Schedule.setInputType<ApprovalStatus>(), Schedule.passthrough, // output = the latest ApprovalStatus Schedule.while(({ input }) => input === "Pending"))// The final output of Effect.repeat is the last ApprovalStatus that caused// the schedule to stop — "Approved" or "Rejected".const waitForMeritApproval = (cycleId: string) => getMeritApprovalStatus(cycleId).pipe(Effect.repeat(pollUntilSettled))
Effect.repeat fails as soon as one run fails, and the caller loses the schedule context.Effect.repeatOrElse(effect, schedule, orElse) hands the failure (the effect's or the schedule's) to a handler that must produce the schedule's output type, together with Option<Schedule.Metadata> for the previous step — None when the very first run failed. Effect.retryOrElse(effect, policy, orElse) is the failure-side twin: when the policy is exhausted, orElse(lastError, scheduleOutput) supplies a fallback instead of the last error.
Fragment · Type-checked
ts
import { Effect, Option, Schedule } from "effect"declare const sendPayrollHeartbeat: Effect.Effect<void, "Disconnected">// Ends with the number of completed beats instead of an error.const heartbeat = Effect.repeatOrElse( sendPayrollHeartbeat, Schedule.spaced("30 seconds"), (error, previous) => Effect.logWarning(`payroll heartbeat stopped: ${error}`).pipe( Effect.as(Option.match(previous, { onNone: () => 0, onSome: (meta) => meta.attempt })) ))
Effect.retry and Effect.repeat also accept a plain options object instead of a Schedule:
Key
Meaning on retry
Meaning on repeat
schedule
Pacing and bounds between attempts
Pacing and bounds between runs
while
Keep retrying while the error matches
Keep repeating while the success value matches
until
Stop retrying once the error matches
Stop repeating once the value matches
times
At most n retries after the first attempt
At most n repetitions after the first run
The object is sugar for Schedule.passthrough(schedule ?? Schedule.forever) filtered with Schedule.while, which explains the two surprises:
The result is the last value, not a schedule counter.Effect.repeat(poll, { until }) returns the value that satisfied until.
Omitting schedule means zero delay.{ while: isTransient } alone is an unbounded hot loop against a struggling dependency. Always pair a predicate with schedule, times, or both.
schedule or times cancels type narrowing. A type-guard while/until only narrows the result (on repeat) or the error (on retry) when the options object has neither schedule nor times. Either one can end the loop before the predicate does — a capped recurrence count or a schedule that completes on its own — so the compiler keeps the original, unnarrowed type whenever schedule/times is present, even though the refinement itself is unchanged.
Predicates may return boolean or an Effect of boolean. With a bare { until } or { while } and no schedule/times, a type guard narrows the result: until narrows the success type on repeat, and while alone removes that error from E on retry — it is retried without limit, so it can never be the final failure. Add schedule or times back for pacing or a hard cap, and the result or error type widens to the source type again.
Fragment · Type-checked
ts
import { Effect, Schedule, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { status: Schema.Int }) {}class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()( "EmployeeNotFound", { employeeId: Schema.String }) {}declare const fetchEmployee: ( id: string) => Effect.Effect<{ readonly name: string }, HrisUnavailable | EmployeeNotFound>declare const getApprovalStatus: Effect.Effect<"Pending" | "Approved" | "Rejected">// Timing is a reusable, named value with no opinion about error types.const hrisBackoff = Schedule.exponential("250 millis").pipe(Schedule.jittered)// Classification sits at the call site that knows what this operation can fail with.// `while` here is a plain predicate, not a type guard, so `times`/`schedule`// have no bearing on its type — they only bound the retry count and pacing.const loadEmployee = (id: string) => fetchEmployee(id).pipe( Effect.retry({ schedule: hrisBackoff, times: 4, while: (error) => error._tag === "HrisUnavailable" }) )// repeat is success-driven. With no `schedule`/`times`, `until`'s refinement// is the only way the loop can stop, so it is also the only type the result// needs to carry.const settled: Effect.Effect<"Approved" | "Rejected"> = Effect.repeat(getApprovalStatus, { until: (status): status is "Approved" | "Rejected" => status !== "Pending"})// Add `schedule` back for pacing between polls, and the result widens to the// full status type again: the schedule could in principle end the loop// before `until` does, even though the refinement text is unchanged.const settledPaced: Effect.Effect<"Pending" | "Approved" | "Rejected"> = Effect.repeat(getApprovalStatus, { schedule: Schedule.spaced("10 seconds"), until: (status): status is "Approved" | "Rejected" => status !== "Pending"})
Put the predicate…
When
On the call site ({ schedule, while })
The classification is specific to one operation; the timing policy is shared and stays input-agnostic
In the schedule (Schedule.while)
The whole policy — timing and classification — is shared and its error type is fixed, or the predicate needs attempt, elapsed, or the computed duration
A third form avoids Schedule.setInputType: pass a builder, Effect.retry(($) => $(hrisBackoff).pipe(Schedule.while(({ input }) => input._tag === "HrisUnavailable"))). The $ function pins the schedule's input to the effect's error type (or success type, for repeat).
A retry policy is a specification, so write it down before composing combinators, then test its shape.
Classify first. Which typed errors are transient? Defects and interruption are never retried; everything not named retryable must fail on the first attempt.
Bound it. Maximum recurrences and a total time budget (upTo({ times, duration })), inside the caller's timeout rather than multiplying it.
Pace it. Backoff with a per-delay cap, plus Schedule.jittered in production so recovering callers do not synchronize.
Retry the transient operation, not the whole use case. Wrap the HRIS call, not the workflow that also wrote an audit row.
Build the side effect inside the retried Effect.Effect.retry re-runs an Effect description. const pending = client.fetch(id) followed by retrying Effect.promise(() => pending) replays one settled Promise; call the client inside Effect.tryPromise so every attempt starts fresh work.
Confirm idempotency for anything that writes; retry gives at-least-once attempts.
Decide what is observed: a Schedule.tap log or metric per retry, and the final failure left in E.
Interruption stops both the running attempt and the pending delay, so a retried effect needs no extra cancellation plumbing.
Schedule.cron parses a standard 5-field (or 6-field with seconds) cron expression and builds a schedule sleeping until the next matching wall-clock time. Accepts an optional IANA timezone string and an optional { onDstOverlap } policy (see Cron); a pre-parsed Cron value keeps its own policy. DST transitions are handled correctly: Cron.next will not return a past occurrence or exhaust its search limit when the current time falls inside a repeated DST interval. A step that lands less than a nanosecond before a tick counts as being on that tick, so Schedule.cron (like Schedule.fixed and Schedule.windowed at their boundaries) waits for the following one instead of recurring again with a zero delay.
Fragment · Type-checked
ts
import { Effect, Schedule } from "effect"declare const kickOffMeritCycle: Effect.Effect<void>// "0 8 1 1,4,7,10 *" = 08:00 on the first day of Jan, Apr, Jul, Oct// — a quarterly merit-cycle kickoff in New York time.const quarterlyCycle = Schedule.cron( "0 8 1 1,4,7,10 *", "America/New_York")// Effect.repeat runs the effect once immediately then at each cron tick.const meritCycleJob = kickOffMeritCycle.pipe(Effect.repeat(quarterlyCycle))// Effect.schedule consults the schedule first: nothing runs until the next tick.const meritCycleJobOnTick = kickOffMeritCycle.pipe(Effect.schedule(quarterlyCycle))
Effect.repeat always evaluates the effect once before it asks the schedule anything; Effect.schedule steps the schedule first. A deploy or crash-restart therefore re-runs a repeat-driven job immediately, which is rarely what a quarterly kickoff or nightly payroll run wants. The same difference shows up in counts: Effect.repeat(task, Schedule.recurs(2)) runs three times, Effect.schedule(task, Schedule.recurs(2)) runs twice. Effect.schedule feeds the schedule undefined on that first step, so it accepts only schedules whose input type is unknown; Effect.scheduleFrom(effect, initial, schedule) seeds a typed initial input instead.
Running a side task for as long as the main task runs
To log progress or send a heartbeat while real work runs, race an endlessly repeating effect against the main effect: the repeater never completes, so when the main effect finishes first the repeater is interrupted with no fork bookkeeping.
Fragment · Type-checked
ts
import { Effect, Schedule } from "effect"declare const runMeritCycle: Effect.Effect<number, "BudgetExceeded">const progress = Effect.log("merit cycle still running").pipe( Effect.repeat(Schedule.fixed("5 seconds")))// raceFirst settles with whichever side completes first, success or failure.const program = Effect.raceFirst(runMeritCycle, progress)
Warning: Use Effect.raceFirst here, not Effect.race. race waits for the first success: if runMeritCycle fails while the repeater is still healthy, race keeps waiting on a side task that never finishes and the failure is never reported. Because raceFirst also settles on the side task's failure, make a fallible side task infallible first (Effect.ignore), or a lost heartbeat cancels the merit cycle.
A schedule is a step function from (now, input) to (output, delay), and Schedule.toStep hands you that function. Feeding it timestamps and inputs by hand prints the exact delay sequence of a composed policy without running an effect or sleeping — the cheapest way to answer "does my capped backoff really plateau at two seconds and stop after five recurrences?". The step is a Pull: success is [output, delay], and exhaustion arrives on the done channel, so close the loop with Pull.catchDone rather than an error handler.
Asserting only the final value and an attempt count proves little: that test also passes for a policy with no backoff at all, for one that retries permanent errors, and for one with the wrong multiplier or cap. Assert the policy's shape on both paths instead:
Retryable path: record attempt@virtualMillis from Clock.currentTimeMillis inside the operation and assert the exact timeline — for Schedule.exponential("100 millis") bounded to two recurrences, ["attempt-1@0", "attempt-2@100", "attempt-3@300"].
Non-retryable path: run the same harness with a permanent error and assert exactly one attempt, at time zero, with the error still in E.
Exhaustion: with an error that never clears, assert the attempt count equals the bound plus one and that the last typed error is what the caller sees.
Keep jitter out of the asserted policy. Compose Schedule.jittered only in the production policy, or pin it with Random.withSeed.
Recur without end and without delay; outputs the recurrence count
identity<A>()
Recur without end; output equals input
max([s1, s2])
Continue while all recur; use the slowest delay
min([s1, s2])
Continue while any recur; use the fastest delay
concat(s)
Run self then other sequentially
jittered
Multiply delay by 0.8–1.2 randomly
while(pred)
Stop when predicate returns false
passthrough
Output the input instead of policy output
upTo({ duration, times })
Bound elapsed time and/or recurrences
addDelay(f)
Add an effectful metadata-derived delay
modifyDelay(f)
Replace the selected delay effectfully
tap(({ input, output, duration, ... }))
Observe full step metadata
cron(expr, tz?)
Sleep to next cron wall-clock match
toStep(schedule)
Extract the step function to inspect or unit-test the delay sequence
Runner
First execution
Input fed to the schedule
Result
Effect.retry(effect, policy)
Immediately
Each typed error
The first success; the last error if the policy stops
Effect.repeat(effect, schedule)
Immediately
Each success value
The schedule's final output (the last value, for the options form)
Effect.schedule(effect, schedule)
After the schedule's first delay
undefined, then each success value
The schedule's final output
Effect.retryOrElse / Effect.repeatOrElse
As retry / repeat
As above
retryOrElse: the fallback once the policy is exhausted; repeatOrElse: the fallback once a run fails
Reach for it when you need to retry failed API calls with backoff, poll a workflow for a terminal state, run background jobs on a cron cadence, or express any policy combining timing, attempt count, and error classification.
What it is.Duration is Effect's typed time-span value. Every scheduling API, timeout, and sleep accepts a Duration.Input — a raw number (millis), a string like "5 seconds", or a Duration object. For arithmetic or comparison, construct a real Duration first.
Mental model. A tagged value preserving finite integral milliseconds as number, sub-millisecond/exact values as nanosecond bigint, and explicit positive/negative infinity. It implements Equal, Pipeable, and Inspectable; module-level Order and Equivalence support sorting, clamping, and min/max. Hashes are canonical across equal millis/nanos representations, so semantically equal durations are safe as HashMap/HashSet keys.
Self-contained source · Type-checked
ts
import { Duration } from "effect"// Construction — pick the unit that matches your domainconst heartbeat = Duration.millis(50)const ttl = Duration.seconds(30)const lease = Duration.minutes(15)const day = Duration.days(1)// A fixed 365-day interval. Calendar-based 12-month cliffs belong in DateTime.const fixedYear = Duration.days(365)// String shorthand works wherever Duration.Input is accepted:// "200 millis", "5 seconds", "2 minutes", "1 hour", "3 days", "1 week"// Arithmeticconst totalReview = Duration.sum(Duration.weeks(1), Duration.days(2)) // 9 daysconst doubled = Duration.times(Duration.hours(2), 2) // 4 hconst overtime = Duration.subtract(Duration.hours(9), Duration.hours(8)) // 1 h// Comparisons — e.g. is a fixed interval already past?Duration.isLessThan(Duration.days(200), fixedYear) // true (200d < 365d)Duration.isGreaterThan(Duration.weeks(52), fixedYear) // falseDuration.between(Duration.days(300), { minimum: Duration.days(180), maximum: Duration.days(365)}) // true — 300d is within the range// ConversionDuration.toMillis(Duration.days(1)) // 86_400_000Duration.toSeconds(Duration.minutes(15)) // 900// Human-readable formatting — useful in review-deadline notificationsDuration.format(Duration.sum(Duration.days(30), Duration.hours(4))) // "30d 4h"// ISO 8601 durations for wire formats that require themDuration.formatIso(Duration.minutes(90)) // Option.some("PT1H30M")Duration.fromIso("P1W2D") // Option.some(Duration.days(9))Duration.fromIso("P1M") // Option.none() — months have no fixed length
Duration.formatIso balances into days (24 hours), hours, minutes, and seconds with up to nine fractional digits, writes "PT0S" for zero and a leading - for negative values, and returns Option.none() for an infinite duration. Duration.fromIso accepts weeks, days, hours, minutes, and seconds (a fraction only on the last time component) and rejects years and months. Duration.toMicros joins toMillis, toSeconds, and the other numeric converters.
Tip:Duration.Input accepts strings like "500 millis", "5 seconds", "2 minutes", "1 hour", "3 days", and "1 week". You never need to multiply by 1000 to pass a duration to Effect.sleep, Schedule.spaced, or Effect.timeout — just write the human name.
Parse a duration once, at startup, into a Duration, and pass that value everywhere after. A bare 5 in a config file or function signature does not say seconds, milliseconds, or attempts; a Duration cannot be misread.
Source of the value
Use
On bad input
Environment / config provider
Config.Duration("HRIS_TIMEOUT")
Typed ConfigError at startup
JSON, HTTP payloads, database text
Schema.DurationFromString inside the boundary schema
SchemaError from decoding
A wire format that mandates ISO 8601 ("PT1H30M")
Schema.DurationFromIsoString
SchemaError from decoding; encoding fails for infinite durations
A value already typed as Duration.Input
Duration.fromInput(input)
Option.none()
A literal you control
Duration.fromInputUnsafe("5 seconds"), or a constructor
Throws — never feed it external text
Duration.fromInput and fromInputUnsafe accept the full Duration.Input union: a number is milliseconds, a bigint is nanoseconds, a string is "<n> <unit>" (nanos through weeks, singular or plural) or "Infinity" / "-Infinity", a [seconds, nanos] tuple is high-resolution time, and an object such as { minutes: 1, seconds: 30 } adds its fields. Schema.DurationFromString decodes strings only; Config.Duration parses text from its provider. Their string grammars agree, not their full accepted input domains.
Self-contained source · Type-checked
ts
import { Config, Duration, Effect, Option, Schema } from "effect"// Deployment input: a malformed value is a named startup failure.const hrisTimeout = Config.Duration("HRIS_TIMEOUT").pipe( Config.withDefault(Duration.seconds(5)))// Boundary schema: "90 seconds" on the wire, Duration in the domain.const SyncSettings = Schema.Struct({ pollEvery: Schema.DurationFromString})// "No TTL" is a value, not a magic number.const cacheTtl = Option.getOrElse( Duration.fromInput("15 minutes"), () => Duration.infinity)const program = Effect.gen(function*() { const timeout = yield* hrisTimeout // Combine spans with Duration arithmetic, not + and *. const budget = Duration.sum(Duration.times(timeout, 3), Duration.seconds(1)) // Convert to a number only where a foreign API demands one. const timer = setTimeout(() => {}, Duration.toMillis(budget)) clearTimeout(timer) return { budget, cacheTtl, SyncSettings }})
Duration.infinity has no nanosecond value: Duration.toNanos returns Option.none() for it, while Duration.toNanosUnsafe throws. Use the Option form whenever a configurable TTL or timeout may be infinite.
Pick the codec by the precision and range you promise.Schema.DurationFromMillis encodes through a JavaScript number, so nanosecond-precision durations beyond 2^53 ns do not survive a round trip. Schema.DurationFromNanos (a bigint carrier) is exact but rejects an infinite duration when encoding. Schema.DurationFromString is exact and carries "Infinity".
Large finite integer milliseconds convert through bigint before scaling to nanoseconds. This avoids overflow in millis * 1_000_000 and preserves the represented integer's precision; it cannot recover precision already lost in an input JavaScript number. Equal millisecond and nanosecond representations compare and hash equally even at very large magnitudes.
Fractional scaling rounds to the nearest nanosecond, ties away from zero.Duration.times(Duration.nanos(3n), 0.5) is 2n nanoseconds; negative ties round away from zero too. Non-finite scaling and overflowing nanosecond input totals are normalized through Duration's infinity/zero handling rather than throwing during BigInt conversion.
Reach for it when you need to express, compare, add, or format typed time spans rather than raw millisecond numbers. It is the currency of every scheduling and timeout API in the library.
What it is.DateTime is Effect's Clock-aware, timezone-capable replacement for the native Date type. Two flavors: DateTime.Utc (a pure millisecond instant) and DateTime.Zoned (an instant pinned to an IANA timezone with rendered local time). Covers parsing, current time, arithmetic, and formatting.
Mental model. An instant is always stored as UTC epoch milliseconds. A Zoned value wraps that instant with a timezone tag so calendar-math (add 1 month, start of week) respects DST transitions. Attaching a zone does not change the underlying timestamp — it changes the lens through which it is read.
Warning:DateTime.now and DateTime.nowInCurrentZone read Effect's Clock, so TestClock controls them. DateTime.nowUnsafe() and new Date() read global wall time and bypass that service; reserve them for synchronous boot code outside an Effect. Constructing/parsing a known timestamp is pure and does not have this problem.
import { DateTime, Option } from "effect"// make() returns Option.Option<DateTime.Utc> — never throwsconst parsed: Option.Option<DateTime.Utc> = DateTime.make("2024-06-15T14:30:00.000Z")// From epoch millis (e.g. a grantDate stored as a number in the HRIS)const fromEpoch: Option.Option<DateTime.Utc> = DateTime.make(1_718_460_600_000)// Epoch-second boundaries avoid hand-written ×1000 / ÷1000 conversions.const fromSeconds: DateTime.Utc = DateTime.fromEpochSeconds(1_718_460_600)DateTime.toEpochSeconds(fromSeconds) // 1_718_460_600// When you're certain the string is valid (e.g. a hardcoded grant date):const grantDate = DateTime.makeUnsafe("2023-01-15T00:00:00Z")
DateTime.Input is an existing DateTime, a JavaScript Date, epoch milliseconds, a partial parts object such as { year: 2026, month: 4 } (missing parts default to the start of the period, in UTC), or a string.
Warning:A zone-less string and a zone-less Date do not mean the same thing.DateTime.make("2026-01-01 04:00:00") treats the text as UTC and yields 04:00Z. DateTime.make(new Date("2026-01-01 04:00:00")) inherits JavaScript's rule that a zone-less date-time string is host local time, so the same text becomes 03:00Z on a machine running at UTC+1 — and a different instant on every other machine. Pass strings, not pre-built Date objects, and when the text is a wall-clock reading in a known zone, use makeZoned with adjustForTimeZone. DateTime.fromDateUnsafe throws on an invalid Date.
import { DateTime, Effect, Option } from "effect"import { NodeRuntime } from "@effect/platform-node"const program = Effect.gen(function*() { const now = yield* DateTime.now // Attach a known IANA zone — unsafe (throws if zone is invalid) const nyTime = now.pipe(DateTime.setZoneNamedUnsafe("America/New_York")) // Safe variant returns Option — use when zone comes from user input const sfTime: Option.Option<DateTime.Zoned> = now.pipe( DateTime.setZoneNamed("America/Los_Angeles") ) // Render with offset and zone id: "2026-06-20T10:00:00.000-04:00[America/New_York]" const isoZoned = DateTime.formatIsoZoned(nyTime) yield* Effect.log(`Merit cycle closes at: ${isoZoned}`) // Read the current zone from the CurrentTimeZone service const localNow: DateTime.Zoned = yield* DateTime.nowInCurrentZone yield* Effect.log(DateTime.formatIsoZoned(localNow))}).pipe( // Provide New York as the application-wide current zone Effect.provide(DateTime.layerCurrentZoneNamed("America/New_York")), NodeRuntime.runMain)
A zone is a value of its own, DateTime.TimeZone, with two variants: TimeZone.Named (an IANA id, DST-aware) and TimeZone.Offset (fixed milliseconds from UTC). An offset zone never follows daylight saving, so store the IANA id whenever the zone describes a place. Validate a user-supplied zone once and reuse the value:
import { DateTime, Option } from "effect"// An employee profile stores either an IANA id or a fixed offset.const parseProfileZone = (raw: string): DateTime.TimeZone => DateTime.zoneFromString(raw).pipe( Option.getOrElse(() => DateTime.zoneMakeOffset(0)) // fall back to UTC )const reviewOpens = DateTime.makeUnsafe("2026-03-01T00:00:00Z")// setZone re-reads the same instant through a validated zone value.const forEmployee = DateTime.setZone(reviewOpens, parseProfileZone("Asia/Kolkata"))// setZoneOffset is the fixed-offset shortcut (+05:30 in milliseconds).const fixedOffset = DateTime.setZoneOffset(reviewOpens, 5.5 * 60 * 60 * 1000)
DateTime.zoneToString(zone) renders the id or offset back to text.
A named zone keeps the identifier you supplied.TimeZone.Named.id is the input id, aliases included: "Europe/Kyiv", "Etc/UTC", and "US/Eastern" stay as written even where Intl resolves them to "Europe/Kiev", "UTC", or "America/New_York". Intl only fixes the casing when its resolved id differs from the input in case alone, so "europe/london" becomes "Europe/London" while "europe/kyiv" stays lowercase. zoneToString, the bracket in formatIsoZoned, and the Schema string and JSON encodings all write that id, but Equal and Hash use Intl's resolved id — so Europe/Kyiv and Europe/Kiev are equal zones that serialize differently. Normalize ids at the boundary (validate against your own canonical list) when stored or compared text must be stable.
setZone* attaches a zone to an instant that is already correct. The other common case is the reverse: the input is a local wall-clock reading — "the merit cycle closes at 09:00 in New York" — and the instant is what you need to compute.
By default DateTime.makeZoned reads its input as UTC and merely attaches the zone; adjustForTimeZone: true interprets the input as local time in that zone, which produces a different instant:
Self-contained source · Type-checked
ts
import { DateTime, Option } from "effect"const local = "2026-03-02T09:00:00"// Input read as UTC, zone attached: 04:00 in New York.const attached = DateTime.makeZonedUnsafe(local, { timeZone: "America/New_York" })DateTime.formatIsoZoned(attached) // "2026-03-02T04:00:00.000-05:00[America/New_York]"// Input read as New York wall-clock time: 09:00 there, 14:00 UTC.const wallClock = DateTime.makeZonedUnsafe(local, { timeZone: "America/New_York", adjustForTimeZone: true})DateTime.formatIsoZoned(wallClock) // "2026-03-02T09:00:00.000-05:00[America/New_York]"DateTime.formatIso(wallClock) // "2026-03-02T14:00:00.000Z"// A payroll cutoff at 02:30 on the day clocks spring forward does not exist.const cutoff = DateTime.makeZoned("2026-03-08T02:30:00", { timeZone: "America/New_York", adjustForTimeZone: true, disambiguation: "reject"}) // Option.none()// formatIsoZoned and makeZonedFromString round-trip without losing the zone.const restored: Option.Option<DateTime.Zoned> = DateTime.makeZonedFromString( DateTime.formatIsoZoned(wallClock))
Daylight-saving transitions make some wall-clock readings nonexistent (the spring-forward gap) and others ambiguous (the repeated hour in autumn). disambiguation applies only together with adjustForTimeZone: true:
disambiguation
Gap (02:30 on 2026-03-08, New York)
Repeated hour (01:30 on 2026-11-01, New York)
"compatible" (default)
Later reading: 03:30 EDT
Earlier occurrence: 01:30 EDT
"earlier"
01:30 EST
01:30 EDT
"later"
03:30 EDT
01:30 EST
"reject"
makeZoned → Option.none(); makeZonedUnsafe throws
same
Use "reject" for deadlines, payroll cutoffs, and anything with legal weight, and surface the rejection to whoever entered the time; silently moving a cutoff by an hour is a decision a person should make. DateTime.setZone accepts the same two options.
import { DateTime } from "effect"const grantDate = DateTime.makeUnsafe("2023-01-15T09:00:00Z").pipe( // Pin to a timezone before doing calendar-aware math DateTime.setZoneNamedUnsafe("America/New_York"))// Vesting cliff: exactly 12 months after grant dateconst cliffDate = grantDate.pipe(DateTime.add({ months: 12 }))// Start of the merit-review quarter (start of the month, 3 months out)const reviewStart = grantDate.pipe(DateTime.add({ months: 3 }), DateTime.startOf("month"))// End of the fiscal year for bonus accrualconst fiscalYearEnd = grantDate.pipe(DateTime.endOf("year"))// How long until the vesting cliff from today?const today = DateTime.makeUnsafe("2026-06-20T00:00:00Z")const timeToCliff = DateTime.distance(today, cliffDate) // Duration (negative = past cliff)// Subtract a Duration — e.g. 30-day window before the cliff to send remindersconst reminderStart = cliffDate.pipe(DateTime.subtractDuration("30 days"))
Month and year arithmetic clamps to the last valid day instead of spilling into the next month: 2026-01-31 plus { months: 1 } is 2026-02-28, and 2024-02-29 plus { years: 1 } is 2025-02-28. Consequently adding a month and then subtracting one is not always the identity — compute recurring dates from the original anchor (grantDate + n months), not by chaining increments. DateTime.setParts / setPartsUtc do not clamp: the parts you pass are applied together, so { month: 2, day: 15 } on 31 January is 15 February, but { month: 2 } alone keeps day 31 and rolls over to 3 March.
Calendar days and elapsed hours differ across DST. On a zoned value, DateTime.add / subtract first apply hours, minutes, seconds, and milliseconds as elapsed time, then apply days, weeks, months, and years as calendar operations. Adding { hours: 24 } moves the instant by exactly 24 hours; adding { days: 1 } preserves the local clock time and can span 23 or 25 hours. Use addDuration for a fixed elapsed interval. startOf, endOf, and nearest keep a zoned value in the same occurrence of a repeated autumn hour — startOf("hour") on the second 01:30 in New York is the second 01:00 (-05:00), not the first — and a calendar-unit endOf that lands in a repeated hour returns the last instant of the later occurrence. When handing a zoned value to a JavaScript API, toDateUtc preserves the instant; toDate instead puts its local wall-clock fields into the returned Date's UTC fields.
import { DateTime, Layer } from "effect"// Named IANA zone — HQ time for the compensation teamconst hqZone = DateTime.layerCurrentZoneNamed("America/New_York")// Fixed UTC offset — offset is in milliseconds (+05:30 = 5.5 * 60 * 60 * 1000)const kolkata = DateTime.layerCurrentZoneOffset(5.5 * 60 * 60 * 1000)// System local zone of the Node processconst local = DateTime.layerCurrentZoneLocal// An already-validated TimeZone valueconst fromValue = DateTime.layerCurrentZone(DateTime.zoneMakeNamedUnsafe("Europe/Rome"))
A Layer fixes the zone for the whole application. For a per-request or per-employee zone, scope CurrentTimeZone to one effect with DateTime.withCurrentZone(zone), withCurrentZoneNamed(id), withCurrentZoneOffset(millis), or withCurrentZoneLocal. withCurrentZoneNamed adds IllegalArgumentError to the effect's error channel for an unknown id, whereas layerCurrentZoneNamed fails when the Layer is built. DateTime.setZoneCurrent(dateTime) re-zones an existing value using the service.
Self-contained source · Type-checked
ts
import { DateTime, Effect } from "effect"// Render the review deadline in each employee's own zone.const deadlineFor = (deadline: DateTime.Utc, employeeZone: DateTime.TimeZone) => DateTime.setZoneCurrent(deadline).pipe( Effect.map(DateTime.formatIsoZoned), DateTime.withCurrentZone(employeeZone) )
Picking the wrong formatter silently changes what a database column or API consumer receives. Output below is for 09:00 New York time on 2 March 2026.
Formatter
Zone applied
Output
DateTime.formatIso
UTC, always
2026-03-02T14:00:00.000Z
DateTime.formatIsoOffset
The value's zone
2026-03-02T09:00:00.000-05:00
DateTime.formatIsoZoned
The value's zone
2026-03-02T09:00:00.000-05:00[America/New_York] — the form makeZonedFromString parses
DateTime.formatIsoDate / formatIsoDateUtc
The value's zone / UTC
2026-03-02 — the two differ near midnight
DateTime.format(dt, options)
The value's zone
Intl.DateTimeFormat output, e.g. Mar 2, 2026, 9:00 AM
DateTime.formatUtc / formatLocal
UTC / the host's zone
As format, with the zone forced
DateTime.formatIntl(dt, formatter)
The formatter's
Bring your own Intl.DateTimeFormat
Persist formatIso (an instant) or formatIsoZoned (an instant plus the place it was meant for); keep format* with Intl options for display only.
Key APIs. Guards: isDateTime, isUtc, isZoned, isTimeZone. Comparison: min, max, between, isLessThan, isGreaterThan, distance. DateTime.isFuture and DateTime.isPast are Effects that read the Clock, so TestClock controls them; isFutureUnsafe / isPastUnsafe read wall time like nowUnsafe. Leaving DateTime: toEpochMillis, toDateUtc, toDate (zone-adjusted), zonedOffset / zonedOffsetIso. Parts: toParts / toPartsUtc, getPart, setParts / setPartsUtc, removeTime, and nearest alongside startOf / endOf.
Official guide: DateTime (several headings keep stale names such as unsafeMake; its "Zoned Constructors" section predates disambiguation; and it describes zone-less strings as local time, which is true only for the Date inputs its examples use).
Reach for it when you need the current time in an Effect, when parsing ISO timestamps safely, when computing dates that must respect DST and timezones, or when formatting a timestamp for display or a database column.
What it is. A pure cron expression parser and evaluator. Parses a standard 5-field (or 6-field with seconds) cron string into a typed Cron value queryable for next/previous run times, instant matching, or an infinite sequence of future fire times. Also backs Schedule.cron.
Mental model. A Cron is six Set<number> values — one per field (seconds, minutes, hours, days, months, weekdays) — plus an optional timezone. Matching is O(1) set lookups; computing the next occurrence walks forward in time field by field.
Self-contained source · Type-checked
ts
import { Cron, Result, DateTime } from "effect"// parse() returns Result<Cron, CronParseError> — never throwsconst everyHour = Result.getOrThrow(Cron.parse("0 * * * *"))// parseUnsafe for hardcoded, known-valid expressions// Nightly payroll run at 01:00 UTC (6-field form with seconds)const nightly = Cron.parseUnsafe("0 0 1 * * *")// Quarterly merit-cycle kickoff: 08:00 on 1 Jan, 1 Apr, 1 Jul, 1 Oct (NY time)const quarterlyMerit = Cron.parseUnsafe("0 8 1 1,4,7,10 *", "America/New_York")// Does today's 08:00 ET match the quarterly expression?const checkpoint = DateTime.makeUnsafe("2026-07-01T12:00:00Z") // 08:00 ETconst fires = Cron.match(quarterlyMerit, checkpoint) // true// Next payroll run after a given instantconst nextPayroll: Date = Cron.next(nightly, new Date("2026-06-20T00:00:00Z"))// → Sat Jun 20 2026 01:00:00 UTC// Enumerate the next 3 nightly payroll runsconst seq = Cron.sequence(nightly)const next3 = [seq.next().value, seq.next().value, seq.next().value]// Serialize for a config editor. A sole zero-seconds field is omitted by default.Cron.format(nightly) // "0 1 * * *"Cron.format(nightly, { includeSeconds: true }) // "0 0 1 * * *"
Cron.format serializes the calendar fields, not the whole semantic value: it drops timezone information, the onDstOverlap policy, and the special day/weekday and restriction. Consequently Cron.parse(Cron.format(cron)) is not always equivalent to cron; persist the missing metadata separately when it matters.
When a zone's clocks fall back, an hour of local time happens twice. Cron.parse, Cron.parseUnsafe, Cron.make, and Schedule.cron take { onDstOverlap } to choose which occurrences count: "earlier" (the default) keeps the first, "later" the second, and "both" both, in chronological order. Zones without repeated times (UTC, fixed offsets) behave the same under every policy. The policy does not govern times skipped when clocks spring forward: a matching time inside that gap resolves to the instant after it.
Self-contained source · Type-checked
ts
import { Cron } from "effect"// Europe/Berlin repeats 02:00–02:59 on 2026-10-25: first at +02:00 (00:30Z), then at +01:00 (01:30Z).const earlier = Cron.parseUnsafe("30 2 * * *", "Europe/Berlin")const later = Cron.parseUnsafe("30 2 * * *", "Europe/Berlin", { onDstOverlap: "later" })const both = Cron.parseUnsafe("30 2 * * *", "Europe/Berlin", { onDstOverlap: "both" })Cron.next(earlier, "2026-10-24T12:00:00Z") // 2026-10-25T00:30:00.000ZCron.next(later, "2026-10-24T12:00:00Z") // 2026-10-25T01:30:00.000ZCron.next(both, "2026-10-25T00:30:00Z") // 2026-10-25T01:30:00.000Z — the second occurrence also fires
Pick "earlier" or "later" for a job that must run once a day, and "both" for an hourly sampler that must not lose an hour of local time.
When the schedule comes from a settings screen or typed configuration rather than a cron string, build it with Cron.make. An empty collection means "unconstrained" for that field, seconds defaults to [0], tz takes a DateTime.TimeZone, and and: true requires day-of-month and weekday to match instead of either.
Self-contained source · Type-checked
ts
import { Cron, DateTime } from "effect"// Payroll preview: 04:00 Rome time on days 8–14 of every month.const secondWeek = Cron.make({ minutes: [0], hours: [4], days: [8, 9, 10, 11, 12, 13, 14], months: [], // every month weekdays: [], // any weekday tz: DateTime.zoneMakeNamedUnsafe("Europe/Rome")})Cron.next(secondWeek, new Date("2026-06-01T00:00:00Z")) // 2026-06-08T02:00:00.000ZCron.prev(secondWeek, new Date("2026-06-01T00:00:00Z")) // 2026-05-14T02:00:00.000Z
Warning:Cron.make throws a RangeError synchronously for out-of-range values (minutes: [99]), and Cron.next / Cron.prev throw when no matching date can be found ("0 0 31 2 *"). Validate user-supplied fields with a Schema first, and prefer Cron.parse, which returns a Result, for cron text.
import { Effect, Schedule } from "effect"// Schedule.cron wraps Cron.parse internally and emits CronParseError if invalid.// Prefer parseUnsafe for literals you control.const payrollCron = Schedule.cron("0 1 * * *", "UTC") // 01:00 UTC every nightdeclare const runPayrollBatch: Effect.Effect<void>// Effect.repeat runs the effect once immediately, then again at each cron tick.const payrollJob = runPayrollBatch.pipe(Effect.repeat(payrollCron))// Effect.schedule waits for the first tick — a restart at 14:00 does not run payroll.const payrollJobOnTick = runPayrollBatch.pipe(Effect.schedule(payrollCron))
Choose the runner by what a restart should do. A nightly job driven by Effect.repeat runs on every deploy and crash-restart, then again at 01:00; Effect.schedule runs only at cron ticks. Neither catches up on ticks missed while the process was down — a job that must not be skipped needs durable scheduling such as ClusterCron or a Workflow. The schedule's output is a Duration (the computed wait), and an invalid expression fails the schedule with Cron.CronParseError.
Reach for it when you need to parse cron expressions from configuration, check whether a scheduled job should have fired, enumerate upcoming run times for a scheduling preview UI, or drive a background job with Schedule.cron.
What it is. Effect-native pseudo-random number generation. Every Random.* function returns an Effect reading from a Context.Reference holding the PRNG service. Because that service can be locally replaced rather than relying on a process-global generator, it is seedable and reproducible — test suites can pin the seed and get deterministic runs.
Mental model.Math.random() is a black box mutating hidden global state. Random.next is an effect reading from an injectable, swappable PRNG. Swap the reference with Random.withSeed("my-seed") and you get the same sequence every run.
Self-contained source · Type-checked
ts
import { Effect, Random } from "effect"const program = Effect.gen(function*() { // Float in [0, 1) const roll = yield* Random.next // Random boolean const flip = yield* Random.nextBoolean // Integer anywhere in the safe-integer range const big = yield* Random.nextInt // Float in [min, max) const pct = yield* Random.nextBetween(0, 100) // Integer in [min, max] inclusive (default; pass { halfOpen: true } for exclusive max) const bucket = yield* Random.nextIntBetween(1, 10) // Pick one element from a collection — e.g. assign a random reviewer const reviewer = yield* Random.choice(["alice", "bob", "carol"] as const) // Shuffle an array — e.g. randomize the order of raise recommendations for review const shuffled = yield* Random.shuffle([1, 2, 3, 4, 5]) return { roll, flip, big, pct, bucket, reviewer, shuffled }})
import { Effect, Random } from "effect"// Simulate a random performance rating draw for load testing.// With a fixed seed, every CI run produces the same sequence.const drawRating = Effect.gen(function*() { const a = yield* Random.nextIntBetween(1, 5) // rating 1–5 const b = yield* Random.nextIntBetween(1, 5) const c = yield* Random.nextIntBetween(1, 5) return [a, b, c] as const})// Same seed → identical output every run, in any environment.const deterministicDraw = drawRating.pipe(Random.withSeed("merit-sim-v1"))// In a real test (e.g. vitest):// const result = await Effect.runPromise(deterministicDraw)// expect(result).toEqual([1, 4, 3]) // pinned by this audited PRNG implementation
Each evaluation of an effect wrapped with Random.withSeed restarts the sequence from the seed, so running the same wrapped effect twice draws the same values. Within one evaluation, the generator object is mutable and inherited by child fibers. Concurrent children in the same region therefore draw from one shared sequence, so scheduling can affect which child receives which value. For independently reproducible branches, wrap each branch separately with its own Random.withSeed.
Schedule.jittered internally uses the Random reference, so it is also seedable in tests. Retry delays with jitter are fully deterministic under a fixed seed.
Self-contained source · Type-checked
ts
import { Effect, Random, Schedule, Schema } from "effect"class HrisError extends Schema.TaggedError<HrisError>()("HrisError", { status: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })), retryable: Schema.Boolean}) {}// Load-test: simulate concurrent compensation-plan API calls with random// employee IDs and staggered delays, reproducibly.const compPlanLoadTest = Effect.gen(function*() { // Random employee ID in a realistic range const empId = yield* Random.nextIntBetween(10000, 99999) // Random startup delay so not all fibers hammer the API at t=0 const jitter = yield* Random.nextBetween(0, 50) yield* Effect.sleep(`${jitter} millis`) yield* Effect.log(`Querying comp plan for employee ${empId}`)}).pipe( // Run 100 times total with a 10 ms gap between completions. Effect.repeat(Schedule.spaced("10 millis").pipe(Schedule.upTo({ times: 99 }))), // Seed the PRNG so the load test is fully reproducible in CI Random.withSeed("comp-load-test-v1"))
Reach for it when you need randomness inside an Effect — picking a random item, shuffling data, generating test data, adding jitter to a custom retry delay, or running a reproducible simulation. Never call Math.random() directly; you lose testability and fiber-locality.
Most collections here use immutable transformations, pipe-friendly dual APIs, and structural Equal/Hash. Exceptions are explicit: HashRing and low-level helpers such as Record.assignProperty mutate their targets. Check each operation's result and ownership contract.
Official guides:Chunk (its unsafeFromArray heading is a stale name; use Chunk.fromArrayUnsafe), HashSet, Equal. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Operates on plain JavaScript arrays — no wrapper type. Collection transformations do not mutate the input; results are native arrays, compatible with third-party code without conversion. Observers and branching helpers return their declared result rather than necessarily allocating an array.
Mental model. Fully typed lodash/fp, integrated with Effect's Order/Equal/Option/Result types. Every function taking a self-argument first also has a curried overload for pipe.
Many functions produce NonEmptyArray<A> (alias: [A, ...A[]]) when the output is guaranteed non-empty — Array.make(1, 2, 3), Array.sortBy(...) on a non-empty input, and Array.groupBy values all yield the tighter type. The readonly counterpart is NonEmptyReadonlyArray<A>. Array.match passes a mutable non-empty array to onNonEmpty for a mutable input and a readonly one otherwise; an inferred data-last callback defaults to readonly so it can accept either input.
Key APIs: make / makeBy / range / replicate, map / flatMap / flatten / filter / filterMap, sort / sortBy / sortWith, groupBy / group / groupWith, partition / separate, dedupe / dedupeWith / dedupeAdjacent, zip / unzip / intersperse, take / drop / span / splitAt / chunksOf, head / last / tail / init, reduce / reduceRight / scan / mapAccum, every / some / contains / findFirst / findLast, getSomes / getSuccesses / getFailures, unfold / cartesian / cartesianWith
Tip: Most collection operators are dual: call Array.map(arr, fn) data-first, or pipe(arr, Array.map(fn)) data-last.
groupBy keeps finite keys. When the key selector returns a literal union, the result type is Record.ReadonlyRecord.GroupByResult<K, NonEmptyArray<A>> — every possible key is known and optional, because a group with no members is simply absent at runtime. A selector typed string still yields an open Record<string, NonEmptyArray<A>>. Iterable.groupBy is typed the same way.
Fragment · Type-checked
ts
import { Array } from "effect"type Rating = "exceeds" | "meets" | "below"interface Review { readonly employeeId: string readonly rating: Rating}declare const reviews: ReadonlyArray<Review>const byRating = Array.groupBy(reviews, (review) => review.rating)// { readonly exceeds?: NonEmptyArray<Review>; readonly meets?: ...; readonly below?: ... }const onPlan = byRating.below ?? [] // a rating nobody received has no key// byRating.outstanding // type error: the selector can never produce it
Counts are normalised. Every count argument in Array, Chunk, Iterable, and String (take, drop, takeRight, chunksOf, makeBy, replicate, ...) is floored when fractional and treated as 0 when NaN or non-positive, so Array.take(xs, 1.7) takes one element and Array.take(xs, NaN) takes none. Constructors that promise a non-empty result (makeBy, replicate, chunksOf) clamp the count to at least 1.
Use for any immutable collection operation on plain arrays — sorting, grouping, deduplicating, partitioning, zipping. Covers ~90% of everyday collection work.
An immutable ordered sequence with five internal backing shapes: empty, singleton, array, slice (ISlice), or concatenation tree (IConcat). Two chunks concatenated stay as a tree node — no data is copied at the join. Traversal materializes a non-array backing on demand and caches that readonly array; Chunk.toArray then returns a separate mutable copy.
Mental model. A balanced rope for arrays. Repeated Array.appendAll copies the accumulated array; Chunk.appendAll instead joins and rebalances immutable tree nodes without copying every element. That makes repeated concatenation much cheaper, although a join can walk and rebalance part of the tree rather than being strictly O(1). NonEmptyChunk mirrors NonEmptyArray and satisfies NonEmptyIterable.
Use Array for most things. Reach for Chunk when doing many concatenations (e.g., collecting emitted items from a Stream) and deferring materialisation.
Self-contained source · Type-checked
ts
import { Chunk, pipe } from "effect"// Accumulate employee IDs without copying the whole prefix on every appendlet acc = Chunk.empty<string>()for (const empId of ["e1", "e2", "e3", "e4", "e5"]) { acc = Chunk.append(acc, empId) // balanced tree join}const ids = Chunk.toArray(acc) // ["e1", "e2", "e3", "e4", "e5"] — mutable copy// Concatenation tree — merge two department chunks without copyingconst engIds = Chunk.make("e1", "e3", "e5")const dsgIds = Chunk.make("e2", "e4")const allIds = Chunk.appendAll(engIds, dsgIds) // tree join; no element-by-element copyconsole.log(Chunk.size(allIds)) // 5// Standard combinators work the same as Arrayconst seniorIds = pipe( Chunk.make(1, 2, 3, 4, 5), // employee levels Chunk.filter((level) => level >= 4), Chunk.map((level) => `L${level}`)) // Chunk("L4", "L5")// Stream.runCollect returns a plain Array in Effect 4import { Stream } from "effect"const program = pipe( Stream.make("e1", "e2", "e3"), Stream.map((id) => id.toUpperCase()), Stream.runCollect // Effect<Array<string>>)
Getting data in and out. Conversion is where accidental copies and accidental sharing happen:
Direction
Function
Cost and sharing
In
Chunk.fromIterable(xs)
Materialises a non-array iterable once; an array input is wrapped as-is, not copied, and a Chunk input is returned unchanged
Wraps the array without copying — the explicit spelling of the same sharing
In
Chunk.make(...) / Chunk.of(a)
Fresh NonEmptyChunk
Out
Chunk.toReadonlyArray(chunk)
Returns the (cached) backing array; no copy once materialised
Out
Chunk.toArray(chunk)
A mutable copy you own
A chunk built from an array aliases that array, so mutating the source afterwards changes the chunk (xs[0] = 99 shows up in both forms above). Copy first (Chunk.fromIterable([...xs])) when the source outlives the call and may still be written to. Both toArray and toReadonlyArray keep non-emptiness in the type: a NonEmptyChunk<A> converts to a non-empty array type. Chunks compare by value — Equal.equals(Chunk.make(1, 2), Chunk.make(1, 2)) is true — and count arguments (take, drop, ...) follow the normalisation rule described under Array. Chunk.get floors a fractional index and treats NaN or an infinite index as out of bounds (Option.none()); getUnsafe throws for those.
Use when accumulating many small pieces and avoiding repeated array copies — especially in stream processing, recursive algorithms, or custom collectors.
Official guide: Chunk (it says fromIterable copies its input; that is only true for non-array iterables).
Immutable key-value map backed by a Hash Array Mapped Trie (HAMT). Lookup, insert, and delete are O(log 32 n) — effectively constant for practical sizes. Keys are hashed and compared via Effect's Equal/Hash protocol — structural equality, not reference equality.
Mental model.HashMap is to JavaScript's Map what Array is to a mutable array — same shape, fully immutable, pipe-friendly. Keys are compared with Equal.equals, which in Effect 4 is structural by default: two plain object literals, two arrays, two instances of the same Data.Class, or two Schema-decoded structs with the same contents are the same key (a Data.Class instance is not equal to a bare literal with the same fields, because prototype keys such as pipe take part in the comparison). Reach for a custom [Equal.symbol] / [Hash.symbol] only when identity should be a subset of the fields.
Self-contained source · Type-checked
ts
import { HashMap, Data, Option, pipe } from "effect"// Use an Employee value-object as a HashMap key — two instances with identical// fields are the same key. `Data.Class` is used here for the constructor and// `.pipe`; two plain `{ id, name, ... }` literals would dedupe the same way.class Employee extends Data.Class<{ readonly id: string readonly name: string readonly departmentId: string readonly level: number}> {}const alice1 = new Employee({ id: "e1", name: "Alice", departmentId: "d1", level: 4 })const alice2 = new Employee({ id: "e1", name: "Alice", departmentId: "d1", level: 4 })// alice1 !== alice2 by reference, but Equal.equals(alice1, alice2) is true// Store per-employee comp-band allocationslet allocations = HashMap.empty<Employee, number>()allocations = HashMap.set(allocations, alice1, 8_000) // merit raise amount// alice2 has the same fields → lookup succeeds even though it's a different instanceconsole.log(HashMap.get(allocations, alice2)) // Option.some(8000)// Build a department → merit budget mapconst meritBudgets: HashMap.HashMap<string, number> = HashMap.make( ["Engineering", 250_000], ["Design", 120_000], ["Product", 80_000])// Map: apply a 5% uplift to every department budgetconst uplifted = pipe( meritBudgets, HashMap.map((budget) => Math.round(budget * 1.05)))// Filter to departments with budget > $100kconst largeBudgets = pipe( uplifted, HashMap.filter((budget) => budget > 100_000))// HashMap { Engineering: 262500, Design: 126000 }// Fold into a total merit poolconst totalPool = HashMap.reduce(meritBudgets, 0, (acc, budget) => acc + budget)// 450000// Bulk update via mutate (scoped local mutation — still returns immutable)const updated = HashMap.mutate(meritBudgets, (draft) => { HashMap.set(draft, "Legal", 50_000) HashMap.remove(draft, "Product")})
Tip: Plain objects already work as keys. Implement both [Equal.symbol] and [Hash.symbol] (see Equal) when only some fields define identity, and keep the law: equal values must always produce the same hash.
Warning: Hashes are cached per object, so a key must not change after it has been hashed. Mutating a field of an object that is already a HashMap key or HashSet member strands the entry: a structurally equal lookup no longer finds it. Treat anything you put in a hash collection as frozen.
Use when you need an immutable key-value store, especially with value-object keys.
Immutable set backed by the same HAMT internals as HashMap. Membership tests and set-algebraic ops (union, intersection, difference, isSubset) use structural Equal/Hash. Two structurally equal items (same fields, different references) count as one member.
Structural membership needs no wrapper. Plain object literals — and therefore values decoded from a Schema.Struct — dedupe on their own; a native Set does not, because it ignores Equal and compares references. The flip side: own string and symbol keys participate, including non-enumerable ones, so an incidental field (a request id, a fetched-at timestamp) makes two records of the same entity distinct. When identity is narrower than the shape, project to the identifying fields first or give the class a custom Equal/Hash.
Self-contained source · Type-checked
ts
import { HashSet } from "effect"// Native Set compares references; HashSet compares structureconst nativeSize = new Set([{ id: "e1" }, { id: "e1" }]).size // 2const hashSetSize = HashSet.size(HashSet.make({ id: "e1" }, { id: "e1" })) // 1// An incidental field defeats dedupe — hidden own fields also countconst withNoise = HashSet.make( { id: "e1", requestId: "r-1" }, { id: "e1", requestId: "r-2" })const noisySize = HashSet.size(withNoise) // 2
Self-contained source · Type-checked
ts
import { HashSet, Data, pipe } from "effect"// Track which employees are included in the current merit cycleclass EmployeeRef extends Data.Class<{ id: string }> {}const cycleA = HashSet.make( new EmployeeRef({ id: "e1" }), new EmployeeRef({ id: "e2" }), new EmployeeRef({ id: "e3" }))const cycleB = HashSet.make( new EmployeeRef({ id: "e2" }), new EmployeeRef({ id: "e3" }), new EmployeeRef({ id: "e4" }))// Employees in both cycles (reviewed twice — flag for audit)const inBoth = HashSet.intersection(cycleA, cycleB)// HashSet { EmployeeRef("e2"), EmployeeRef("e3") }// All employees touched by either cycleconst allTouched = HashSet.union(cycleA, cycleB)// HashSet { e1, e2, e3, e4 }// Employees only in cycle A (e.g., left before cycle B opened)const onlyA = HashSet.difference(cycleA, cycleB)// HashSet { EmployeeRef("e1") }// Adding a structurally-equal element is a no-opconst deduped = pipe(cycleA, HashSet.add(new EmployeeRef({ id: "e1" })))console.log(HashSet.size(deduped)) // still 3// Iterate and collect IDsconst ids = pipe( allTouched, HashSet.map((ref) => ref.id), (set) => Array.from(set))
Key APIs: empty / make / fromIterable, add / remove / has, union / intersection / difference / isSubset, map / filter / some / every / reduce, size / isEmpty
Immutable or mutable?HashSet returns a new set per change, which makes it safe to share across fibers, keep in a Ref, or return from a function. MutableHashSet updates in place and is the cheaper choice for building a set inside one synchronous loop. Converting to an array (Array.from(set)) copies every element, so do it once at the boundary, not inside a hot loop.
Use when you need set semantics (deduplication, union/intersection) on value objects or an immutable Set.
Immutable prefix tree mapping string keys to values. Structurally like HashMap<string, V> but with first-class prefix operations: enumerate all keys starting with a given prefix, or find the longest stored key that is a prefix of a query string. Iteration yields [key, value] pairs in alphabetical order.
Mental model. Autocomplete index, URL router, or command-completion table — any use case where lookups cluster around common prefixes.
Self-contained source · Type-checked
ts
import { Trie, Array as Arr } from "effect"// Employee-name autocomplete for the HR search box.// Keys are lowercase full names; values are employee IDs.const nameTrie = Trie.make( ["alice johnson", "e1"], ["alice kim", "e7"], ["bob martin", "e2"], ["carol nguyen", "e3"], ["carlos mendez", "e9"], ["dave patel", "e4"])// Exact lookup by full nameconsole.log(Trie.get(nameTrie, "alice johnson")) // Option.some("e1")// All names that start with what the user has typed so farconst suggestions = Arr.fromIterable(Trie.keysWithPrefix(nameTrie, "alice"))// ["alice johnson", "alice kim"] (alphabetical)// All entries under "car" — useful for typeahead with result IDsconst carEntries = Arr.fromIterable(Trie.entriesWithPrefix(nameTrie, "car"))// [["carlos mendez", "e9"], ["carol nguyen", "e3"]] (alphabetical: "carl" < "caro")// Longest-prefix match — find an employee whose name is a prefix of a longer queryconst matched = Trie.longestPrefixOf(nameTrie, "carol nguyen (engineering)")// Option.some(["carol nguyen", "e3"])// Build an approval-path trie: keys are org-path strings, values are approver IDsconst approvalTrie = Trie.make( ["eng", "vp-eng"], ["eng/backend", "mgr-backend"], ["eng/frontend", "mgr-frontend"], ["design", "vp-design"])const engApprovers = Arr.fromIterable(Trie.keysWithPrefix(approvalTrie, "eng"))// ["eng", "eng/backend", "eng/frontend"]
The empty string is an ordinary key: Trie.insert(trie, "", value) stores it, get, modify, remove, and iteration see it, and longestPrefixOf returns it when no longer stored key is a prefix of the query. An iterator obtained from a trie continues from its current position when iterated again rather than restarting.
Use when keys are strings and prefix-based lookup is a core operation.
Typed graph with directed and undirected support, user-defined node and edge data, and a broad algorithm set: DFS/BFS/topological traversal, shortest paths (Dijkstra, A*, Bellman-Ford, Floyd-Warshall), path enumeration, cycle witnesses, connectivity analysis, minimum spanning forests, transitive reduction, bipartite matching, and maximum flow / minimum cut. Nodes identified by NodeIndex (allocated number); edges by EdgeIndex.
Mental model. Create with Graph.directed(mutate => ...) or Graph.undirected(mutate => ...). The callback receives a mutable snapshot; the result snaps back to immutable when it returns. For incremental updates, use Graph.mutate(graph, draft => ...).
Self-contained source · Type-checked
ts
import { Graph, Array as Arr } from "effect"// Model the org reporting hierarchy as a directed graph.// Nodes hold employee names; edges point from manager to direct report.const orgGraph = Graph.directed<string, void>((g) => { const ceo = Graph.addNode(g, "CEO") const vpEng = Graph.addNode(g, "VP Engineering") const vpDes = Graph.addNode(g, "VP Design") const mgrBe = Graph.addNode(g, "Mgr Backend") const mgrFe = Graph.addNode(g, "Mgr Frontend") const alice = Graph.addNode(g, "Alice") const carol = Graph.addNode(g, "Carol") const bob = Graph.addNode(g, "Bob") Graph.addEdge(g, ceo, vpEng, undefined) Graph.addEdge(g, ceo, vpDes, undefined) Graph.addEdge(g, vpEng, mgrBe, undefined) Graph.addEdge(g, vpEng, mgrFe, undefined) Graph.addEdge(g, mgrBe, alice, undefined) Graph.addEdge(g, mgrBe, carol, undefined) Graph.addEdge(g, vpDes, bob, undefined)})// Topological order — valid top-down traversal for approval-chain evaluationconst topo = Graph.topo(orgGraph)const order = Arr.fromIterable(Graph.values(topo))// ["CEO", "VP Engineering", "VP Design", "Mgr Backend", "Mgr Frontend", ...]// DFS from the CEO node (index 0) — walk the approval chain depth-firstconst dfsWalker = Graph.dfs(orgGraph, { start: [0], direction: "outgoing" })const visited = Arr.fromIterable(Graph.values(dfsWalker))// Shortest approval-chain path between two employees.// Re-build with numeric edge weights (hierarchy levels) for Dijkstra.const weightedOrg = Graph.directed<string, number>((g) => { const ceo = Graph.addNode(g, "CEO") const vpEng = Graph.addNode(g, "VP Engineering") const mgr = Graph.addNode(g, "Mgr Backend") const alice = Graph.addNode(g, "Alice") Graph.addEdge(g, ceo, vpEng, 1) Graph.addEdge(g, vpEng, mgr, 1) Graph.addEdge(g, mgr, alice, 1)})const result = Graph.dijkstra(weightedOrg, { source: 0, // CEO target: 3, // Alice cost: (edgeData) => edgeData})// Option.some({ path: [0, 1, 2, 3], edges: [0, 1, 2], distance: 3, costs: [1, 1, 1] })// Sanity check — no circular reporting relationshipsconsole.log(Graph.isAcyclic(orgGraph)) // true// Export to Mermaid for HR dashboard visualisationconst diagram = Graph.toMermaid(orgGraph, { nodeLabel: (name) => name})
Traversal — dfs, bfs, dfsPostOrder, topo — all return lazy NodeWalker iterators. Traversal accepts a radius limit and directed graphs can be explored with direction: "outgoing" | "incoming" | "undirected". externals(graph, { direction }) walks the sources or sinks.
Local queries — neighbors / successors / predecessors for adjacent nodes; incidentEdges, outgoingEdges, incomingEdges, and edgesBetween(graph, source, target) for edge indexes (parallel edges are all returned); degree for undirected graphs and inDegree / outDegree for directed ones.
Reachability and connectivity — hasPath(graph, source, target, { direction }) answers yes/no without building a path; unweightedDistances(graph, source) returns a Map of hop counts. Whole-graph predicates are kind-specific: isConnected and isTree (undirected), isWeaklyConnected and isStronglyConnected (directed). The partitions behind them are connectedComponents, weaklyConnectedComponents, and stronglyConnectedComponents; bridges, articulationPoints, and biconnectedComponents find the single points of failure of an undirected graph.
Cycles — isAcyclic is the boolean check; findCycle returns Option<{ path, edges }>, a concrete witness whose path repeats its first node at the end. Use the witness in an error message instead of reporting "there is a cycle somewhere". isBipartite checks two-colorability of an undirected graph.
Paths — dijkstra for weighted shortest paths with non-negative costs, astar when a heuristic can guide the search, bellmanFord when costs may be negative, floydWarshall for all pairs. A PathResult is { path, edges, distance, costs }: node indexes, the traversed edge indexes, the numeric total, and the original edge data along the route. All of them return Option.none() (or Infinity / null entries for floydWarshall) when the target is unreachable. simplePaths(graph, { source, target, limit }) lazily enumerates loop-free routes and allShortestPaths(graph, { source, target, cost, limit }) enumerates every route tied for the minimum; both return an iterable PathWalker, and because the number of simple paths can be exponential, pass a limit unless the graph is known to be small.
Optimisation — minimumSpanningForest(graph, cost) (undirected, Kruskal; disconnected inputs give a forest), transitiveReduction(dag) (drops every edge implied by a longer route), maximumBipartiteMatching(graph) (largest set of disjoint pairs, as { left, right, edge }), and maximumFlow / minimumCut ({ source, target, capacity } on a directed graph; maximumFlow reports per-edge flows, minimumCut the crossing edges plus the node partition on each side).
Composition and sets — make(kind), compose, intersection, difference, symmetricDifference, complement, and sum build graphs from graphs. neighborhood(graph, node, { radius, direction }) returns the local subgraph around a node. These operations preserve directed/undirected kind and remap node indexes, so do not assume input indexes survive in the result. inducedSubgraph(graph, nodeIndexes), minimumSpanningForest, and transitiveReduction are the index-preserving exceptions: surviving nodes and edges keep their original indexes, so results can be joined back to the source graph.
Bulk mutation — inside Graph.mutate, removeNodes(draft, indexes) and removeEdges(draft, indexes) delete in one pass; missing and duplicate indexes are ignored, and removing a node removes its incident edges. A callback that is transforming a graph (mapNodes, filterEdges, ...) may not mutate that same graph — doing so throws GraphError.
Snapshots — Graph.toSnapshot(graph) produces plain data { type, nodes: [{ index, data }], edges: [{ index, source, target, data }] } and Graph.fromSnapshot(snapshot) rebuilds an equal graph with the same indexes (Equal.equals holds across the round trip). This is the persistence and wire shape; Schema.Graph(kind, nodeSchema, edgeSchema) is the matching codec. fromSnapshot throws GraphError for out-of-order indexes or an edge whose endpoint is missing. toJSON() is an inspection summary, not this format.
Export — toGraphViz for DOT format, toMermaid for Mermaid diagram syntax — great for org-chart docs and debugging.
Typing a parameter — accept any immutable graph as Graph.Graph<N, E, Graph.Kind>. There is no separate Graph.Proto interface to name.
Warning: Graph functions are synchronous and throwGraph.GraphError (a Data.TaggedError) instead of returning it: a missing node index, a kind mismatch (degree on a directed graph, maximumFlow on an undirected one), a negative or NaN Dijkstra cost, arithmetic that leaves the finite number range, or a negative cycle that affects the bellmanFord target (floydWarshall rejects any negative cycle). Option.none() is reserved for "unreachable". At an Effect boundary, wrap the call in Effect.try and keep the GraphError as a typed failure.
Weighted consistent-hashing ring. Register nodes (any value implementing PrimaryKey), each with an optional weight. Route string keys to nodes via HashRing.get(ring, key) (returns A | undefined), or precompute a balanced shard distribution with HashRing.getShards(ring, shardCount).
Mental model. A sorted number line of 32-bit hash points. Each node gets weight × baseWeight virtual points. A lookup binary-searches the insertion position and chooses the nearer of the surrounding points (at an outer boundary it uses the nearest endpoint); it does not always choose the next clockwise point. When a node joins or leaves, nearby keys are the ones most likely to remap. The ring is mutable; add/addMany/remove mutate and return the same instance.
Self-contained source · Type-checked
ts
import { HashRing, PrimaryKey } from "effect"// Payroll workers — each one processes a shard of the employee population.// Nodes must implement PrimaryKey (a string identity protocol).class PayrollWorker implements PrimaryKey.PrimaryKey { readonly workerId: string readonly region: string constructor(workerId: string, region: string) { this.workerId = workerId this.region = region } [PrimaryKey.symbol](): string { return this.workerId }}const w1 = new PayrollWorker("worker-1", "us-east")const w2 = new PayrollWorker("worker-2", "us-west")const w3 = new PayrollWorker("worker-3", "eu-west")// Create ring with default baseWeight=128 virtual nodes per unit weightconst ring = HashRing.make<PayrollWorker>()HashRing.addMany(ring, [w1, w2, w3])// Route any employee ID to the responsible payroll workerconst owner1 = HashRing.get(ring, "employee:e1") // PayrollWorker | undefinedconst owner2 = HashRing.get(ring, "employee:e42") // PayrollWorker | undefined// Give w1 twice the load — it handles more employeesHashRing.addMany(ring, [w1], { weight: 2 })// Precompute shard ownership for 256 shards (e.g. for a Cluster entity map)const shards = HashRing.getShards(ring, 256)// Array<PayrollWorker> | undefined — shards[i] is the owner of shard i// Remove a worker (employee keys remap minimally)HashRing.remove(ring, w3)
Tip: Nodes implement PrimaryKey via [PrimaryKey.symbol](): string.
Membership and mutation operations (add, addMany, has, and remove)
compare that key, so an equivalent node value targets the same ring member.
get and getShards answer different questions. get(ring, key) is a pure nearest-point lookup. getShards(ring, count) builds a balanced table: it first limits each node to its floored weight share of count (at least one shard), spilling to eligible nodes. Once all nodes reach those soft caps, remaining shards are assigned without exclusions; the share is not a hard maximum. A shard's owner is therefore not always the node get would pick for the same hash. Both return undefined for an empty ring. count is normalised like other Effect counts: fractions are floored, and NaN or a non-positive value yields an empty array. getShards is deterministic: the same nodes and weights always produce the same shard table regardless of the order in which nodes were added or removed (weights are summed in node-key order; hash ties are broken by node key).
Use when distributing work across a dynamic set of nodes where stable key-to-node assignments with minimal remapping are needed.
Helpers operating on plain JavaScript objects (Record<K, V> / ReadonlyRecord<K, V>). Collection transformations return new records; observers, collect, and partition have their declared result shapes. The low-level assignProperty intentionally mutates its target and returns void. Provides map, filter, filterMap, reduce, partition, collect (map + collect values into an array), and set operations (union, intersection, difference) over record values.
Self-contained source · Type-checked
ts
import { Record, Result, pipe } from "effect"// Department merit budgets — a plain Record<string, number>const budgets: Record<string, number> = { Engineering: 250_000, Design: 120_000, Product: 80_000, Legal: 40_000,}// Map: compute the per-headcount allocation given headcountsconst headcounts: Record<string, number> = { Engineering: 25, Design: 12, Product: 8, Legal: 4,}const perHead = Record.map(budgets, (budget, dept) => Math.round(budget / (headcounts[dept] ?? 1)))// { Engineering: 10000, Design: 10000, Product: 10000, Legal: 10000 }// Filter to departments with budgets above $100kconst largeDepts = Record.filter(budgets, (b) => b > 100_000)// { Engineering: 250000, Design: 120000 }// Collect to a summary array for a reportconst summary = Record.collect(budgets, (dept, budget) => `${dept}: $${budget.toLocaleString()}`)// ["Engineering: $250,000", "Design: $120,000", ...]// Partition: split into under-budget and over-budget departments// (budget ceiling = $150k). partition returns [passes, fails].const [withinCeiling, overBudget] = Record.partition(budgets, (b) => b <= 150_000 ? Result.succeed(b) : Result.fail(b))// Merge approved supplemental budgets (right/combiner wins on conflict)const supplemental: Record<string, number> = { Engineering: 30_000, Sales: 60_000 }const merged = Record.union(budgets, supplemental, (base, extra) => base + extra)// { Engineering: 280000, Design: 120000, Product: 80000, Legal: 40000, Sales: 60000 }// Keys are typed when possibleconst depts: Array<string> = Record.keys(budgets)
Record.fromIterableBy(items, keyOf) is the concise dual constructor for indexing values by a derived string/symbol key. When assigning a dynamic key into a mutable object, use Record.assignProperty(target, key, value): unlike target[key] = value, it safely treats "__proto__" as an ordinary own property instead of invoking the legacy prototype setter.
Use when you have a plain object and need to map, filter, or fold its values without writing manual Object.fromEntries(Object.entries(o).map(...)) chains.
Typed tuple helpers — construct, pick, omit, evolve, map, rename indices, and build structural Equivalence and Order for fixed-length tuples. All operations preserve the exact tuple type.
Self-contained source · Type-checked
ts
import { Tuple, Order } from "effect"// A comp-band snapshot as a tuple: [level, minSalary, maxSalary]const band = Tuple.make(4, 130_000, 160_000)// inferred type: [4, 130000, 160000]; annotate explicitly to widen the literals// Pick or omit positions — extract just the salary range (positions 1 & 2)const range = Tuple.pick(band, [1, 2]) // [130000, 160000]const noLevel = Tuple.omit(band, [0]) // [130000, 160000]// Append an element (non-mutating) — attach a currency codeconst withCcy = Tuple.appendElement(band, "USD") // [4, 130000, 160000, "USD"]// Structural Order — compare bands lexicographically: level first, then min salary// Use Order.Number (capitalised) for numeric orderingsconst BandOrder = Tuple.makeOrder([Order.Number, Order.Number, Order.Number])console.log(BandOrder([3, 100_000, 130_000], [4, 130_000, 160_000])) // -1 (level 3 < 4)// Evolve individual slots with typed transformsconst adjusted = Tuple.evolve(band, [ undefined, // index 0 (level) unchanged (min) => Math.round(min * 1.03), // 3% min uplift (max) => Math.round(max * 1.03) // 3% max uplift])// [4, 133900, 164800]
Tuple.evolve types each slot from its transform: a slot whose transform is undefined keeps its element type, and a slot whose transform may be undefined at the type level (an optional function) is typed as the union of the transformed and the original element, matching what happens at runtime.
Use with fixed-arity tuples for type-safe manipulation — common in codegen outputs, multi-field keys, or zipped pairs.
Helpers for typed plain objects: pick / omit fields, evolve individual values, assign additional fields, renameKeys, and derive structural Equivalence and Order from per-field comparators. All return new plain objects — no mutation, no class wrapping.
Mental model. Object surgery kit. Where Record iterates all values homogenously, Struct operates on known, typed fields. evolve takes a partial transformer map; only listed fields are changed; the rest pass through with correct types preserved.
Self-contained source · Type-checked
ts
import { Struct, Order, Equivalence, pipe } from "effect"type Employee = { readonly id: string readonly name: string readonly departmentId: string readonly level: number readonly baseSalary: number}const alice: Employee = { id: "e1", name: "Alice", departmentId: "d-eng", level: 4, baseSalary: 140_000}// Pick specific fields — useful when sending to a public API or UIconst publicProfile = Struct.pick(alice, ["id", "name", "level"])// { id: "e1", name: "Alice", level: 4 }// Omit salary for a non-confidential exportconst nonConfidential = Struct.omit(alice, ["baseSalary"])// { id: "e1", name: "Alice", departmentId: "d-eng", level: 4 }// Evolve specific fields — apply a merit increase and a promotionconst promoted = pipe( alice, Struct.evolve({ level: (l) => l + 1, // L4 → L5 baseSalary: (s) => Math.round(s * 1.12) // 12% raise }))// { id: "e1", name: "Alice", departmentId: "d-eng", level: 5, baseSalary: 156800 }// Assign additional fields (like Object.assign but typed and immutable)const withCycle = Struct.assign(alice, { meritCycle: "2026-Q1" as const })// { ...alice, meritCycle: "2026-Q1" }// Rename keys for an external system (e.g. HRIS field names)const hrisPayload = Struct.renameKeys(alice, { id: "employeeId", name: "fullName"})// { employeeId: "e1", fullName: "Alice", departmentId: "d-eng", ... }// Derive structural Equivalence using Equivalence.String and Equivalence.Number// (capitalised — Equivalence.string does not exist)const EmployeeEq = Struct.makeEquivalence({ id: Equivalence.String, name: Equivalence.String, departmentId: Equivalence.String, level: Equivalence.Number, baseSalary: Equivalence.Number,})console.log(EmployeeEq(alice, { ...alice })) // true — same field values// Derive lexicographic Order: sort employees by level, then by name (both ascending;// wrap a field's Order in Order.flip for descending).// Use Order.Number and Order.String (capitalised).const EmployeeOrder = Struct.makeOrder({ level: Order.Number, name: Order.String,})
Tip: Use Struct.evolve for heterogeneous, known-shape objects where each field has its own transformation; use Record.map for homogeneous string-keyed records.
Use to pick, omit, rename, or selectively transform fields on a typed plain object — especially at API boundaries, in mappers, or when building structural comparators.
Combinators for any value implementing [Symbol.iterator] — arrays, strings, generators, sets, custom sequences. Transformations such as map, filter, and take return lazy iterables with no materialization until traversal. Terminal and aggregating operations such as reduce, size, groupBy, and forEach traverse eagerly and may allocate their complete result.
Self-contained source · Type-checked
ts
import { Iterable, Option, pipe, Array as Arr } from "effect"// Generate all salary levels from 1 to infinity, lazily// Iterable.makeBy(f, options?) — f receives the index; options.length caps itconst allLevels = Iterable.makeBy((n) => n + 1) // 1, 2, 3, ...const seniorLevels = Iterable.filter(allLevels, (l) => l >= 4)const firstThree = Iterable.take(seniorLevels, 3)console.log(Arr.fromIterable(firstThree)) // [4, 5, 6]// Build a vesting schedule: (month, vestedShares) pairs// Unfold: seed is [month, totalGranted]; emit (month, shares) each stepconst vestingSchedule = Iterable.unfold( [0, 10_000] as [number, number], ([month, remaining]) => month < 48 ? Option.some([ [month + 1, Math.round(10_000 * (month + 1) / 48)] as const, [month + 1, remaining] as [number, number] ] as const) : Option.none())const first4Months = Arr.fromIterable(Iterable.take(vestingSchedule, 4))// [[1, 208], [2, 417], [3, 625], [4, 833]]// Group employees by department (eager — returns a materialized record of NonEmptyArray)const employees = [ { name: "Alice", dept: "Engineering" }, { name: "Bob", dept: "Design" }, { name: "Carol", dept: "Engineering" },]const byDept = Iterable.groupBy(employees, (e) => e.dept)// { Engineering: [Alice, Carol], Design: [Bob] }// Cartesian product of levels × rating labels — enumerate all comp scenariosconst levels = [3, 4, 5]const ratings = ["exceeds", "meets", "below"] as constconst scenarios = Arr.fromIterable(Iterable.cartesian(levels, ratings))// [[3,"exceeds"],[3,"meets"],[3,"below"],[4,"exceeds"],...]
Iterable.groupBy shares Array.groupBy's typing: a literal-union key selector yields a record whose known keys are optional (see Array), and count arguments such as take(n) and drop(n) are normalised the same way.
Note: Iterable-to-iterable transformations preserve lazy traversal. Operations that return a scalar, array, record, map, or set consume the source; consult the return type rather than assuming every Iterable function is lazy. Corresponding Array transformations work eagerly on materialized arrays.
Use when you want lazy, composable iteration over any sequence without forcing it into an array.
Type-level brand: NonEmptyIterable<A> extends Iterable<A> and carries readonly [nonEmpty]: A as a phantom field. Non-emptiness is visible at the type level with zero runtime cost — purely a TypeScript narrowing mechanism.
One runtime helper: NonEmptyIterable.unprepend, which safely destructures the head element and the remaining iterator. NonEmptyChunk and NonEmptyArray both satisfy NonEmptyIterable.
Self-contained source · Type-checked
ts
import { NonEmptyIterable, Chunk } from "effect"// A confirmed non-empty list of employees in a merit cycle// NonEmptyChunk satisfies NonEmptyIterableconst cycle: Chunk.NonEmptyChunk<string> = Chunk.make("e1", "e2", "e3")// Safely extract the first employee and the rest — no Option neededconst [firstId, rest]: [string, Iterator<string>] = NonEmptyIterable.unprepend(cycle)console.log(firstId) // "e1"console.log([...{ [Symbol.iterator]: () => rest }]) // ["e2", "e3"]// Write a function that requires at least one employee in the cyclefunction processLeadEmployee( employees: NonEmptyIterable.NonEmptyIterable<string>): string { const [lead] = NonEmptyIterable.unprepend(employees) return lead}
Use as a parameter type for functions requiring at least one element; call unprepend to safely access the first element without an Option dance.
Effect ships a full standard library — structural equality, comparators, branded types, pattern matching, optics, arbitrary-precision decimals, and more — all composable with each other and the rest of the ecosystem.
Official guides:Pattern Matching, Branded Types, Equal, Hash, Equivalence, Order, BigDecimal, Dual APIs; each is linked again, with any caveat, in the section it belongs to. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Exhaustive, composable pattern matching for TypeScript. Type-safe switch that narrows unions automatically, enforces case coverage, and composes through pipe.
Mental model. Start with Match.type<YourUnion>() (reusable matcher) or Match.value(someValue) (one-shot). Add arms with when, tag, discriminator, etc. — each narrows the remaining union. When remaining union is never, seal with exhaustive; otherwise use orElse for a catch-all. Closing Match.type or Match.fn produces a reusable function; closing Match.value produces the result for the already-supplied value.
Self-contained source · Type-checked
ts
import { Match, pipe } from "effect"type PerformanceRating = | { _tag: "Exceeds"; percentileRank: number } | { _tag: "Meets" } | { _tag: "Below"; pipPlan: string }// Build a reusable merit-multiplier function — type inferred as (rating: PerformanceRating) => numberconst meritMultiplier = pipe( Match.type<PerformanceRating>(), Match.tag("Exceeds", ({ percentileRank }) => percentileRank >= 90 ? 0.05 : 0.04), Match.tag("Meets", () => 0.02), Match.tag("Below", () => 0), Match.exhaustive // compile error if any tag is unhandled)meritMultiplier({ _tag: "Exceeds", percentileRank: 95 }) // 0.05meritMultiplier({ _tag: "Meets" }) // 0.02
One-shot matching. Use Match.value when you have a value in hand:
Structural patterns.when accepts any predicate or literal pattern — match by shape, not just tag:
For a known object input, Match.when, whenOr, whenAnd, and not reject pattern keys absent from every input variant, catching misspelled fields at compile time. Tuple patterns match a prefix, not an exact array length: matching [1] against a variadic array narrows the first element but preserves the remaining elements' original type. An array shorter than the pattern never matches.
Built-in predicates (usable at the top level or nested inside an object pattern): Match.string, Match.nonEmptyString, Match.number, Match.boolean, Match.bigint, Match.symbol, Match.date, Match.record, Match.null, Match.undefined, Match.defined, Match.any, Match.is(...literals), Match.instanceOf(Class). Any (value) => boolean also works as a field pattern: { level: (n) => n >= 3 }.
Match.tag("Exceeds", "Meets", handler) handles multiple tags in one arm. Match.not(pattern, handler) matches everything that does NOT match the pattern. Match.tagStartsWith("Comp", handler) useful for namespaced tags. Match.withReturnType<R>() pins the return type of every arm — it must be the first step of the pipeline; placed later, TypeScript does not enforce the return type correctly.
Literal unions as a handler table.Match.literals({ ... }) (unstable) maps finite string or number literals to handlers, each receiving its literal; handled literals leave the remaining input, so close the matcher with orElse or another arm. Match.literalsExhaustive({ ... }) (unstable) requires a handler for every remaining member and closes the matcher, so a new literal, a widened string/number, or any non-literal member is a compile error. Keys that are not members of the input are rejected, and so is a union holding both a number and its string spelling (1 | "1"), since they share one runtime key.
Conditional handler tables. In Match.tags, Match.discriminators, and Match.literals, a key whose handler is undefined (for example { Meets: canPromote ? promote : undefined }) is skipped at runtime, and a key whose handler type admits undefined does not count as handled. Those members stay in the remaining input, so a later arm, orElse, or exhaustive must still account for them.
Matching on several arguments.Match.fn builds a reusable matcher from a selector over the function's arguments; handlers receive the narrowed selected value first, then the original arguments:
Self-contained source · Type-checked
ts
import { Match } from "effect"type Rating = "exceeds" | "meets" | "below"const meritNote = Match.fn((currency: string, rating: Rating) => rating).pipe( Match.when("exceeds", (_rating, currency) => `top-of-band review in ${currency}`), Match.when("meets", (_rating, currency) => `standard merit in ${currency}`), Match.when("below", () => "no adjustment"), Match.exhaustive)meritNote("USD", "meets") // "standard merit in USD"
The finalizers of a Match.value(x) pipeline (orElse, option, result, exhaustive) type-check even when the type of x contains a generic type parameter, which makes one-shot matching usable inside generic functions.
The input is a closed union and every member has a policy
Match.tagsExhaustive({ ... })
Compile error for a missing or unknown tag
The same, written as one handler table
Match.literalsExhaustive({ ... })
Compile error for a missing or unknown literal
The same table over a string/number literal union
Match.orElse(fallback)
The fallback's value
A deliberate default exists; never as a way to silence exhaustive
Match.option
Option.none()
A partial matcher feeding Option combinators
Match.result
Result.fail(input) — the unmatched input
The caller should see what was not handled
Self-contained source · Type-checked
ts
import { Match } from "effect"type Reviewer = { readonly role: "admin" | "analyst" | "viewer"; readonly level: number }// Partial matcher: predicates nest inside object patterns, `option` closes itconst approvalLimit = Match.type<Reviewer>().pipe( Match.withReturnType<number>(), // first step, or it does not constrain the arms Match.when({ role: "admin" }, () => 50_000), Match.when({ role: "analyst", level: (n) => n >= 3 }, () => 10_000), Match.option)approvalLimit({ role: "admin", level: 1 }) // Option.some(50000)approvalLimit({ role: "viewer", level: 9 }) // Option.none()// Policy table over an error union: a new variant is a compile error right heretype RaiseError = | { readonly _tag: "BudgetExceeded"; readonly overBy: number } | { readonly _tag: "OutOfBand" } | { readonly _tag: "HrisUnavailable" }const httpStatus = Match.type<RaiseError>().pipe( Match.tagsExhaustive({ BudgetExceeded: () => 409, OutOfBand: () => 422, HrisUnavailable: () => 503 }))httpStatus({ _tag: "OutOfBand" }) // 422
Classify a whole union without a wildcard. When one boundary maps every member of a union to a policy — an HTTP status, a retry decision, a user-facing message — finish with Match.exhaustive or Match.tagsExhaustive, not a switch with default or a Match.orElse. A default branch silently assigns tomorrow's variant to today's fallback; the exhaustive form fails compilation exactly where the policy must be revisited. Completeness is mechanical, though: it proves every row exists, not that every row is right. The error-side of this practice lives in Effect error handling.
Use when exhaustively pattern-matching unions — discriminated unions, workflow state machines, error types — and you want the compiler to enforce coverage.
A typeclass for total ordering: Order<A> returns -1 | 0 | 1. All sorting, min/max, and clamp operations in Effect are backed by Order.
Mental model. Treat Order as a composable comparator. Built-ins for all primitives are Capitalized: Order.Number, Order.String, Order.Boolean, Order.Date, Order.BigInt.
Self-contained source · Type-checked
ts
import { Order, Array as Arr } from "effect"// Built-in primitives (Capitalized)const byNum = Order.Number // Order<number>const byStr = Order.String // Order<string>// Derive an order from a fieldconst byLevel = Order.mapInput(Order.Number, (e: { level: number }) => e.level)// Combine: primary sort by level, secondary sort by baseSalary within the same levelconst byLevelThenSalary = Order.combine( Order.mapInput(Order.Number, (e: { level: number; baseSalary: number }) => e.level), Order.mapInput(Order.Number, (e: { level: number; baseSalary: number }) => e.baseSalary))const employees = [ { name: "Ana", level: 3, baseSalary: 120_000 }, { name: "Ben", level: 2, baseSalary: 95_000 }, { name: "Cara", level: 3, baseSalary: 115_000 },]// Array.sort takes an Order directlyconst sorted = Arr.sort(employees, byLevelThenSalary)// [Ben(L2,$95k), Cara(L3,$115k), Ana(L3,$120k)]// Sort by CompBand level then by band label — Order.Struct builds a struct comparatorconst byBand = Order.Struct({ level: Order.Number, label: Order.String,})
Order.flip reverses sort direction. Order.Struct({ level: Order.Number, name: Order.String }) builds a struct comparator in one call. Array.sort(values, order) returns a new array; the native values.sort(...) mutates in place.
Helpers derived from an Order. Each takes the Order first and returns a function of the values: the comparison predicates isLessThan, isLessThanOrEqualTo, isGreaterThan, isGreaterThanOrEqualTo, plus min, max, clamp, and isBetween. clamp and isBetween take an options object, { minimum, maximum } — not positional bounds — and both ends are inclusive.
Self-contained source · Type-checked
ts
import { Order } from "effect"const band = { minimum: 90_000, maximum: 160_000 }Order.clamp(Order.Number)(185_000, band) // 160_000 (data-first)Order.clamp(Order.Number)(band)(185_000) // 160_000 (data-last, for pipe)Order.isBetween(Order.Number)(band)(160_000) // true — bounds are inclusiveOrder.max(Order.Number)(120_000, 95_000) // 120_000Order.isLessThan(Order.Number)(95_000, 120_000) // true
Use when sorting by multiple fields, finding min/max values, or clamping a value to a range.
The structural equality protocol. Equal.equals(a, b) compares any two values using deep structural comparison for plain objects, arrays, Maps, Sets, and Dates; falls back to [Equal.symbol] for custom types.
Mental model.Equal.equals(a, b) compares by value, not reference. Types built with Data and collection types (HashMap, HashSet) implement the Equal interface and use it internally for membership and lookup.
Implement Equal on custom classes by satisfying the Equal interface (which extends Hash):
Self-contained source · Type-checked
ts
import { Equal, Hash } from "effect"class Employee implements Equal.Equal { readonly id: string readonly name: string readonly level: number constructor(id: string, name: string, level: number) { this.id = id this.name = name this.level = level } [Equal.symbol](that: Equal.Equal): boolean { return that instanceof Employee && this.id === that.id } [Hash.symbol](): number { return Hash.string(this.id) }}const emp1 = new Employee("emp-001", "Alice", 3)const emp2 = new Employee("emp-001", "Alice", 3)const emp3 = new Employee("emp-002", "Bob", 2)Equal.equals(emp1, emp2) // true — same idEqual.equals(emp1, emp3) // false — different id
Structural is the default in Effect 4. Plain objects, arrays, Map, Set, Date, and instances of ordinary classes all compare by content, and NaN equals NaN. Data classes are about ergonomics — constructors, tags, yieldable errors — not about obtaining value equality. The comparison looks at keys and values, not at the constructor: prototype keys such as methods take part, so two instances of one class are equal when their fields are, while an instance with methods is not equal to a bare literal carrying the same fields. If exactly one operand implements Equal, the result is false. Implementing means holding a function under Equal.symbol (and Hash.symbol): parsed JSON that merely carries an "~effect/Equal" or "~effect/Hash" key is compared and hashed as ordinary data.
Hidden own fields count too. Default record equality compares own string and symbol keys, including non-enumerable ones. An incidental field such as a request id or a fetched-at timestamp makes two records of the same entity unequal. When identity is a subset of the shape, implement [Equal.symbol] and [Hash.symbol] over the identifying fields only, as Employee does above.
Binary data compares by content. Typed arrays, ArrayBuffers, and SharedArrayBuffers compare and hash by their bytes; an ArrayBuffer never equals a SharedArrayBuffer, and a detached buffer is equal only to itself. Use Bytes.Equivalence when you only need a byte comparison.
Mutable cells are not identity-keyed. A Ref or MutableRef has no Equal implementation of its own, so the structural default compares the value it currently holds: two cells holding 1 are Equal, hash alike, and collapse to one HashSet member. That comparison is cached, so it goes stale as soon as either cell is updated (see Compared values must stay frozen below). Never use a cell as a key or set member; when identity is the point, wrap it with Equal.byReference(cell), which the Ref and MutableRef functions still accept.
Compared values must stay frozen. Hashes are cached per object and comparison results per object pair, so mutating a value after its first comparison or first use as a key leaves stale answers behind. Build a new value instead.
Opting out.Equal.byReference(obj) returns a proxy that compares by identity and leaves obj untouched; Equal.byReferenceUnsafe(obj) marks obj itself, permanently and without a proxy.
Self-contained source · Type-checked
ts
import { Equal } from "effect"const recommendation = { employeeId: "emp-001", bps: 150 }Equal.equals(recommendation, { employeeId: "emp-001", bps: 150 }) // true — structural by defaultEqual.equals(NaN, NaN) // true// An incidental field makes "the same" record differentEqual.equals( { employeeId: "emp-001", requestId: "r-1" }, { employeeId: "emp-001", requestId: "r-2" }) // false// Identity semantics on demand; the original object is untouchedconst byIdentity = Equal.byReference(recommendation)Equal.equals(byIdentity, { employeeId: "emp-001", bps: 150 }) // falseEqual.equals(byIdentity, byIdentity) // true
Use when you need value-semantic equality on domain objects, want to use them as HashMap keys, or check membership in a HashSet.
The hashing half of the equality protocol. Hash.hash(value) returns a stable integer hash, using structural hashing for plain objects/arrays and delegating to [Hash.symbol]() for custom types.
Mental model. Rarely called directly unless implementing a custom Equal. Compose hashes with Hash.combine for good distribution:
Self-contained source · Type-checked
ts
import { Hash } from "effect"// Composing hashes for a composite key — e.g. (employeeId, cycleYear)const h = Hash.combine(Hash.string("emp-001"))(Hash.number(2025))// Helpers availableHash.string("analyst@example.com")Hash.number(3)Hash.array(["L3", "Engineering", "NYC"])Hash.structure({ departmentId: "eng", level: 3 }) // structureKeys over all own keysconst someObj = { employeeId: "emp-001" }Hash.random(someObj) // stable random hash per object identity
Hash first, then equals.Equal.equals and the hash collections compare hashes before anything else: different hashes prove inequality immediately, while equal hashes only mean "maybe" and trigger the full [Equal.symbol] comparison. Two rules follow. Equal values must hash equally, or lookups miss. And [Hash.symbol] may use a cheap, stable subset of the fields that [Equal.symbol] compares (hashing only the id is fine) but must never read a field that equality ignores. Hashes of objects are cached, which is one more reason to treat hashed values as immutable.
Hash values are not a stable wire format. They are small numeric fingerprints for in-process bucketing, not cryptographic digests, and the mixing Hash.combine and the structural hashers use is an implementation detail that can change between Effect versions. Never persist a hash, send it across a process boundary, or compare one computed by an old build against one computed by a new build — recompute instead.
Use when implementing [Hash.symbol]() on a custom class that also implements Equal.
A simple function type (a: A, b: A) => boolean with combinators for building custom equality predicates outside the Equal protocol.
Mental model. Where Equal is a protocol for arbitrary cross-type comparison, Equivalence is a typed comparator for a specific type — lighter when you don't need the full protocol. Built-ins are Capitalized: Equivalence.String, Equivalence.Number, Equivalence.Boolean, Equivalence.Date. Compose into struct and tuple comparators:
Self-contained source · Type-checked
ts
import { Equivalence } from "effect"// Primitive equivalences (Capitalized exports)Equivalence.String // case-sensitive exact matchEquivalence.Number // NaN-awareEquivalence.BooleanEquivalence.Date // by getTime()// Struct equivalence: compare comp bands by level and salary midpointconst eqCompBand = Equivalence.Struct({ level: Equivalence.Number, midSalary: Equivalence.Number,})eqCompBand({ level: 3, midSalary: 130_000 }, { level: 3, midSalary: 130_000 }) // true// Derive from an existing equivalence by projecting — compare employees by id onlyconst eqById = Equivalence.mapInput( Equivalence.String, (emp: { id: string }) => emp.id)
The contract. An Equivalence must be reflexive (eq(a, a)), symmetric (eq(a, b) implies eq(b, a)), and transitive. Array.dedupeWith, groupWith, and similar functions assume all three, so a hand-written Equivalence.make that breaks one (for example "within 5% of each other", which is not transitive) produces order-dependent results. Equivalence.strictEqual<A>() is the === instance for symbols and reference types, Equal.asEquivalence() adapts structural equality, and Schema.toEquivalence(schema) derives an instance from a schema instead of assembling one by hand.
Use when you need a custom equality predicate for deduplication, test assertions, or domain comparisons without implementing the full Equal interface.
The type Ordering = -1 | 0 | 1 — return value of any Order<A> comparator. Provides Ordering.reverse to flip a result and Ordering.match to branch on it. Mostly consumed by Order combinators internally; useful when implementing custom comparators combining multiple sub-comparisons.
Fragment · Type-checked with fixture
ts
import { Ordering } from "effect"// Combine two sub-results: primary ordering wins, fall back to secondary on tieconst combined: Ordering.Ordering = firstResult !== 0 ? firstResult : secondResultOrdering.reverse(-1) // 1Ordering.match(combined, { onLessThan: () => "lower band", onEqual: () => "same band", onGreaterThan: () => "higher band" })
An associative binary operation: combine(a, b) produces another value of the same type. Building block for combining two values into one.
Mental model. A Combiner<A> merges two As together. Carries no identity element — that is what Reducer adds. Note: Combiner.intercalate is curried — provide the separator first, then the base combiner.
Self-contained source · Type-checked
ts
import { Combiner, Number, String } from "effect"// Sum two department merit budgetsconst SumBudget = Combiner.make<number>((a, b) => a + b)SumBudget.combine(120_000, 95_000) // 215_000// By picking the smaller/larger according to an Order — useful for capping budgetsconst MinBudget = Combiner.min(Number.Order)const MaxBudget = Combiner.max(Number.Order)MinBudget.combine(120_000, 95_000) // 95_000MaxBudget.combine(120_000, 95_000) // 120_000// always keep the first / last valueconst First = Combiner.first<string>()const Last = Combiner.last<string>()// Intercalate: insert a separator between department codes// Note: intercalate is curried — separator first, then combinerconst CommaSep = Combiner.intercalate(",")(String.ReducerConcat)CommaSep.combine("HR", "ENG") // "HR,ENG"// Flip argument order (useful for non-commutative ops)const Prepend = Combiner.flip(Combiner.make<string>((a, b) => a + b))Prepend.combine("Engineering", "Senior ") // "Senior Engineering"
Use when folding a non-empty collection into one value. Use Reducer when the collection may be empty.
Combiner + an initialValue — enables folding empty collections. The initialValue acts as the identity element.
Mental model. Every primitive module ships ready-made reducers: Number.ReducerSum, Number.ReducerMultiply, String.ReducerConcat, Boolean.ReducerAnd, Boolean.ReducerOr, BigInt.ReducerSum. Roll your own with Reducer.make.
Self-contained source · Type-checked
ts
import { Reducer, Number } from "effect"// Custom reducer for summing merit budgetsconst BudgetSum = Reducer.make<number>((a, b) => a + b, 0)// Sum department merit budgets — returns 0 for an empty orgconst departments = [120_000, 95_000, 80_000, 150_000]const totalBudget = departments.reduce( (acc, n) => Number.ReducerSum.combine(acc, n), Number.ReducerSum.initialValue)// => 445_000BudgetSum.combine(120_000, 95_000) // 215_000BudgetSum.initialValue // 0// Flip reverses arg order (prepend instead of append)const Prepend = Reducer.flip(BudgetSum)
Use when folding potentially-empty collections of values or building the identity element for a Combiner.
Nominal typing for TypeScript. A Branded<string, "EmployeeId"> is a string at runtime but a distinct type at compile time.
Mental model. Two flavors: nominal (no runtime validation, type assertion only — use when trusting the source) and refined (validated on construction, throws or returns a Result on failure — use when invariants are needed).
Self-contained source · Type-checked
ts
import { Brand, Schema } from "effect"// ── Nominal brand (zero runtime cost) ────────────────────────────────────────type EmployeeId = string & Brand.Brand<"EmployeeId">const EmployeeId = Brand.nominal<EmployeeId>()const id: EmployeeId = EmployeeId("emp-001") // fine// const bad: EmployeeId = "emp-001" // type error — just a string// ── Refined brand (runtime validation) ───────────────────────────────────────// Money in cents: must be a non-negative integertype MoneyCents = number & Brand.Brand<"MoneyCents">const MoneyCents = Brand.make<MoneyCents>( (n) => (Number.isInteger(n) && n >= 0) || `Expected non-negative integer cents, got ${n}`)MoneyCents(12_500_00) // 1_250_000 as MoneyCents (represents $12,500.00)// MoneyCents(-1) // throws BrandError at runtime// Safe API — returns Result<MoneyCents, BrandError>const result = MoneyCents.result(95_000_00) // Result.succeed(...)const none = MoneyCents.option(-1) // Option.none()const ok = MoneyCents.is(10_000_00) // true// ── Using a Schema check ──────────────────────────────────────────────────────const NonNegativeInt = Brand.check<number & Brand.Brand<"NonNegativeInt">>(Schema.isInt())// ── Combining multiple brands ─────────────────────────────────────────────────// GrantShares must be a positive integer and below the authorized captype GrantShares = MoneyCents & Brand.Brand<"GrantShares">const GrantShares = Brand.all( MoneyCents, Brand.make<GrantShares>((n) => n <= 100_000 || "grant exceeds authorized share cap"))
Why brand at all. TypeScript is structural: an employeeId: string parameter happily accepts a department id, a cost-center code, or unvalidated user input, because all of them are string. A brand makes the mix-up a compile error without changing the runtime value.
Derive the combined type from the constructor. Build the constructor with Brand.all(...) first and let Brand.Brand.FromConstructor produce the type, so the two cannot drift apart. Brand.Branded<A, "Key"> is shorthand for A & Brand.Brand<"Key">.
Self-contained source · Type-checked
ts
import { Brand } from "effect"type Int = Brand.Branded<number, "Int">const Int = Brand.make<Int>((n) => Number.isInteger(n) || `Expected ${n} to be an integer`)type Positive = Brand.Branded<number, "Positive">const Positive = Brand.make<Positive>((n) => n > 0 || `Expected ${n} to be positive`)const ShareCount = Brand.all(Int, Positive)type ShareCount = Brand.Brand.FromConstructor<typeof ShareCount> // number & Brand<"Int"> & Brand<"Positive">const granted: ShareCount = ShareCount(5_000)const rejected = ShareCount.option(-1.5) // Option.none() — both checks fail, and both messages are reported
Failures surface as Brand.BrandError: a tagged, error-like value that wraps a SchemaIssue and does not extend JavaScript's Error, so instanceof Error is false — branch on _tag or prefer the .result / .option constructors. Brand.all runs every constituent check and reports all failures, not just the first. To use a brand as a field of a decoded payload, bridge it into a schema: Schema.brand("EmployeeId") brands a schema directly, and schema.pipe(Schema.fromBrand("ShareCount", ShareCount)) reuses an existing constructor's checks — see Schema.
Use to prevent primitive confusion — mixing EmployeeId with DepartmentId, salary cents with share counts, validated with raw strings — without wrapper classes at runtime.
Official guides: Branded Types (its illustrative Brand declaration uses a symbol key; brand keys are strings), Schema branded types.
Composable, typed lenses and prisms for reading and immutably updating nested data. An optic describes a path into a data structure; compose paths then call .get, .replace, or .modify.
Mental model. Four optic types: Optional (may fail to focus) is the base; Lens (always-present field focus) and Prism (optional branch focus) are independent specializations of it; Iso (lossless bijection) is both a Lens and a Prism. Compose left-to-right via method chaining from Optic.id<S>(). modify returns a function (s: S) => S — call the result with the data.
Self-contained source · Type-checked
ts
import { Optic } from "effect"type CompensationPlan = { readonly employeeId: string readonly base: { readonly annual: number; readonly currency: string } readonly equity: { readonly shares: number; readonly vestingMonths: number }}// Build a lens to a nested fieldconst annualBase = Optic.id<CompensationPlan>().key("base").key("annual")const plan: CompensationPlan = { employeeId: "emp-001", base: { annual: 120_000, currency: "USD" }, equity: { shares: 5_000, vestingMonths: 48 },}annualBase.get(plan) // 120_000annualBase.replace(130_000, plan) // new plan with base.annual = 130_000// modify returns a function — apply it to the dataconst applyMerit = annualBase.modify((salary) => Math.round(salary * 1.04))applyMerit(plan) // plan with base.annual = 124_800// Deep-update equity shares with a 10% refresh grantconst equityShares = Optic.id<CompensationPlan>().key("equity").key("shares")equityShares.modify((shares) => shares + Math.round(shares * 0.10))(plan)// plan with equity.shares = 5_500
Prisms for optional and union types. Prisms focus on one branch and may fail — getResult returns a Result, replaceResult only updates if the prism can focus:
Self-contained source · Type-checked
ts
import { Optic, Option, Result, Schema } from "effect"// Focus into Option — e.g. an optional managerIdconst inner = Optic.id<Option.Option<string>>().compose(Optic.some())inner.getResult(Option.some("mgr-007")) // Result.succeed("mgr-007")inner.getResult(Option.none()) // Result.fail(...)// Validated prism using Schema checks — salary must be positiveconst positiveSalary = Optic.id<number>().compose( Optic.fromChecks(Schema.isGreaterThan(0)))
Traversals focus on all elements of a collection at once using .forEach:
Fragment · Type-checked with fixture
ts
import { Optic, Schema } from "effect"type OrgChart = { readonly departments: ReadonlyArray<{ readonly headcount: number }> }// Traversal over all department headcounts greater than 0const positiveHeadcounts = Optic.id<OrgChart>() .key("departments") .forEach((dept) => dept.key("headcount").check(Schema.isGreaterThan(0)))// Apply a function to every matching elementconst scaled = positiveHeadcounts.modifyAll((n) => Math.ceil(n * 1.1))(org)
Note:replace only clones objects along the focused path — all unrelated branches are reused by reference. This makes optic updates efficient even for deeply nested structures.
notUndefined() preserves optionality: called on an Optional it returns another Optional, while on a Prism it returns a Prism. Replacement through composed Iso/Prism optics writes without first reading the old focus, so setters do not unexpectedly fail merely because the getter cannot currently focus. Treat the optic as the public abstraction; its internal representation is not an API.
Standalone functions. Every read and update is also exported as a dual function that takes the optic as an argument, which reads better in a pipe and lets one helper accept any optic: Optic.get (needs a Lens), Optic.getResult, Optic.replace, Optic.replaceResult, Optic.modify, Optic.set (needs a Prism), Optic.getAll, and Optic.modifyAll (need a Traversal). Note the argument order: the standalone Optic.replace(source, optic, value) is data-first, while the method is optic.replace(value, source).
Narrowing the focus..pick([...]) and .omit([...]) focus on a sub-struct, and .optionalKey("k") focuses on a key whose removal is expressed by writing undefined. Replacement through them is exact: an optional field left out of a pick / omit replacement is deleted from the source rather than kept, and optionalKey on a tuple index splices the element out.
Type guards, refinements, and Boolean combinators. Both a utility belt of isString/isNumber/... guards and a combinator library for building complex predicates from simpler ones.
Mental model. A Predicate<A> is (a: A) => boolean. A Refinement<A, B extends A> is a type guard that narrows. Both compose:
Self-contained source · Type-checked
ts
import { Predicate } from "effect"// PrimitivesPredicate.isString("hello") // truePredicate.isNumber(42) // truePredicate.isNullish(null) // truePredicate.isNullish(undefined) // truePredicate.isNotUndefined(0) // truePredicate.isTagged("Exceeds")({ _tag: "Exceeds", percentileRank: 95 }) // true// Merit eligibility: employee must have a rating that is not "Below" and a level >= 2const isMeritEligible = Predicate.and( Predicate.isTagged("Exceeds") as Predicate.Predicate<{ _tag: string; level: number }>, (e: { _tag: string; level: number }) => e.level >= 2)// Combinatorsconst isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber)const isNotNull = Predicate.not(Predicate.isNull)// Struct predicate: every field must pass — validate a RaiseRecommendation shapeconst isRaiseRecommendation = Predicate.Struct({ employeeId: Predicate.isString, amount: Predicate.isNumber,})// Compose refinements: non-empty department codeconst isNonEmptyString = Predicate.compose( Predicate.isString, (s: string): s is string => s.length > 0)// hasProperty type-safe property checkPredicate.hasProperty({ level: 3 }, "level") // true// Logical shortcutsPredicate.every([Predicate.isString, (s: string) => s.length > 3])Predicate.some([Predicate.isNull, Predicate.isUndefined])
Arbitrary-precision decimal arithmetic based on a bigint significand and integer scale. No floating-point rounding errors — 0.1 + 0.2 === 0.3 in BigDecimal.
Mental model. A BigDecimal is value / 10^scale where both are exact integers. Addition and multiplication are exact within representable scales; division uses default precision 100 and rounds the terminal digit, so non-terminating quotients are approximate. Division returns Option<BigDecimal> (use divideUnsafe if known non-zero). Parse from strings, format back to strings — never go through IEEE 754.
Self-contained source · Type-checked
ts
import { BigDecimal, pipe } from "effect"// ── Merit increase calculation ────────────────────────────────────────────────// Base salary $120,000.00 × 4% merit raiseconst baseSalary = BigDecimal.fromStringUnsafe("120000.00")const meritRate = BigDecimal.fromStringUnsafe("0.04")const increase = BigDecimal.multiply(baseSalary, meritRate) // 4800 (value 48000000n, scale 4)const newSalary = BigDecimal.sum(baseSalary, increase) // 124800 (still scale 4)BigDecimal.format(newSalary) // "124800" — format normalizes, so trailing zeros are dropped// Round to nearest dollar using the options objectBigDecimal.round(newSalary, { scale: 0, mode: "half-from-zero" })// => BigDecimal representing 124800// ── Equity grant value ────────────────────────────────────────────────────────// 5,000 RSUs at current price $48.75 eachconst sharePrice = BigDecimal.fromStringUnsafe("48.75")const grantShares = BigDecimal.fromBigInt(5000n)const grantValue = BigDecimal.multiply(sharePrice, grantShares) // 243750 (scale 2)BigDecimal.format(grantValue) // "243750"// ── Comparison ────────────────────────────────────────────────────────────────// Is the proposed salary above the band minimum?BigDecimal.isGreaterThan( BigDecimal.fromStringUnsafe("124800"), // proposed BigDecimal.fromStringUnsafe("115000") // band min) // trueBigDecimal.equals( BigDecimal.fromStringUnsafe("124800.00"), BigDecimal.fromStringUnsafe("124800.000")) // true — comparison ignores scale, so trailing zeros do not matter// Safe division returns Optionconst perShare = BigDecimal.divide( BigDecimal.fromStringUnsafe("243750"), BigDecimal.fromStringUnsafe("5000")) // Option<BigDecimal> → Option.some(48.75)
Order and Equivalence are both exported — plug into Array.sort or collection APIs directly. Both compare by numeric value regardless of scale (1.05 at scale 2 equals 1.050 at scale 3, under BigDecimal.equals and Equal.equals alike), and they share a comparator that aligns ordinary scale differences cheaply and never materialises the zeros of a huge one.
Choosing a constructor.
Source
Constructor
Notes
Integer minor units (cents, basis points)
BigDecimal.make(12_345n, 2)
Exact; value / 10^scale. A scale that is not a safe integer throws RangeError; a negative scale is allowed and multiplies (make(12n, -2) is 1200)
Untrusted text
BigDecimal.fromString(text)
Option<BigDecimal>; "12,5" is Option.none(), and so is text whose scale falls outside ±10,000 (see below)
A literal you control
BigDecimal.fromStringUnsafe("0.04")
Throws on malformed input
A bigint
BigDecimal.fromBigInt(5000n)
Scale 0
A number
BigDecimal.fromNumber(n) / fromNumberUnsafe(n)
Option / throws for NaN and infinities. The float may already be imprecise — prefer text or minor units for money
Scale, normalize, and display. The same number has many (value, scale) representations: multiplication adds the operands' scales (120000.00 × 0.04 has scale 4) and addition keeps the larger one. BigDecimal.normalize strips trailing zeros, and BigDecimal.format normalizes before rendering — so formatnever pads: 124800.00 prints as "124800" and 123.50 as "123.5". Round with BigDecimal.round for arithmetic, and pad to the currency's minor units yourself when rendering money. Non-terminating quotients are rounded at precision 100, and format switches to scientific notation once the normalized scale reaches 16, so 1 / 3 prints as 3.333…e-1; round a quotient to the scale you actually need (BigDecimal.round(q, { scale: 4 }) formats as "0.3333").
Scale limits. Scales are bounded so hostile numeric text cannot make the library allocate huge powers of ten. fromString, fromStringUnsafe, Schema.BigDecimal's JSON codec, and Schema.BigDecimalFromString reject text whose scale, before or after dropping trailing zeros, lies outside ±10,000: "1e-10001" and a fraction with 10,001 digits are Option.none() (a throw, or a SchemaError), while "1e-10000" parses. Operations that must align two scales — sum, sumAll, subtract, remainder / remainderUnsafe, scale in either direction, and round, truncate, ceil, floor toward a much smaller target scale — throw a RangeError when the scales differ by more than 20,000. Two freshly parsed values always fit; a wider gap comes from make(value, scale), which accepts any safe-integer scale, or from repeated multiply, which adds its operands' scales. equals, Order, and Equivalence compare without materializing the difference, so they never throw. round returns a value already at or below its target scale unchanged.
remainder follows the divide rule: the safe form returns Option.none() for a zero divisor and the Unsafe form throws. clamp and between take { minimum, maximum }.
Use for any financial or compensation calculation where floating-point rounding is unacceptable.
Official guide: BigDecimal (its unsafeFromString / unsafeFromNumber headings are stale names; use fromStringUnsafe / fromNumberUnsafe or the safe fromNumber).
An exact fraction: a bigintnumerator and a positive bigintdenominator, always reduced to lowest terms (zero is 0/1). Where BigDecimal rounds a non-terminating quotient such as one third, Rational keeps it exact through any number of sum, multiply, divide, and pow steps. Use BigDecimal for decimal quantities such as money, and Rational for ratios that must stay exact until an explicit conversion: allocation shares, unit-conversion factors, probabilities, compounding rates.
Mental model. Canonical form makes equality a field comparison, so Equal.equals, Rational.equals, and Rational.Equivalence agree, and makeUnsafe(2n, 4n) equals makeUnsafe(1n, 2n). Every operation that can fail has a safe and an Unsafe form: make, fromNumber, fromString, divide, and pow return Option (a zero denominator or divisor, a non-finite number, malformed text, zero to a negative power), while the Unsafe twins throw. pow takes an integer exponent and throws a RangeError for anything that is not a safe integer, including 0.5, in both forms.
Self-contained source · Type-checked
ts
import { BigDecimal, Option, Rational } from "effect"// Split a bonus pool three ways without losing the remainder to rounding.const third = Rational.makeUnsafe(1n, 3n)const shares = Rational.sumAll([third, third, third])Rational.format(shares) // "1/1": exactly the whole pool// Decimal text converts exactly; a JavaScript number keeps its binary error.Rational.format(Rational.fromBigDecimal(BigDecimal.fromStringUnsafe("0.1"))) // "1/10"Rational.fromNumber(0.1) // Option.some(3602879701896397/36028797018963968)// Leave the exact world only at an explicit, rounded boundary.const perShare = Rational.toBigDecimal(Rational.makeUnsafe(2n, 3n), { scale: 4 }) // 0.6667const roundedDown = Rational.toBigDecimal(Rational.makeUnsafe(2n, 3n), { scale: 4, mode: "floor" }) // 0.6666Rational.toNumberUnsafe(third) // 0.3333333333333333// Safe division: a zero divisor is Option.none(), not an exception.Rational.divide(third, Rational.fromBigInt(0n)) // Option.none()Rational.fromString("-4/-6").pipe(Option.map(Rational.format)) // Option.some("2/3")const _ = [perShare, roundedDown]
Conversions.fromBigDecimal is the exact route from decimal text, and toBigDecimal(r, { scale, mode? }) is the rounded route back (mode defaults to "half-from-zero", the same modes as BigDecimal.round). fromNumber captures the exact binary value of the double, so 0.1 is not one tenth; toNumberUnsafe rounds to the nearest double and becomes Infinity for very large magnitudes. fromString accepts only [+-]digits or [+-]digits/[+-]digits — no whitespace, decimal point, or exponent — and format writes the reduced numerator/denominator, 3/1 for an integer.
At the boundary.Schema.Rational validates Rational values, and its JSON codec writes the canonical "numerator/denominator" string; Schema.RationalFromString decodes that text grammar from a string field and rejects a zero denominator. A persisted schema representation containing Schema.Rational needs SchemaRepresentation.RationalReviver passed to fromRepresentation.
Warning: Exactness has a cost: numerators and denominators grow with every operation whose denominators share no factor, so a long chain of unrelated ratios can produce very large bigints. Round with toBigDecimal at the step where precision is allowed to end, and bound untrusted inputs before compounding them.
An exact, non-negative, integral byte count: a branded bigint, so a 9 EiB object store and a 12-byte header use the same type without precision loss. It replaced the ad-hoc FileSystem.Size / FileSystem.MiB helpers and is now the size vocabulary across the ecosystem — FileSystemFile.Info.size, HTTP body limits, and Config.ByteSize.
Mental model. Decimal units are powers of 1,000 (kB, MB, GB, …); binary units are powers of 1,024 (KiB, MiB, GiB, …). The two families have separate constructors so "10 MB" never silently means 10 MiB. A value is always a whole number of bytes. Two doors lead in, and they differ: ByteSize.Input (what fromInput, Stream.limitBytes, and other size options accept) takes a ByteSize, a bigint, a number checked at runtime, or a string literal that is a whole number followed by a unit ("64 KiB", "64KiB", "10 megabytes"), and a malformed or fractional literal such as "1.5 KiB" is a compile error. Text from outside the program goes through ByteSize.fromString (an Option) or fromStringUnsafe (throws), which also accept decimal fractions and surrounding whitespace: "1.5 KiB" parses to 1,536 bytes, but "1.5 B" is rejected because it is not a whole byte.
Fragment · Type-checked
ts
import { ByteSize, Config, Option } from "effect"// ── Constructors name their unit family ──────────────────────────────────────const uploadLimit = ByteSize.mebibytes(25) // 25 × 1024²const diskQuota = ByteSize.gigabytes(500) // 500 × 1000³// ── Typed input: string literals are checked at compile time ─────────────────ByteSize.fromInput("64 KiB") // Option.some(65536n)ByteSize.fromInput(-1) // Option.none() — numbers are checked at runtime// ByteSize.fromInput("1.5 KiB") does not compile: literals need a whole quantity// ── External text: fromString (Option) or the throwing fromStringUnsafe ──────declare const quotaFromAdminForm: stringByteSize.fromString(quotaFromAdminForm) // Option<ByteSize>ByteSize.fromString("1.5 KiB") // Option.some(1536n) — fractions allowedByteSize.fromString("1.5 B") // Option.none() — not an integral byte count// ── Exact arithmetic; scalar operations are partial, so they return Option ───const perReviewer = ByteSize.divide(diskQuota, 40) // Option<ByteSize>, remainder discardedconst doubled = ByteSize.times(uploadLimit, 2) // Option<ByteSize>const total = ByteSize.sum(uploadLimit, ByteSize.bytes(512))// ── Comparison: use the module, not `>` on the brand ─────────────────────────ByteSize.isGreaterThan(total, uploadLimit) // trueByteSize.clamp(total, { minimum: ByteSize.zero, maximum: uploadLimit })// ── Presentation ─────────────────────────────────────────────────────────────ByteSize.format(uploadLimit) // "25 MiB" (binary units by default)ByteSize.format(uploadLimit, { system: "decimal" }) // "26.21 MB" (precision defaults to 2)ByteSize.format(uploadLimit, { unit: "KiB", precision: 0 }) // "25600 KiB"ByteSize.toUnit(uploadLimit, "MiB") // 25 — an approximate `number`// ── Configuration: accept "25 MiB" (or "1.5 GiB") from the environment ────────const maxUpload = Config.ByteSize("MAX_UPLOAD").pipe(Config.withDefault(uploadLimit))const _ = [perReviewer, doubled, Option.isSome(perReviewer), maxUpload]
The unit constructors (kilobytes, megabytes, kibibytes, …) take a number quantity and compute the byte count exactly, without floating-point rounding: ByteSize.megabytes(2.01) is 2,010,000 bytes. A quantity that does not land on a whole, non-negative, safe-integer byte count — ByteSize.kilobytes(0.0005), ByteSize.bytes(1.5), a negative number — throws instead of being rounded. When a quantity is computed rather than known to be exact, pass the byte count to fromInput, which returns an Option.
ByteSize.Order, ByteSize.Equivalence, ReducerSum, CombinerMin, and CombinerMax plug into sorting, collections, and folds. ByteSize.toNumber returns Option<number> because a byte count may exceed the safe-integer range; toNumberUnsafe throws instead. Schema.ByteSize is the matching schema.
Use for every size limit, quota, buffer bound, and file size — anywhere a bare number would leave "bytes or kilobytes? 1000 or 1024?" to a comment.
An interface for patch-based change tracking. A Differ<T, Patch> computes the difference between two Ts as a Patch, combines patches, and applies a patch to produce an updated value.
Mental model. Typed diff/apply protocol. Rarely constructed by hand — consumed by data structures needing incremental updates (e.g., context propagation in the runtime). Implement when building patch-based state management:
Self-contained source · Type-checked
ts
import { Differ } from "effect"// The interface:// interface Differ<T, Patch> {// readonly empty: Patch// diff(oldValue: T, newValue: T): Patch// combine(first: Patch, second: Patch): Patch// patch(oldValue: T, patch: Patch): T// }// Example: track incremental changes to a merit budget pool (in cents)const BudgetDiffer: Differ.Differ<number, number> = { empty: 0, diff: (oldVal, newVal) => newVal - oldVal, combine: (a, b) => a + b, patch: (oldVal, delta) => oldVal + delta}const delta1 = BudgetDiffer.diff(500_000, 450_000) // -50_000 (first department draw)const delta2 = BudgetDiffer.diff(450_000, 380_000) // -70_000 (second department draw)const combined = BudgetDiffer.combine(delta1, delta2) // -120_000BudgetDiffer.patch(500_000, combined) // 380_000 remaining
Use when building patch-sourced state propagation that needs to compute, merge, and replay incremental changes rather than replacing values wholesale.
Minimal edit scripts for arrays and text (Myers' algorithm in linear space). diff(before, after) compares array items with Equal.equals and diffWith(isEquivalent) with a custom equivalence; lines diffs text line by line, keeping each \n so line-ending changes are visible; codePoints diffs by Unicode code point, never splitting a surrogate pair. A script is an array of Equal / Delete / Insert runs. apply and applyText replay a script and return Result — applyText rejects a script made for different text with a TextDiffError — and invert reverses it. unified(edits, { context?, fromFile?, toFile? }) formats a line script as a unified diff.
Warning: Without a cap, work grows with input size times the number of differences — quadratic for unrelated inputs. Pass maxEdits for large or untrusted inputs; past the cap the script stays valid but may no longer be minimal.
Use for audit trails, review screens, and change previews over text or lists. For patching typed state, use Differ.
Immutable Semantic Versioning 2.0.0 values: numeric major, minor, patch, optional prerelease identifiers, and optional build metadata. Parsing is strict — SemVer.parse(text) returns Result<SemVer, SemVerError> and rejects partial versions ("1.2") and a v prefix; parseUnsafe throws, and make(components) / fromInput build from fields. format prints the canonical string.
SemVer.Order follows spec precedence (a pre-release sorts before its release) and ignores build metadata, while Equal.equals and hashing include it — so 1.0.0+a and 1.0.0+b are not Equal but compare as 0. Comparison helpers (isLessThan, between, min, max, clamp), release (drop the pre-release), bumpMajor / bumpMinor / bumpPatch, the bumpPre* family, bump(version, releaseType, identifier?), and difference(a, b) (an Option<ReleaseType> naming the bump between two versions) cover release tooling.
Self-contained source · Type-checked
ts
import { Result, SemVer } from "effect"const current = SemVer.parseUnsafe("1.4.2-rc.1+build.7")SemVer.isPrerelease(current) // trueSemVer.format(SemVer.release(current)) // "1.4.2"const stable = SemVer.parseUnsafe("1.4.2")SemVer.format(SemVer.bump(stable, "minor")) // "1.5.0"SemVer.format(SemVer.bump(stable, "premajor", "rc")) // "2.0.0-rc.0"SemVer.difference(stable, SemVer.parseUnsafe("1.5.0")) // Option.some("minor")Result.isFailure(SemVer.parse("v1.2.3")) // true — no `v` prefix, no partial versions
Schema.SemVer validates SemVer values and Schema.SemVerFromString decodes the version string form, for config, manifests, and API payloads.
npm-style version ranges over SemVer: comparators, ^ caret, ~ tilde, x/* wildcards, hyphen ranges (1.2.3 - 2.3.4), and || alternatives. SemVerRange.parse(text) returns Result<SemVerRange, SemVerError>; constructors (exact, caret, tilde, greaterThan, lessThanOrEqualTo, between({ minimum, maximum }), any) build ranges directly. matches(range, version, options?), maxSatisfying, and minSatisfying accept a SemVer or a version string and throw SemVerError on an invalid one.
Pre-releases follow node-semver: a pre-release version matches only a comparator set that names a pre-release of the same major.minor.patch, unless { includePrerelease: true } is passed. One deliberate difference: || alternatives always form a union, so a * alternative does not discard pre-releases another alternative admits. Schema.SemVerRange and Schema.SemVerRangeFromString cover the schema side.
A zero-cost type wrapper — a type-level distinct alias for another type, with helpers to lift its Equivalence, Order, Combiner, and Reducer instances. Related to Brand but different: a Newtype carries no runtime value of its own; it is the carrier type with a phantom tag.
Mental model. Zero-overhead alternative to Brand when you only need distinct types without runtime validation. Pairs with Optic.Iso for lossless conversions. makeIso returns an Iso whose .get unwraps and .set wraps:
Self-contained source · Type-checked
ts
import { Newtype, Optic, Equivalence, Order } from "effect"// Distinguish salary dollars from equity dollars at the type levelinterface SalaryUSD extends Newtype.Newtype<"SalaryUSD", number> {}const salaryIso = Newtype.makeIso<SalaryUSD>()const base: SalaryUSD = salaryIso.set(120_000) // 120_000 branded as SalaryUSDsalaryIso.get(base) // 120_000 (the plain number)// Lift Order and Equivalence for the underlying numberconst SalaryOrder = Newtype.makeOrder<SalaryUSD>(Order.Number)const SalaryEq = Newtype.makeEquivalence<SalaryUSD>(Equivalence.Number)
Use when you want unit-tagged types at zero runtime cost and don't need Brand's validation machinery.
Combinators for functional composition: pipe, flow, identity, constant, and indispensable utilities.
Re-exported from the "effect" barrel — typically import { pipe, flow } from "effect" rather than importing from this module directly.
Self-contained source · Type-checked
ts
import { pipe, flow, Function as F } from "effect"// pipe: pass a value through a left-to-right pipeline// Apply a merit raise and round to nearest dollarconst applyMerit = (base: number, rate: number) => pipe( base, (salary) => salary * (1 + rate), (raised) => Math.round(raised))applyMerit(120_000, 0.04) // 124_800// flow: compose functions into a new function (no initial value)const formatSalary = flow( (cents: number) => cents / 100, (dollars) => `$${dollars.toLocaleString()}`)formatSalary(12_480_000) // "$124,800"// identity / constantF.identity(42) // 42F.constant(true)() // trueF.constNull() // nullF.constUndefined() // undefined// flip: swap the first two arguments of a functionconst sub = (a: number) => (b: number) => a - bF.flip(sub)(5_000)(120_000) // 120_000 - 5_000 = 115_000// compose: left-to-right function composition// First extract level (string -> number), then format itconst formatLevel = F.compose( (s: string) => parseInt(s, 10), // applied first (n: number) => `Level ${n}` // applied second)formatLevel("3") // "Level 3"// dual: makes a function work data-first OR data-last (pipeable)// — used extensively inside Effect to build the pipe-friendly API// memoize: WeakMap-based memoization for object-keyed functions.// memoizeIdempotent also caches the computed output as a fixed point.type Normalized = { readonly name: string }const normalize = F.memoizeIdempotent<Normalized>((person) => ({ name: person.name.trim()}))const normalized = normalize({ name: " Ada " })normalize(normalized) === normalized // true: the output is cached as its own result
Use memoizeIdempotent only when applying the original transformation again to its output would be observably idempotent; otherwise caching the output as a fixed point changes behavior.
Both memoizers are identity-based WeakMap caches, so structurally equal objects are different keys and mutating a key does not invalidate its cached value. memoize cannot return undefined: that value is reserved internally to mean “cache miss” (return null or another sentinel if absence is a legitimate result).
Why functions instead of methods. Effect's API is module functions plus one .pipe method, not fluent method chains, for two reasons: a bundler can drop every function you never import (a method on a class cannot be tree-shaken), and anyone can add a new operator for an existing type without patching its prototype. dual(arity, body) is what gives each function both call shapes — Array.map(xs, f) data-first for a single call, Array.map(f) data-last inside pipe.
Self-contained source · Type-checked
ts
import { Function as F, pipe } from "effect"// `dual(2, ...)`: two arguments means data-first, one argument returns the pipeable formconst applyMerit: { (rate: number): (salary: number) => number (salary: number, rate: number): number} = F.dual(2, (salary: number, rate: number): number => Math.round(salary * (1 + rate)))applyMerit(120_000, 0.04) // 124_800pipe(120_000, applyMerit(0.04)) // 124_800
Use for pipe or flow (everyday use), or when building dual-mode utility functions for your own library.
Official guides: Building Pipelines (it states that Option and Result can be yielded inside Effect.gen; they cannot — convert with Effect.fromOption / Effect.fromResult), Dual APIs.
Pipeable arithmetic, comparisons, and ready-made Reducers for number. Exports Number.Order, Number.Equivalence, Number.ReducerSum, Number.ReducerMultiply, Number.ReducerMin, Number.ReducerMax. Arithmetic ops (sum, multiply, subtract, divide, remainder) are data-last for pipeline use. Also Number.clamp, Number.between, Number.sign, Number.parse (safe string parse returning Option), Number.round, and Number.nextPow2.
Self-contained source · Type-checked
ts
import { Number as N, pipe } from "effect"pipe(3, N.increment) // 4pipe(-1, N.sign) // -1N.sumAll([80_000, 95_000, 120_000]) // 295_000N.parse("0.04") // Option.some(0.04)// Clamp a proposed salary to a comp band [min, max]N.clamp({ minimum: 90_000, maximum: 160_000 })(185_000) // 160_000
Comprehensive, pipeable string API. Re-exports the global String constructor plus safe wrappers for common string operations. Notable additions over plain JS: String.indexOf/lastIndexOf return Option, String.stripMargin cleans multiline template literals, full case-conversion helpers (camelCase, pascalCase, snakeToCamel, constantCase, etc.).
snakeToCamel and snakeToPascal drop a trailing underscore rather than throwing; an input made only of an even number of underscores becomes "". noCase returns "" without invoking a custom transform when the input contains no words (such as "" or "---"). These are case-conversion utilities, not identifier validators.
Self-contained source · Type-checked
ts
import { String as S, pipe } from "effect"pipe(" eng-l3-nyc ", S.trim, S.toUpperCase) // "ENG-L3-NYC"S.stripMargin(` |employeeId: emp-001 |level: 3`)// "\nemployeeId: emp-001\nlevel: 3\n" — the newline after the opening backtick is keptS.camelCase("merit_cycle") // "meritCycle"S.pascalCase("comp_band") // "CompBand"S.configCase("Payroll API URL") // "PAYROLL_API_URL"// data-last: searchString first, then selfS.indexOf("emp")("hris-emp-001") // Option.some(5)
Boolean logic as pipeable functions. Boolean.match branches on a boolean like a mini pattern match. Logical connectives — and, or, not, xor, nand, nor, implies, eqv — as data-last functions. Includes Boolean.every/some for iterables and ready-made reducers Boolean.ReducerAnd/ReducerOr.
The mixin that gives an object a .pipe(...) method, enabling value.pipe(f, g, h) fluent style. Many object-based Effect types implement this; primitive brands such as ByteSize are plain bigints and use module functions or pipe(value, ...). Extend Pipeable.Class or mix in Pipeable.Mixin(Base) to add .pipe to your own types. Pipeable.pipeArguments is the internal dispatch used by the .pipe implementation.
Self-contained source · Type-checked
ts
import { Pipeable } from "effect"class SalaryBand extends Pipeable.Class { readonly min: number readonly mid: number readonly max: number constructor(min: number, mid: number, max: number) { super() this.min = min this.mid = mid this.max = max }}new SalaryBand(90_000, 120_000, 150_000) .pipe((band) => band.max - band.min) // 60_000 (band spread)
Provides Symbol.isSymbol (type guard), consistent with Predicate.isSymbol. It does not re-export a constructor alias; use globalThis.Symbol to construct symbols when the imported namespace shadows the global name.
Re-exports the global RegExp constructor, provides RegExp.isRegExp (type guard), and adds RegExp.escape(string) — escapes all regex metacharacters so a literal string can be safely embedded in a regex pattern.
Self-contained source · Type-checked
ts
import { RegExp as RE } from "effect"// Safely search for an employee ID that might contain regex metacharactersconst empId = "emp.001+special"const pattern = new RE.RegExp(`^${RE.escape(empId)}$`)// pattern: /^emp\.001\+special$/
Ergonomics for A | undefined without Option ceremony. Provides UndefinedOr.map, UndefinedOr.match, UndefinedOr.getOrThrow, UndefinedOr.getOrThrowWith, and UndefinedOr.liftThrowable. Bridges to Combiner/Reducer: UndefinedOr.makeReducer(combiner) and UndefinedOr.makeReducerFailFast.
Fragment · Type-checked with fixture
ts
import { UndefinedOr } from "effect"// An employee's manager may or may not be setconst managerId: string | undefined = employee.managerIdUndefinedOr.map(managerId, (id) => `mgr:${id}`) // string | undefinedUndefinedOr.getOrThrow(managerId) // string or throwsUndefinedOr.match(managerId, { onDefined: (id) => `Reports to ${id}`, onUndefined: () => "No manager assigned (top-level)"})
Small helpers for Uint8Array: Bytes.concat(chunks) joins chunks into one new array (it never aliases an input, even for zero or one chunk), Bytes.Equivalence compares byte by byte, and Bytes.Order sorts lexicographically by unsigned byte with a prefix before any longer sequence. Text and Base64/hex conversions stay in TextEncoder/TextDecoder and the effect/encoding modules below.
Self-contained source · Type-checked
ts
import { Array as Arr, Bytes } from "effect"const frame = Bytes.concat([new Uint8Array([0x01, 0x02]), new Uint8Array([0x03])]) // Uint8Array [1, 2, 3]Bytes.Equivalence(frame, new Uint8Array([1, 2, 3])) // trueconst sorted = Arr.sort([new Uint8Array([1, 0]), new Uint8Array([1])], Bytes.Order) // [[1], [1, 0]]
Warning:Bytes.Equivalence returns at the first differing byte, so it is not constant-time. Never compare MACs, tokens, or other secrets with it; use the verification operations in Cryptography.
Text codecs live under effect/encoding, one module per format. The three binary-to-text modules (Base64, Base64Url, Hex) share one shape: encode accepts a Uint8Array or a string and always succeeds; decode returns Result<Uint8Array, EncodingError>; decodeString decodes and then interprets the bytes as UTF-8, returning Result<string, EncodingError>. decodeString keeps a leading U+FEFF as part of the text instead of stripping it as a byte-order mark, so decoding then re-encoding returns the original bytes; the same holds for Schema.StringFromBase64, StringFromBase64Url, and StringFromHex. Trim it yourself when the payload is a file that may start with a BOM. There is no catch-all Encoding namespace — import the format you need.
Self-contained source · Type-checked
ts
import { Result } from "effect"import { Base64 } from "effect/encoding"// Encode an employee token payload for transmissionconst encoded = Base64.encode("emp-001:merit-2025") // base64 stringconst decoded = Base64.decodeString(encoded) // Result<string, EncodingError>if (Result.isSuccess(decoded)) { console.log(decoded.success) // "emp-001:merit-2025"}const bytes = Base64.decode(encoded) // Result<Uint8Array, EncodingError>
The URL- and filename-safe alphabet (- and _ instead of + and /, no padding), with the same encode / decode / decodeString trio. Use it for values that travel in query strings, cookies, or path segments. Base64Url.encodePadded keeps the = padding for consumers that require it, such as Go's base64.URLEncoding; SchemaGetter.encodeBase64Url takes the matching padding option. Decoding accepts unpadded (Zg) and fully padded (Zg==) input but rejects partial padding (Zg=) with an EncodingError.
Hexadecimal with the same trio — encode writes lowercase, decode accepts either case and fails on an odd length or a non-hex character — plus Hex.random(length), which returns a random lowercase hex string for identifiers such as correlation ids. random draws from Math.random(), so it is not cryptographically secure — never use it for tokens, secrets, or anything an attacker must not guess; for those, draw bytes with randomBytes from the SecureRandom service and pass them to Hex.encode. length is not validated: it is rounded down to a multiple of 8, so Hex.random(10) has 8 characters and Hex.random(3) is the empty string.
The single failure type shared by the format modules: a Data.TaggedError with _tag: "EncodingError", a kind ("Decode" or "Encode"), the module that failed ("Base64", "Hex", and the configuration parsers "Toml", "Json5", "Jsonc", …), the offending input, and a human-readable message. EncodingError.isEncodingError narrows an unknown value. Because every decode returns a Result, you handle it with the Result combinators rather than with Effect.catch.
Self-contained source · Type-checked
ts
import { Result } from "effect"import { Base64, EncodingError } from "effect/encoding"const parsed = Base64.decodeString("not base64!")if (Result.isFailure(parsed)) { const error: EncodingError.EncodingError = parsed.failure console.log(error.kind, error.module, error.message) // "Decode" "Base64" "Length must be a multiple of 4, but is 11"}
Defines the Inspectable interface (toJSON, toString, [NodeInspectSymbol]) and a BaseProto/Class you can extend to make custom types print correctly in the Node.js REPL, logs, and test output. Inspectable.toJson first applies redaction, invokes an inspectable toJSON, and recursively handles arrays; plain objects otherwise remain unchanged. It is a structured inspection representation, not a promise that JSON.stringify can accept every nested value or cycle. String rendering uses Formatter.
Type-level utilities — no runtime code. Commonly encountered:
Simplify<A> — Flattens intersection types into a readable object shape. Essential for IDE hover text.
UnionToIntersection<T> — Converts A | B | C to A & B & C. Used in requirement accumulation.
Equals<X, Y> — Type-level equality check, returns true or false. Useful in conditional types.
Tags<E> — Extracts the string literal union of all _tag values from a discriminated union.
Mutable<T> / DeepMutable<T> — Strips readonly from object properties, shallowly or recursively. DeepMutable recurses through plain records, arrays, tuples, Map, and Set, and stops at primitives, functions, and opaque objects (anything with methods or symbol-keyed properties), so a Date, DateTime, Option, or class instance nested inside keeps its own type.
RequiredKeys<T> — The union of T's required property names. Named required keys are still reported when T also has an index signature.
NoInfer<A> — Prevents TypeScript from using a parameter site as an inference point — useful for pinning type parameters.
Also: TupleOf, TupleOfAtLeast, MergeLeft/MergeRight, Concurrency, Invariant/Covariant/Contravariant variance wrappers, ExtractTag, ExcludeTag, ReasonOf, and more.
Advanced plumbing for libraries that implement Effect-style generator syntax; it is not a general application utility bag. SingleShotGen<T, A> is the one-yield iterator used to make a custom value work with yield*. The type-only Variance and Gen<F> encode environment, output, and error variance for a TypeLambda, which is how Effect.gen, Option.gen, and Result.gen infer the values yielded by their generators.
Self-contained source · Type-checked
ts
import { Option } from "effect"import type { Utils } from "effect"// A library can pin the common generator signature for its TypeLambda.const optionGen: Utils.Gen<Option.OptionTypeLambda> = Option.genconst value = optionGen(function*() { const n = yield* Option.some(41) return n + 1}) // Option.some(42)
Most applications should use the owning module's .gen directly. Reach into Utils only when authoring a new Effect-like data type or generator DSL.
A type-level mechanism that collapses a union of Effect-like types (e.g., Effect<A> | Effect<B>) into a single unified Effect. Makes yield* in Effect.gen work correctly across conditional branches returning different Effect types.
Rarely called directly, but Unify.Unify<T> appears in type signatures as the return type of generators and combinators that unify disparate branches. Unify.unify(value) is the runtime identity function carrying the type-level unification.
Higher-Kinded Types for TypeScript, encoded via the defunctionalisation trick. TypeScript has no native HKT support, so Effect uses a TypeLambda interface as a "type function" mapping variance parameters to a concrete type via Kind<F, In, Out2, Out1, Target>.
Relevant when building typeclass instances (Functor, Traversable, etc.) for your own types, or reading internals of Combiner, Reducer, and Equivalence. Normal application code never touches HKT directly. Key exports: TypeLambda, TypeClass, Kind.
Effect v4 rebuilt Schema around a single Codec abstraction: a two-way, validating, possibly-effectful bridge between two TypeScript types. Type is the decoded, in-memory value; Encoded is the wire/storage shape. decode goes Encoded → Type (with validation); encode goes Type → Encoded. Schema.String is the degenerate case (both sides string); Schema.FiniteFromString (Encoded = string, Type = number) is the usual numeric boundary. Satellite modules — SchemaParser, SchemaIssue, SchemaGetter, SchemaTransformation, SchemaRepresentation — are the implementation; Schema is the interface.
This page covers the everyday codec work (sections 1–9 below). Schema in Depth continues with annotations, serialization, recursion, parse options, optional fields, and effectful schemas; Schema Tooling & Internals covers the AST, compilers, issues, JSON Schema, and TestSchema.
Official companion: Effect's release-matched comprehensive Schema guide goes substantially deeper into codecs, constraints, transformations, serialization, generated tooling, integrations, and migration.
Official guides:Introduction to Effect Schema (its parse-option and transformOrFail spellings are stale — see the sections below); section-specific guides are linked where they apply. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
The core module: declare data shape and validation; get back a value that is simultaneously a type-level description (Type and Encoded), a runtime validator, a two-way codec, and a seed for derived artifacts (JSON Schema, arbitraries, equivalence, formatters).
Mental model. A schema is a Codec<Type, Encoded, RD, RE>: decodes Encoded into Type, encodes Type into Encoded, decoding may require services RD, encoding may require services RE. Use typeof Employee.Type and typeof Employee.Encoded rather than reading the full Schema.Struct<...> type. Schema.revealCodec(schema) exposes the four inferred codec parameters of a precise schema; it cannot recover information already erased by widening to Schema.Schema<T>. Retain the precise type or an explicit Codec<T, E, RD, RE> annotation.
Prerequisites and naming. Schema assumes strict: true. Turn on exactOptionalPropertyTypes too, because Schema.optionalKey(S) means "absent, or present as an S": with the flag off TypeScript accepts { key: undefined } and the decoder then rejects it at runtime. Library names follow one rule worth copying for your own codecs: a bare name (Schema.Date, Schema.Trimmed) only validates, so Encoded equals Type; TFromE (DateFromString) or a verb (Trim) transforms. In generic code, extract types with Schema.Schema.Type<S>, Schema.Codec.Encoded<S>, Schema.Codec.DecodingServices<S>, and Schema.Codec.EncodingServices<S>.
Numeric boundary warning:Schema.Number intentionally accepts NaN, Infinity, and -Infinity (their JSON encoding uses strings). Schema.NumberFromString can decode them too. For money, percentages, coordinates, scores, and most domain quantities, use Schema.Finite / Schema.FiniteFromString; add Schema.Int, Schema.Natural, range checks, or brands when the domain is narrower. Use bare Number only when non-finite IEEE-754 values are genuinely part of the model.
Schema.Natural means a non-negative safe integer, including zero. Schema.Date accepts only valid Date instances (an Invalid Date fails); use DateFromString or DateFromMillis for ISO text or safe-integer epoch milliseconds, and both reject transformations that produce an invalid date. Schema.Void is for ignored return values: it accepts any present runtime value and decodes it to undefined; use Schema.Undefined when the boundary must contain literal undefined.
1. Decoding and encoding — pick your result style
Runners form a matrix: how failures surface × whether input is typed (decode) or unknown (decodeUnknown). For untrusted external input use decodeUnknownSync at a boundary or decodeUnknownEffect inside a program.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"// The HRIS sends salaries as strings. Encoded = string, Type = number — a real codec.const SalaryFromString = Schema.FiniteFromString// At a trusted boundary: throw on bad input.console.log(Schema.decodeUnknownSync(SalaryFromString)("185000")) // 185000// Inside a program: failures land in the typed error channel as a SchemaError.const program = Effect.gen(function*() { const base = yield* Schema.decodeUnknownEffect(SalaryFromString)("185000") // base: number return base * 1.04 // a 4% merit bump})// Encoding goes the other way: Type -> Encoded (number -> the wire string).Effect.runPromise(Schema.encodeUnknownEffect(SalaryFromString)(192400)).then(console.log)// "192400"
You want
Use
On failure
Boundary code that fails loudly
decodeUnknownSync(s)(x)
throws SchemaError
Decode inside Effect.gen
decodeUnknownEffect(s)(x)
Effect<A, SchemaError>
Inspect an Exit
decodeUnknownExit(s)(x)
Exit<A, SchemaError>
Only ask whether it parses
decodeUnknownOption(s)(x)
Option<A>
A synchronous value without exceptions
decodeUnknownResult(s)(x)
Result<A, SchemaError>
Promise interop
decodeUnknownPromise(s)(x)
rejects
Note: Every runner has an encode* twin and a non-Unknown variant (decodeSync, etc.) for when the input type already matches Encoded.
Choose the runner by who consumes the failure.
Effect runner when typed composition, services, or interruption matter. It is the only runner for an effectful schema: the Sync, Option, Result, Exit, and Promise runners accept only schemas whose DecodingServices / EncodingServices are never (a compile error otherwise). A service-free schema that still does asynchronous work is accepted by the types but not by the synchronous adapters: decodeUnknownSync and decodeUnknownResult throw a plain Error wrapping an AsyncFiberError defect instead of a SchemaError, and decodeUnknownExit returns a Die. Only decodeUnknownPromise tolerates async steps outside an Effect.
Result / Exit when pure code branches on the outcome. Option only when discarding the diagnostics is intended.
Throwing Sync only at an edge that already speaks exceptions (a script, a framework callback) and catches there.
Warning:Effect.sync(() => Schema.decodeUnknownSync(S)(input)) has error type never, so bad input becomes a defect that no Effect.catchTag("SchemaError", ...) can see. Inside an Effect, call Schema.decodeUnknownEffect(S)(input) so the expected boundary outcome stays in the typed error channel. The two sibling mistakes are casting (input as Employee) and Effect.orElseSucceed(() => believableDefault) straight after decoding, which hides a parse failure behind plausible data.
Per-call behavior — excess keys, error accumulation, concurrency, rejected-input reporting — is covered in Parse options are boundary policy.
Official guide: Getting Started (its "preserve", propertyOrder, and parseOptions-annotation passages do not apply to this edition).
2. Type vs Encoded — the distinction that runs everything
A schema carries two TypeScript types. toType produces a schema whose Encoded equals its Type (useful when the input is already decoded and only validation is needed). toEncoded gives the wire shape. flip swaps both directions.
For generic APIs that only consume one direction, accept Schema.Decoder<T, RD> or Schema.Encoder<E, RE>; these retain the relevant type and service requirements while deliberately erasing the other direction. Use the full Codec<T, E, RD, RE> only when both decoding and encoding matter.
Self-contained source · Type-checked
ts
import { Schema } from "effect"const schema = Schema.FiniteFromStringtype T = typeof schema.Type // number (a salary in memory)type E = typeof schema.Encoded // string (the salary on the wire)// Project a schema down to just the decoded side (Type == Encoded == number).const justType = Schema.toType(schema)// Project to just the encoded side (string).const justEncoded = Schema.toEncoded(schema)// Swap decode/encode directions: now decodes number -> string.const flipped = Schema.flip(schema)
What the projections keep.toType keeps the checks attached to the decoded side and drops the transformation plus any encoded-side checks; toEncoded does the opposite. Neither result needs services. For Schema.FiniteFromString.check(Schema.isGreaterThan(0)), the toType projection validates a value that is already a number and still enforces the range (use it to avoid decoding container elements twice), while the toEncoded projection accepts any string — "-1" included — because the range check lives on the decoded side.
Name both positions from day one, even when they are identical: type Employee = typeof Employee.Type and type EmployeeWire = typeof Employee.Encoded. The second name lets a signature say "this has not crossed the boundary yet", and it removes the temptation to write a helper that takes the wire type and casts it to the domain type. When introducing Schema into existing code, start with structure plus .check(...) only; add brands, transformations, defaults, and classes once the boundary exists.
Struct builds object schemas. Fields are schemas; wrap in optionalKey (key may be absent) or optional (absent or undefined) to control optionality. Spread SomeStruct.fields to reuse field sets across schemas.
Self-contained source · Type-checked
ts
import { Schema } from "effect"// Audit columns we reuse on every persisted entity.const Timestamped = Schema.Struct({ createdAt: Schema.Date, updatedAt: Schema.Date})const Employee = Schema.Struct({ ...Timestamped.fields, // reuse a field set id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), // e.g. IC4 -> 4 baseSalary: Schema.BigDecimalFromString, // currency: BigDecimal in memory, string on the wire managerId: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))) // top of the org chart has none})// { readonly createdAt: Date; readonly updatedAt: Date; readonly id: number;// readonly name: string; readonly level: number;// readonly baseSalary: BigDecimal; readonly managerId?: number }type Employee = typeof Employee.Typeconst alice = Schema.decodeUnknownSync(Employee)({ createdAt: new Date(), updatedAt: new Date(), id: 1, name: "Alice", level: 5, baseSalary: "185000"})
optionalKey and optional differ at runtime, not only in the type; the full input-state table, null handling, and Option-typed fields are in Optional fields, null, and Option.
Deriving structs. v4 has no Schema.pick / omit / partial / required. A struct is reshaped by passing a plain function over its fields record to .mapFields(...), and the generic Struct module supplies those functions.
Self-contained source · Type-checked
ts
import { Schema, Struct, Tuple } from "effect"const Employee = Schema.Struct({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), baseSalary: Schema.BigDecimalFromString})const PublicEmployee = Employee.mapFields(Struct.omit(["baseSalary"]))const EmployeeRef = Employee.mapFields(Struct.pick(["id"]))const EmployeePatch = Employee.mapFields(Struct.map(Schema.optionalKey)) // PATCH body: every key may be absentconst LevelChange = Employee.mapFields(Struct.mapPick(["level"], Schema.optionalKey)) // only `level` optionalconst Audited = Employee.mapFields(Struct.assign({ updatedBy: Schema.String }))// Different key names on the Encoded side: snake_case columns, camelCase domain.const EmployeeRow = Schema.Struct({ employeeId: Schema.Int, hiredAt: Schema.DateFromString}).pipe(Schema.encodeKeys({ employeeId: "employee_id", hiredAt: "hired_at" }))Schema.decodeUnknownSync(EmployeeRow)({ employee_id: 7, hired_at: "2026-01-05T00:00:00.000Z" })// { employeeId: 7, hiredAt: Date }// Add shared fields to every member of a union in one expression.const AuditedAction = Schema.Union([ Schema.TaggedStruct("Raise", { amount: Schema.Finite }), Schema.TaggedStruct("Bonus", { amount: Schema.Finite })]).mapMembers(Tuple.map(Schema.fieldsAssign({ actorId: Schema.String })))
Need
Pass to mapFields
Keep / drop keys
Struct.pick([...]), Struct.omit([...])
Make every key optional / required
Struct.map(Schema.optionalKey) or Struct.map(Schema.optional); Struct.map(Schema.requiredKey) or Struct.map(Schema.required)
Change only some keys
Struct.mapPick(keys, f), Struct.mapOmit(keys, f), Struct.evolve({ key: f })
Add or replace fields
Struct.assign({ ... })
Rename decoded keys
Struct.renameKeys({ old: "new" }); pair it with Schema.encodeKeys to keep the old wire name
Mutable properties
Struct.map(Schema.mutableKey); for an array or tuple schema use Schema.mutable(schema) (shallow; it keeps the schema's checks and annotations and throws for a schema that carries an encoding). Every constructor infers readonly by default
Warning:mapFieldsdrops struct-level .check(...) filters, because the old predicate may not type-check against the new shape. Re-attach the rule, or pass { unsafePreserveChecks: true } as the second argument when the predicate provably still applies.
Schema.encodeKeys leaves unmapped keys alone and fails at construction when two fields map to the same encoded name. Schema.annotateKey({ ... }) attaches key-level metadata (title, description, messageMissingKey) that JSON Schema output and error messages use. A declared struct field may be inherited from the input's prototype and is copied to an own property of the output; check ownership before parsing if every field must be own. The exception is a field named after an Object.prototype member (toString, constructor, valueOf, hasOwnProperty, __proto__, …): it is read only as an own property, so Schema.Struct({ toString: Schema.optionalKey(Schema.String) }) accepts {} instead of seeing the inherited function.
Union([...]) normally evaluates viable members in order, but it first uses literal sentinel fields to discard contradicted candidates. The same pruning applies to nested unions by collecting sentinels common to their members, so an error tree may omit branches already contradicted by the observed discriminator. Literals([...]) is the array form of a literal union; supports .pick([...]) and .transform([...]). Schema.StringForLiteralAutocomplete is an alias for Schema.String that editors treat as a plain string for autocomplete purposes; pair it with Union and Literals to accept any string while still suggesting the known literals (Union([StringForLiteralAutocomplete, Literals(["GET", "POST"])])). Record(key, value) takes two positional schemas. Tuple([...]) takes an element array. Every list-taking constructor — Union, Tuple, TupleWithRest, StructWithRest, Literals, TemplateLiteral, TemplateLiteralParser, and the mapMembers / mapElements callbacks — expects a fixed-length tuple: write it inline or as const. A widened array such as Object.values(schemas) or a .map(...) result still type-checks but is unsupported and loses positional typing. Refined key schemas in a Record select matching properties rather than rejecting the whole object. A Schema.Enum(...) or literal-union key declares every member as a required property. Record values cannot be Schema.optionalKey(...) or Schema.optional(...) — construction throws, because an index signature already lets keys be absent; use Schema.UndefinedOr(value) to allow undefined values.
If encoded record keys transform to the same output key, there is no collision combiner: later synchronous entries win, while effectful concurrent decoding can make completion order decide the winner. Design key transformations to remain injective instead of relying on overwrite order.
TaggedUnion builds a discriminated union from a map of tag → fields and provides a type-safe .match:
.match also has a data-last form, CompAction.match({ Raise: ..., Promotion: ..., Bonus: ... }), which returns a reusable function; each handler receives its narrowed member and the result type is the union of the handlers' returns.
TaggedUnion and a union augmented with Schema.toTaggedUnion(tag) also expose .tag (the property key used as discriminator, e.g. "_tag") and .discriminants (an ordered tuple of their literal tag values). Duplicate or missing discriminants are rejected (at runtime) while building the augmented union; there is no compile-time uniqueness check, so generic member lists type-check. The same augmentation provides .cases (member schema per tag), .guards, .isAnyOf([...tags]), and .matchOrElse(value, cases, orElse), which handles a subset of tags and hands every remaining member — typed as the residual union — to orElse. isAnyOf accepts only tags of the union, so a misspelled tag or a widened string[] is a type error, and it narrows the value in both branches from the key list's type. For a list known only at runtime, use a plain check such as allowed.includes(action._tag): the false branch of isAnyOf would also exclude tags that the runtime list does not contain.
Tagged structs.Schema.tag("Raise") is a literal field with a constructor default, and Schema.TaggedStruct("Raise", fields) is shorthand for a struct whose _tag is that field. make fills the tag; decoding and encoding still require it on the wire. When the external payload has no discriminator, Schema.tagDefaultOmit supplies it while decoding or constructing and strips it on encode.
Self-contained source · Type-checked
ts
import { Schema } from "effect"const Raise = Schema.TaggedStruct("Raise", { amount: Schema.Finite })Raise.make({ amount: 5 }) // { _tag: "Raise", amount: 5 }// Schema.decodeUnknownSync(Raise)({ amount: 5 }) fails: Missing key at ["_tag"]// The payroll vendor sends no discriminator: add it on decode, strip it on encode.const VendorRaise = Schema.Struct({ amount: Schema.Finite }).mapFields((fields) => ({ ...fields, _tag: Schema.tagDefaultOmit("Raise")}))Schema.decodeUnknownSync(VendorRaise)({ amount: 5 }) // { amount: 5, _tag: "Raise" }Schema.encodeUnknownSync(VendorRaise)({ _tag: "Raise", amount: 5 }) // { amount: 5 }
Template literals and open-ended shapes.Schema.TemplateLiteral(parts) only validates a string against a template; Schema.TemplateLiteralParser(parts) decodes the same string into a typed tuple and encodes it back, replacing regex-plus-split code. TemplateLiteral throws at construction when a part carries an encoding (FiniteFromString), so transformed parts belong in the parser. Since onExcessProperty: "preserve" no longer exists, properties beyond the declared fields survive decoding only when the schema models them.
Self-contained source · Type-checked
ts
import { Schema } from "effect"// Validate only: Type is the template-literal string type `emp_${number}`.const EmployeeRef = Schema.TemplateLiteral(["emp_", Schema.Finite])// Parse: decode into a typed tuple, encode back to the string.const GrantRef = Schema.TemplateLiteralParser([ "grant-", Schema.FiniteFromString, "/", Schema.Literals(["RSU", "ISO"])])Schema.decodeUnknownSync(GrantRef)("grant-42/RSU") // ["grant-", 42, "/", "RSU"]Schema.encodeUnknownSync(GrantRef)(["grant-", 42, "/", "ISO"]) // "grant-42/ISO"// Index signature next to fixed fields: extra string labels are kept and validated.const LabeledEmployee = Schema.StructWithRest( Schema.Struct({ id: Schema.String }), [Schema.Record(Schema.String, Schema.String)])// readonly [string, number?, ...boolean[]]const ImportArgs = Schema.TupleWithRest( Schema.Tuple([Schema.String, Schema.optionalKey(Schema.Finite)]), [Schema.Boolean])// A literal-union key yields a fixed-key object type: both keys are required.const PayComponents = Schema.Record(Schema.Literals(["base", "bonus"]), Schema.Finite)
StructWithRest requires an object-shaped encoded base. Whole-object transformations (even with an empty rest list) are not supported: first complete the struct/rest schema, then apply wrappers such as Schema.fromJsonString. Transformations on individual fields remain supported. Object-shaped encoded types alone do not guarantee that every encoding is supported at runtime.
Also available: Schema.NonEmptyArray(item) (infers readonly [A, ...A[]]), Schema.ArrayEnsure(item) (a single value or an array decodes to an array; a one-element array encodes back to the single value), Schema.UniqueSymbol(sym), Schema.Enum(TsEnum) (exposes .enums; rejects non-finite numeric members), Schema.JsonObject (a string-keyed record of Schema.Json values — arrays and non-JSON leaves such as Date fail), and the primitives BigInt, Symbol, ObjectKeyword, Any, Unknown, Never, Null. Schema values keep their parts public — .fields, .members, .elements, .rest, .literals, .key / .value, .schema — so they can be recombined. Schema.Literal(0) and Schema.Literal(-0) each accept either signed zero and preserve the input's sign; add a transformation when a canonical sign matters.
Official guide: Basic Usage (its "Transforming Keys" passage is stale: records accept transformed key schemas).
check attaches one or more filters (predicates that do not change the type); built-in filters now carry an is prefix. refine attaches a type-narrowing refinement. Schema.makeFilter builds ad-hoc filters that can return rich failures: undefined/true for success, a string message, a { path, issue } for a nested failure, or an array of issues to report multiple failures at once.
Self-contained source · Type-checked
ts
import { Schema } from "effect"// Built-in checks (note the `is` prefix). check takes a variadic list.const Level = Schema.Int.pipe( Schema.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(10)))const NonEmptyName = Schema.String.check(Schema.isMinLength(1))const VestingMonths = Schema.Natural.check(Schema.isBetween({ minimum: 0, maximum: 48 }))// A custom cross-field check: a recommended salary must sit inside its band.const RaiseRecommendation = Schema.Struct({ proposedSalary: Schema.Finite, bandMin: Schema.Finite, bandMax: Schema.Finite}).check( Schema.makeFilter((o) => o.proposedSalary >= o.bandMin && o.proposedSalary <= o.bandMax ? undefined : { path: ["proposedSalary"], issue: "proposed salary is outside the comp band" } ))
Built-in checks by carrier. Every one takes a trailing annotations argument ({ message }, { expected }, ...); there are no bare minLength, between, or pattern names.
isGreaterThan, isGreaterThanOrEqualTo, isLessThan, isLessThanOrEqualTo, isBetween({ minimum, maximum }), isInt, isInt32, isUint32, isFinite, isMultipleOf(n) (throws for a zero or non-finite divisor)
Array
the string length checks, plus isUnique() and isUniqueKey() (unique first elements in an array of [key, value] tuples)
the comparison family with a suffix: isBetweenDate, isGreaterThanBigInt, isLessThanOrEqualToBigDecimal, ...
Prebuilt aliases cover the common combinations (Schema.NonEmptyString, Schema.Int, Schema.Natural, Schema.Trimmed). Duration has no dedicated family; write a makeFilter over Duration predicates.
isMinLength/isMaxLength/isBetweenLength count UTF-16 code units; isMinCodePoints/isMaxCodePoints/isBetweenCodePoints count Unicode code points instead. Neither counts grapheme clusters (user-perceived characters). JSON Schema measures code points: isMinLength(n) exports minLength: Math.ceil(n / 2), while isMaxLength(n) exports maxLength: n; isBetweenLength(min, max) uses those respective bounds. These are sound approximations of the UTF-16 checks, not exact replacements when round-tripping through JSON Schema.
Filter annotations, abort, and groups.Schema.makeFilter(predicate, annotations?, abort?) receives (input, ast, options) and may return undefined / true (pass), false, a message string, { path, issue }, a full SchemaIssue.Issue, or an array of those. Its annotations decide what every derivation sees: expected / message for error text, toJsonSchema so the rule reaches generated JSON Schema and OpenAPI (a custom predicate is otherwise invisible there), and arbitraryConstraint so the native generator satisfies the rule constructively instead of by rejection. .abort() on a filter stops later checks from running once it fails; Schema.makeFilterGroup([...checks], annotations) packages a reusable set.
Self-contained source · Type-checked
ts
import { Schema } from "effect"const slugPattern = "^[a-z0-9-]+$"const isSlug = Schema.makeFilter( (s: string) => new RegExp(slugPattern).test(s), { expected: "a lowercase slug", toJsonSchema: () => ({ pattern: slugPattern }), arbitraryConstraint: { patterns: [{ source: slugPattern, flags: "" }] } })// An empty string reports only the first failure, even with { errors: "all" }.const DepartmentSlug = Schema.String.check(Schema.isNonEmpty().abort(), isSlug)const CodeLength = Schema.makeFilterGroup( [Schema.isMinLength(3), Schema.isMaxLength(10)], { title: "cost-center code length" })const CostCenterCode = Schema.String.check(CodeLength, isSlug)
Order of narrowing: structure, then checks, then a refinement only if the static type really narrows, then the brand.
A check never trims, parses, or defaults — that is a transformation (section 6). A check that "fixes" its input cannot exist: the predicate's return value is a verdict, not a new value.
A check is synchronous and service-free. "Is this cost-center code still free?" is an effectful decode step whose requirement stays visible in the schema type (SchemaGetter.checkEffect), never a lookup hidden inside a predicate.
Bound attacker-reachable input in the schema itself — string lengths, collection sizes, recursion depth — and test those bounds like any other rule.
Transformations are written with decodeTo(target, transformation), where the transformation is a SchemaTransformation (two-way) or a pair of one-way SchemaGetters.
Self-contained source · Type-checked
ts
import { Schema, SchemaGetter, SchemaTransformation } from "effect"// Pair of getters: explicit decode + encode directions. Share count <-> string.const SharesFromText = Schema.String.pipe( Schema.decodeTo(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), { decode: SchemaGetter.transform((s) => Number(s)), encode: SchemaGetter.transform((n) => String(n)) }))// A prebuilt two-way SchemaTransformation reads cleaner when one exists.// The HRIS encodes employment status as "active"/"terminated".const ActiveFromStatus = Schema.Literals(["active", "terminated"]).pipe( Schema.decodeTo( Schema.Boolean, SchemaTransformation.transform({ decode: (status) => status === "active", encode: (isActive) => (isActive ? "active" : "terminated") }) ))Schema.decodeUnknownSync(SharesFromText)("4000") // 4000Schema.decodeUnknownSync(ActiveFromStatus)("active") // true
For a transformation that can fail, use SchemaGetter.transformEffect and return an Effect that fails with a SchemaIssue; the two-way equivalent is SchemaTransformation.transformEffect, matching Config.mapEffect and the rest of the library. When a conversion is decode-only, use SchemaGetter.forbiddenEncoding as the encode leg so an attempt to encode fails with a Forbidden issue instead of inventing a value. For async validation, use SchemaGetter.checkEffect inside a Schema.decode({...}) — the v4 replacement for filterEffect.
Self-contained source · Type-checked
ts
import { Effect, Number, Option, Schema, SchemaGetter, SchemaIssue } from "effect"// A share count must be a real non-negative integer; reject junk like "abc".const SharesFromStringStrict = Schema.String.pipe( Schema.decodeTo(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), { decode: SchemaGetter.transformEffect((s) => // Number.parse returns Option<number>; turn None into a schema issue. Option.match(Number.parse(s), { onNone: () => Effect.fail(new SchemaIssue.InvalidValue({ message: "not a share count" }, s)), onSome: (n) => Effect.succeed(n) }) ), encode: SchemaGetter.String() }))
Data flow of decodeTo.source.pipe(Schema.decodeTo(target, bridge)) decodes with the source schema first, maps source Type to target Encoded through the bridge, then decodes with the target schema; encoding runs the same three steps in reverse. Three consequences:
When source Type already equals target Encoded, call decodeTo(target) with no bridge. That is schema composition.
When the target is a container of the same item schema, wrap the item in Schema.toType(item) so elements are not decoded twice.
A transformation has three independent failure sites — the source schema, the getter, the target schema — and each takes its own message (Custom error messages).
Official guide: Schema Transformations (it still spells transformEffect as transformOrFail, and it predates SchemaGetter.forbiddenEncoding — this page and the edition's tagged source win).
brand narrows the type nominally (no runtime check). fromBrand additionally wires in a Brand.Constructor's checks.
Self-contained source · Type-checked
ts
import { BigDecimal, Schema } from "effect"const EmployeeId = Schema.Int.check(Schema.isGreaterThan(0)).pipe(Schema.brand("EmployeeId"))type EmployeeId = typeof EmployeeId.Type // number & Brand<"EmployeeId">// Branding usually rides on top of validation. Money is a non-negative BigDecimal.const Money = Schema.BigDecimal.check( Schema.isGreaterThanOrEqualToBigDecimal(BigDecimal.fromBigInt(0n))).pipe(Schema.brand("Money"))type Money = typeof Money.Type // BigDecimal & Brand<"Money">
A brand is identity, not validation.Schema.String.pipe(Schema.brand("EmployeeId")) accepts ""; the rules come from the checks underneath. Three habits follow:
A brand is earned by decoding (or make).raw as EmployeeId bypasses the gate and makes the brand meaningless, so reserve the cast for test fixtures of already-valid data.
Brands prevent mixing, they do not sanitize. An EmployeeId that is also a SQL fragment is still a SQL fragment.
One owner per rule. When a Brand constructor already exists, reuse it with Schema.fromBrand(identifier, constructor) — identifier first — instead of restating its checks.
identifier must be a single concrete string literal.Schema.brand rejects a union, a widened string, or an open template-literal type for its identifier at the type level — the brand key has to be one known name. The brand is also type-only: it narrows the TypeScript type but is not recorded as an AST annotation, so schema representations and generated schema code omit it entirely. Reapply Schema.brand after rebuilding a representation or regenerating a schema when the nominal type still matters (checks added by fromBrand do survive, via the constructor's own .checks). Schema.fromBrand's identifier must match the constructor's one brand key; apply fromBrand repeatedly to compose distinct brands, and represent alternatives with Union.
Self-contained source · Type-checked
ts
import { Brand, Schema } from "effect"type PositiveInt = number & Brand.Brand<"PositiveInt">const PositiveInt = Brand.check<PositiveInt>(Schema.isInt(), Schema.isGreaterThan(0))// The schema runs the constructor's checks and produces the same branded type.const PositiveIntSchema = Schema.Number.pipe(Schema.fromBrand("PositiveInt", PositiveInt))Schema.decodeUnknownSync(PositiveIntSchema)(3) // 3 as PositiveInt; -3 fails
withConstructorDefault fills a field when building a value with Schema.make/new. withDecodingDefault / withDecodingDefaultKey fill a missing field during decoding. Defaults are Effects and may be effectful (generated id, clock-derived timestamp).
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"const GrantDefaults = Schema.Struct({ // Filled by the constructor when omitted (rating has only a decoding default, so make still requires it). vestingMonths: Schema.Natural.pipe( Schema.optionalKey, Schema.withConstructorDefault(Effect.succeed(48)) ), // Filled while decoding when the HRIS omits the rating. rating: Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed("meets")))})GrantDefaults.make({ rating: "meets" }) // { vestingMonths: 48, rating: "meets" }Schema.decodeUnknownSync(GrantDefaults)({ vestingMonths: 36 }) // { vestingMonths: 36, rating: "meets" }
Which side, and what triggers it. Five helpers, two axes: is the default written in Encoded or Type terms, and does an explicit undefined count as "missing"?
Helper
Default is written as
Fires when
Explicit undefined
withDecodingDefaultKey(effect)
an Encoded value, then decoded
key is absent
rejected
withDecodingDefault(effect)
an Encoded value, then decoded
key is absent or undefined
replaced by the default
withDecodingDefaultTypeKey(effect)
a Type value
key is absent
rejected
withDecodingDefaultType(effect)
a Type value
key is absent or undefined
replaced by the default
withConstructorDefault(effect)
the constructor input
only make / new
not applicable — decoding never consults it
Prefer the Type variants once a field has a transformation: the default for a FiniteFromString field is 1, not "1", and for a DateTimeUtcFromString field it can be DateTime.now, which reads the Clock and is therefore controllable with TestClock.
A decoding default fires for absence only. An explicit false, 0, or "" is a present value and survives; an explicit value that violates the field's checks fails instead of being replaced; null is not absence. This is exactly the bug that value || fallback after decoding introduces.
{ encodingStrategy } (all four decoding helpers) decides what encoding writes: "passthrough" (the default) emits the value; "omit" always drops the key, so a non-default value does not survive a round trip. "omit" suits constants — Schema.tagDefaultOmit is built from it.
Constructor defaults never apply while decoding, including inside Schema.Class: an optionalKey field with withConstructorDefault(Effect.succeed([])) decodes to an absent key and gets [] only through new / make. They also do not make the encoded key optional.
A constructor default is re-evaluated on every make / new (Effect.sync(() => crypto.randomUUID()) yields fresh values), it travels with the field (Schema.Struct({ id: Grant.fields.id }) inherits it), and an outer default may be partial: its type is the constructor input, so nested defaults complete it.
An Effect-valued decoding default need not make decoding asynchronous. An already-successful effect such as Effect.succeed(value) preserves synchronous decoding. This is not a promise that arbitrary Effects can run in a synchronous decoder: defaults needing asynchronous work or services still need an appropriate Effect runner and provided services.
Self-contained source · Type-checked
ts
import { DateTime, Effect, Schema } from "effect"const ApprovalPolicy = Schema.Struct({ // Type-side default: a decoded number, not the wire string "1". requiredApprovers: Schema.FiniteFromString.pipe( Schema.withDecodingDefaultTypeKey(Effect.succeed(1)) ), // Clock-driven, so TestClock controls it in tests. effectiveAt: Schema.DateTimeUtcFromString.pipe( Schema.withDecodingDefaultTypeKey(DateTime.now) ), notifyManager: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(true)))})Schema.decodeUnknownSync(ApprovalPolicy)({ notifyManager: false })// { requiredApprovers: 1, effectiveAt: <now>, notifyManager: false } — the explicit false survivesconst Notifications = Schema.Struct({ channel: Schema.String.pipe(Schema.withConstructorDefault(Effect.succeed("email"))), digest: Schema.Boolean})const ReviewCycleSettings = Schema.Struct({ // Partial outer default; the inner `channel` default completes it. notifications: Notifications.pipe(Schema.withConstructorDefault(Effect.succeed({ digest: true })))})ReviewCycleSettings.make({}) // { notifications: { channel: "email", digest: true } }
Test every default with three cases: key omitted decodes to the default; an explicit falsy value is kept; an explicit invalid value still fails. A derived arbitrary cannot cover the first case — it generates Type values, never "key omitted" wire input — so keep these as named encoded fixtures.
Official guides: Advanced Usage (decoding defaults and the missing / undefined / null tables), Default Constructors (nested, lazy, and class-level constructor defaults).
Schema.Class produces a real class whose constructor validates its fields, with a derived schema attached. TaggedClass auto-adds a _tag. Error and TaggedError produce yieldable, schema-validated errors: yield* new EmployeeNotFound({...}) works inside Effect.gen. Schema.Opaque types the decoded value as a nominal class rather than its structural shape. A class supports Base.extend<Sub>("Sub")(extraFields) for schema-validated subclassing; the Self generic is required just as it is on Schema.Class (omit it and the result is the MissingSelfGeneric error type), and the subclass inherits fields, checks, getters, and methods.
These class builders are distinct from validating an existing JavaScript Error: use Schema.ErrorInstance(options?) for that. Its JSON representation contains message plus optional name and cause; stack data is omitted unless includeStack is enabled, and excludeCause removes the cause. Persisted schema representations containing it need SchemaRepresentation.ErrorInstanceReviver; every built-in reviver lives in SchemaRepresentation, built from SchemaRepresentation.makeReviverDeclaration, makeReviverFilter, and makeReviverFilterGroup.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"class EquityGrant extends Schema.Class<EquityGrant>("EquityGrant")({ employeeId: Schema.Int.check(Schema.isGreaterThan(0)), shares: Schema.Natural, grantDate: Schema.Date}) {}const grant = new EquityGrant({ employeeId: 1, shares: 4000, grantDate: new Date() })console.log(`${grant}`) // EquityGrant({"employeeId":1,"shares":4000,"grantDate":2026-…})// The house error idiom: TaggedError + Schema.Defect() for the cause.class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { id: Schema.Int.check(Schema.isGreaterThan(0)), cause: Schema.Defect()}) {}const lookup: Effect.Effect<never, EmployeeNotFound> = new EmployeeNotFound({ id: 42, cause: "no such row in HRIS" })
What a class schema is. A declaration wrapped around its field struct: decoding turns a plain object into an instance, encoding turns an instance back into a plain object (a plain object passed to encode fails with Expected <identifier>). So a class is a codec, not only a validated constructor.
The identifier is load-bearing. It is exposed as Grant.identifier, stored in the AST, used in diagnostics and as the JSON Schema $defs name, and it drives a runtime marker that still recognizes instances after a hot-module reload replaces the constructor. It must be explicit because the JavaScript class name is not available while extends is evaluated and may be minified. Keep it unique and stable.
Instances compare structurally. They extend Data.Class, so Equal.equals(a, b) is true for two separately decoded instances with equal fields while a === b is false. Schema.toEquivalence(Grant) compares only the declared fields, ignoring any undeclared runtime properties on the instance.
new always builds a fresh instance; Grant.make(existing), makeOption, and makeEffect return an existing instance unchanged.
The fields argument may be a whole Schema.Struct(...).check(...), so a cross-field rule is enforced by new, decoding, and encoding alike; a second argument carries annotations (title, description).
Struct or Class? Default to Struct for boundary records. Choose Class for a validated constructor, methods or getters, nominal identity, or an integration that needs instances — not merely because the data is "domain data".
decode produces an instance; encode leaks no internals
the class is a codec; getters and private state must not reach the wire
round trip under a stated equivalence
use Equal.equals or Schema.toEquivalence, never ===
the JSON form
JSON.stringify(instance) is not the codec; derive Schema.toCodecJson(Class)
Official guide: Class APIs (its sample output for a failing new shows formatted issue text; construction throws the generic message described in section 4 of Schema in Depth).
This page continues the Schema guide past the everyday codec work. It covers what you reach for once a schema owns a real boundary: annotations and derived artifacts, serialization codecs, recursive and custom schemas, deliberate construction fallbacks, parse options as boundary policy, optional fields and null, Effect data types on the wire, custom error messages, and schemas that need services. Every section builds on the Type / Encoded model from the main page; the lower-level modules behind it are on Schema Tooling & Internals.
annotate attaches metadata (title, description, examples, custom keys) that flows into JSON Schema, error messages, and docs. Derivations from the same schema object: Arbitrary.schema (native property-test generator, from effect/Arbitrary), toEquivalence (structural equality), toFormatter (pretty-printer), toStandardSchemaV1 (Standard Schema interop), toJsonSchemaDocument.
Self-contained source · Type-checked
ts
import { Arbitrary, Schema } from "effect"const CompBand = Schema.Struct({ level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), salaryMid: Schema.Finite}).pipe( Schema.annotate({ title: "CompBand", description: "Salary midpoint for a level" }))const eq = Schema.toEquivalence(CompBand)eq({ level: 5, salaryMid: 190000 }, { level: 5, salaryMid: 190000 }) // true// Native generator for the decoded Type: there is no `Schema.toArbitrary` or// fast-check bridge; checks like isBetween generate constructively.const CompBandArb = Arbitrary.schema(CompBand) // Arbitrary<{ level: number; salaryMid: number }>const fiveBands = Arbitrary.sampleEffect(CompBandArb, { count: 5, seed: 42 })
Three attachment points.annotate documents the decoded side, Schema.annotateEncoded the encoded side (the one JSON Schema sees for a transformation), and Schema.annotateKey a struct field or tuple element. .annotate(...) called after .check(...) lands on the last check, not on the base schema, and Schema.resolveAnnotations(schema) reads from the same place — so annotate first, then add checks, when the metadata describes the schema as a whole. examples and default annotations are documentation only; they never affect decoding or construction. Annotations accept any string key, so nothing rejects a key the library never reads.
Migration: The v3 concurrency, batching, and parseOptions annotations were removed, but .annotate({ concurrency: "unbounded", batching: true }) or .annotate({ parseOptions: { onExcessProperty: "error" } }) still compiles after renaming .annotations to .annotate, and is silently ignored. Nothing fails: parsing becomes sequential, Effect.request calls from sibling elements stop sharing batches, and a nested struct that used to refuse unknown keys now strips them. Search for those keys when migrating and move them to runtime parse options (section 5).
Typed custom annotations. Annotations are an open record. Make a team-specific key (a PII marker, a deprecation flag, a UI hint) type-checked by augmenting the Annotations interface, and read it back with Schema.resolveAnnotations (key-level ones with Schema.resolveAnnotationsKey).
works on the decoded Type side (transformations are dropped first, so a record with transformed keys compares its decoded entries); compares only what the schema describes (extra properties are ignored) and recurses through structs and arrays; schemas that say nothing about structure (Unknown, Any, an un-annotated declaration) fall back to Equal.equals
Schema.overrideToEquivalence(() => (a, b) => ...) for "same id means same entity"; a toEquivalence annotation on a declaration
Schema.toFormatter
builds (value: Type) => string following the decoded side of the schema; it does not validate. Its onBefore hook therefore receives type-side AST nodes with the encoding links removed, not the original nodes, so a hook that matches on encoding metadata or node identity no longer fires — attach per-schema formatting with overrideToFormatter instead. Distinct from the issue formatters in SchemaIssue and from the general Formatter module
Schema.overrideToFormatter; a toFormatter annotation; an onBefore(ast, recur) hook that intercepts node kinds (return undefined to keep the default)
Arbitrary.schema
built-in checks generate constructively; a custom filter is satisfied by rejection unless it carries an arbitraryConstraint annotation (section 5 of Schema); a declaration supplies a generatable stand-in with a toCodecArbitrary annotation
Boundary formats are codecs, not ad-hoc JSON.stringify calls. fromJsonString(schema) parses JSON text and then validates the parsed value; fromFormData(schema) and fromURLSearchParams(schema) do the same for browser form and query-string containers. In the other direction, derive a canonical representation with toCodecJson, toCodecStringTree, or toCodecIso.
Form/query bracket paths are built by SchemaGetter.makeTreeRecord. Numeric indexed containers become arrays only when there are at most 20 holes below the highest index; sparser input becomes an object keyed by index strings instead of a huge sparse array. A payload such as items[4294967294]=x is therefore not a request to allocate a giant array. Model and validate the expected shape rather than relying on numeric brackets always producing arrays.
toCodecJson recursively makes non-JSON-native values—such as Date, BigInt, Uint8Array, maps, sets, classes, and Option—reversible through JSON-safe data. A declaration or class can provide a custom toCodecJson annotation; JSON Schema generation reuses that representation, so runtime serialization and the published contract stay aligned. toCodecStringTree converts leaves to strings for form/query/XML-shaped data, while toCodecIso exposes a schema's isomorphic representation for transformations and optics.
Self-contained source · Type-checked
ts
import { Schema } from "effect"const Grant = Schema.Struct({ employeeId: Schema.String, shares: Schema.Natural, grantedAt: Schema.Date})// Runtime value <-> JSON-safe object. Date encodes as an ISO string.const GrantJson = Schema.toCodecJson(Grant)const encoded = Schema.encodeUnknownSync(GrantJson)({ employeeId: "e-42", shares: 4_000, grantedAt: new Date("2026-08-12T10:00:00.000Z")})const decoded = Schema.decodeUnknownSync(GrantJson)(encoded)// Complete JSON-text boundary: string <-> decoded Grant. Derive the JSON-safe// representation first, then parse/stringify that representation.const GrantFromJsonText = Schema.fromJsonString(GrantJson)const roundTrip = Schema.decodeUnknownSync(GrantFromJsonText)( JSON.stringify(encoded))
Go services.Schema.toCodecGoJson(schema) (unstable) wraps the canonical JSON codec for responses written by Go's encoding/json, which writes nil slices and maps as null: a null optional key decodes as a missing key, and a null required array or record decodes as an empty collection; schemas that already accept null are left alone. It covers only those null rules — durations, base64 bytes, and numbers-as-strings still belong in the field schemas.
The JSON Schema and schema representation of fromJsonString(schema) keep the inner schema as contentSchema with contentMediaType: "application/json", so tools and OpenAPI (including SSE event data) see what the string contains.
Do not use the internal Schema.UnknownFromJsonString; compose Schema.fromJsonString(Schema.Unknown) when the JSON value is intentionally unknown. The JSON forms of Option, Result, Exit, collections, and Duration are tabulated in Effect data types at the boundary.
Use Schema.suspend(() => schema) to make a recursive edge lazy. Recursive declarations are the main case where an explicit Schema.Codec<Type, Encoded> annotation is useful because TypeScript cannot infer a self-reference safely. For an otherwise unsupported runtime type, use Schema.declare(guard, annotations?); use declareConstructor when the custom type itself is parameterized by child schemas. Prefer Schema.instanceOf for ordinary class-instance checks.
When Encoded differs from Type.Schema.Codec<OrgNode> only works while both sides coincide. As soon as a field transforms (DateFromString, FiniteFromString), annotate the suspend thunk with both parameters — Schema.Codec<Node, NodeEncoded> — or TypeScript reports an assignability error. Keep the non-recursive fields in a constant and derive both interfaces from it, adding only the recursive member by hand. A recursive Schema.Class follows the same rule with the class itself as the Type (Schema.Codec<Department, DepartmentEncoded>), and mutually recursive schemas annotate the suspend on each back-edge.
Give a declaration an encoded form.Schema.declare only knows how to recognize a value. Without a toCodecJson or toCodec annotation, Schema.toCodecJson uses Json as the encoded schema: JSON-native declaration values can encode unchanged, while non-JSON values such as URL instances fail with Expected JSON value. Supply an explicit representation when the domain value is not already JSON or needs a different wire shape. The mechanism is an annotation returning Schema.link<T>()(representationSchema, { decode, encode }): toCodecJson for the JSON form, toCodecStringTree / toCodecIso for the other canonical codecs, toCodecArbitrary for a generatable stand-in, plus toEquivalence and toFormatter. Inside a custom parser, build issues as new SchemaIssue.InvalidType(ast, input, options) / new SchemaIssue.InvalidValue({ message }, input, options) so reportInput is honored.
Self-contained source · Type-checked
ts
import { Effect, Schema, SchemaGetter, SchemaIssue } from "effect"// A teaching declaration; for real URLs use the built-in Schema.URL / Schema.URLFromString.const BenefitsPortalUrl = Schema.declare( (value): value is URL => value instanceof URL, { expected: "URL", toCodecJson: () => Schema.link<URL>()(Schema.String, { decode: SchemaGetter.transformEffect((text: string, options) => Effect.try({ try: () => new URL(text), catch: () => new SchemaIssue.InvalidValue({ message: "not a URL" }, text, options) }) ), encode: SchemaGetter.transform((url: URL) => url.href) }) })const PortalJson = Schema.toCodecJson(Schema.Struct({ portal: BenefitsPortalUrl }))Schema.encodeUnknownSync(PortalJson)({ portal: new URL("https://benefits.example.com") })// { portal: "https://benefits.example.com/" }
In generic helpers, use S extends Schema.Top (or a narrower constraint) and return S-derived types. Avoid broad Schema.Top, Schema.Schema<T>, or Schema.Codec<T, E> annotations on concrete non-recursive schemas: widening erases mutability, optionality, constructor, and other type-level metadata baked into the precise schema.
Official guides: Advanced Usage (mutual recursion, declarations with type parameters), Class APIs (recursive classes).
Construction is not decoding.make, makeOption, makeEffect, and class new take the decoded Type (after constructor defaults) and run checks; they never turn an encoded string into a transformed value, so Schema.FiniteFromString.make wants a number. Decode wire input; construct in already-trusted code.
Constructor
On invalid input
Use when
.make(input) / new Class(input)
throws a plain Error("Schema validation failed") whose cause is the SchemaIssue.Issue — not a SchemaError, and the message is not formatted
invalid input is a programming bug
.makeOption(input)
Option.none()
probing
.makeEffect(input)
fails with the raw SchemaIssue.Issue
the failure should stay typed
Self-contained source · Type-checked
ts
import { Schema, SchemaIssue } from "effect"const Level = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 }))try { Level.make(42)} catch (error) { // The thrown message is generic; the structured issue rides in `cause`. if (error instanceof Error && SchemaIssue.isIssue(error.cause)) { console.log(SchemaIssue.makeFormatterDefault()(error.cause)) // Expected a value between 1 and 10 }}Level.makeOption(42) // Option.none()Level.make(42, { disableChecks: true }) // 42 — a deliberate hole
Warning:{ disableChecks: true } (a second argument to every constructor and class new, and a parse option for decoding) skips checks while still applying defaults and transformations. It is a measured optimization for data that was validated moments ago, never an ingress default.
Deliberate fallbacks.SchemaParser.makeOption(schema) is the standalone form of .makeOption(...). Schema.catchDecoding can replace a decoding failure with an effectful Option fallback; catchDecodingWithContext may additionally require services. These middlewares intentionally weaken a boundary, so reserve them for an explicit compatibility/defaulting policy rather than hiding malformed input.
Official guide: Default Constructors (it types makeEffect as failing with SchemaError and prints formatted text for a throwing make; use the behavior in the table above).
A schema describes a shape; parse options describe how this boundary wants that shape parsed. Keep them at the call site, not in the schema, so one schema can back a strict ingress and a tolerant reader without being duplicated.
Option
Default
Effect
errors
"first"
"all" collects every issue the traversal can reach
onExcessProperty
"ignore"
"ignore"strips undeclared keys from the result; "error" fails with an unexpected-key issue at that path. Applies to decoding and encoding, at every nesting level
concurrency
sequential
number | "unbounded" with Effect.forEach semantics, for effectful children. There is no batching option: sibling Effect.request calls share a resolver batch only when this lets them be pending together. Under sequential parsing, children that each await one request send separate batches; requests started concurrently inside one transformation, or by other fibers, still batch. Bound batch sizes on the RequestResolver, not here
reportInput
false
attaches rejected input values to issues (read them via SchemaIssue.hasInput); can retain secrets and PII
disableChecks
false
skips checks, still applies defaults and transformations (section 4)
Self-contained source · Type-checked
ts
import { Schema } from "effect"const PayrollTarget = Schema.Struct({ id: Schema.NonEmptyString, timeoutMs: Schema.Int.check(Schema.isGreaterThan(0))})// Tolerant reader: undeclared keys are stripped from the result.const decodeLenient = Schema.decodeUnknownEffect(PayrollTarget)// Strict ingress: a typo'd or smuggled key is an error; report everything at once.const decodeStrict = Schema.decodeUnknownEffect(PayrollTarget, { onExcessProperty: "error", errors: "all"})const input = { id: "adp", timeoutMs: 5_000, admin: true }const lenient = decodeLenient(input) // succeeds with { id: "adp", timeoutMs: 5000 }const strict = decodeStrict(input) // fails: Expected no excess property at ["admin"]// Options given when applying the decoder override the creation-time ones, key by key.const firstOnly = decodeStrict(input, { errors: "first" })
The excess-property policy is part of the contract. A struct looks strict in its type while the runtime quietly accepts { id, admin: true } and drops the extra key. That is right for a tolerant reader or a projection, and wrong for a config file, a signed payload, a PATCH body, or any input where a typo'd or smuggled key must be noticed. Decide per boundary and test the chosen policy — it is the case most often forgotten.
The same option name controls JSON Schema generation. Pass "error" in both places when the published document and the runtime parser must agree.
To keep unknown keys, model them with Schema.Record or Schema.StructWithRest (section 4 of Schema). There is no onExcessProperty: "preserve" option, because it would let unvalidated values cross the boundary.
Options apply to the whole operation. A parseOptionsannotation does not affect parsing, so there is no per-node override; there is no propertyOrder option either, and decoded key order is unspecified — sort at presentation time if order matters.
Excess-property checks only see enumerable own properties. A non-enumerable own property — Error#stack on a TaggedError instance, for example — is never flagged as an excess property, even under onExcessProperty: "error", unless the schema explicitly declares it; the same rule applies to the properties an index signature can match.
errors: "all" does not mean "every rule ran". An invalid field prevents a struct-level check from running (a cross-field rule is reported only once its fields parse), and an aborting filter stops later checks. Do not assert on the absence of an issue under "all".
concurrency parallelizes product children only — tuple and array elements, struct fields, record entries, structs with rest — independently at each nesting level. Union members always stay sequential, because speculatively running candidates would execute transformations that are not selected. With errors: "first" the first observed failure interrupts its siblings; array order is preserved, but issue order (and the winner of colliding transformed record keys) follows completion order.
A field specification must answer five input states: key absent, present undefined, present null, present valid, present invalid (always a failure). The helpers differ in exactly those cells.
Field schema
Key absent
undefined
null
Decoded Type
None encodes to
Schema.optionalKey(S)
absent
fails
fails
key?: A
—
Schema.optional(S)
absent
undefined
fails
key?: A | undefined
—
Schema.optionalKey(Schema.NullOr(S))
absent
fails
null
key?: A | null
—
Schema.OptionFromOptionalKey(S)
None
fails
fails
Option<A>
absent key
Schema.OptionFromOptional(S)
None
None
fails
Option<A>
absent key
Schema.OptionFromOptionalNullOr(S)
None
None
None
Option<A>
absent key, or { onNoneEncoding: null | undefined }
optionalKey rejects an explicit undefined; only optional accepts it. With exactOptionalPropertyTypes off, TypeScript will not flag { key: undefined } even though decoding fails.
Schema.Option(S) is not a wire codec. It expects an actual Option on both sides and only transforms the payload, so raw JSON fails with Expected Option. The OptionFrom* family is what bridges wire absence to Option; section 7 covers the JSON form of a real Option.
null is never absence unless the schema says so. To collapse a wire null into an absent key (or a missing key into null), compose optionalKey(NullOr(S)) with a decodeTo whose getters use SchemaGetter.transformOptional — see the example under SchemaGetter.
Two steps, not one. The constructors for Effect's own data types — Schema.Option, Schema.Result, Schema.Exit, Schema.ReadonlyMap, Schema.ReadonlySet, Schema.HashMap, Schema.HashSet, Schema.Duration, Schema.Redacted — take the runtime value on both sides and apply the inner schemas only to the contents. The wire form is a separate, explicit step: Schema.toCodecJson(schema).
Self-contained source · Type-checked
ts
import { HashMap, Schema } from "effect"const MeritBudgets = Schema.HashMap(Schema.String, Schema.FiniteFromString)// Runtime value on both sides: HashMap<string, string> -> HashMap<string, number>.// Raw JSON fails here with "Expected HashMap".Schema.decodeUnknownSync(MeritBudgets)(HashMap.make(["eng", "100"]))// The JSON form is opt-in: an array of [key, value] entries.const MeritBudgetsJson = Schema.toCodecJson(MeritBudgets)Schema.decodeUnknownSync(MeritBudgetsJson)([["eng", "100"]]) // HashMap with "eng" -> 100
{ _tag: "Success", value } or { _tag: "Failure", cause: [...] }, where cause is a flat array of reasons such as { _tag: "Fail", error } and { _tag: "Die", defect }; Schema.Defect() revives error-like defects as { name, message }. Schema.Cause encodes each reason to exactly these wire fields, so strict encoding (onExcessProperty: "error") yields the same output
ReadonlySet / HashSet
array of items
ReadonlyMap / HashMap
array of [key, value] entries
Schema.Duration
{ _tag: "Millis", value }, { _tag: "Nanos", value: "<digits>" }, or an infinity tag, so infinite and sub-millisecond durations survive
Pick a Duration codec by the precision you promise.
Codec
Encoded
Notes
Schema.Duration
a Duration
no wire claim; derive toCodecJson for the tagged form above
Schema.DurationFromMillis
number
a nanosecond-precision duration beyond 2^53 ns does not round-trip
Schema.DurationFromNanos
bigint
lossless for finite durations
Schema.DurationFromString
string
decodes anything Duration.fromInput parses ("250 millis"), encodes parseable text ("2000 millis"); it is what Config.Duration uses
Schema.DurationFromIsoString
string
ISO 8601 ("PT1H30M", "P1W2D") via Duration.fromIso / formatIso; rejects years and months; encoding fails for infinite durations
The general lesson: when the encoded carrier is narrower than the Type, either constrain the Type with a check (which also constrains the derived arbitrary) or exclude that field from generic round-trip properties and test it with explicit values.
the first expects a Redacted on both sides and rewraps the inner schema's transformed result (Schema.Redacted(Schema.NumberFromString) decodes a Redacted<string> to a Redacted<number>, keeping the label); the second decodes a raw value and wraps it. The "refuse to encode" option is spelled differently on each
the string form requires a unit ("5 MiB") and encodes the exact count as "5242880 bytes"; see ByteSize
Exact fractions (unstable)
Schema.Rational, Schema.RationalFromString
the first validates Rational values and encodes to "numerator/denominator" under toCodecJson; the second decodes that text from a string field; see Rational
strict SemVer 2.0.0 and npm-style ranges; see SemVer
Crypto keys (unstable)
Schema.AeadKey, MacKey, SignaturePrivateKey, … with *FromBytes / *FromFormat codecs
opaque key values for the effect/crypto services; the byte and format codecs for secret or private keys only decode unless constructed with { allowEncode: true } — see Cryptography
Messages are plain annotations on the node that fails. The default formatters honor them first and fall back to generated text.
Failure
Where the text goes
Type mismatch
.annotate({ message }) on the base schema, before any .check(...)
A failed built-in check
the check's trailing argument: Schema.isMinLength(3, { message }), or { expected } to keep the Expected ... wording
A nested type mismatch
identifier — the message reads Expected RaiseForm instead of a structural dump
Missing key
Schema.annotateKey({ messageMissingKey }) on the field
Unexpected key (under onExcessProperty: "error")
messageUnexpectedKey on the struct
Self-contained source · Type-checked
ts
import { Result, Schema, SchemaIssue } from "effect"const RaiseForm = Schema.Struct({ employeeId: Schema.String.annotate({ message: "employee id must be text" }) .check(Schema.isMinLength(3, { message: "employee id is too short" })) .pipe(Schema.annotateKey({ messageMissingKey: "employee id is required" })), percent: Schema.Finite.annotate({ identifier: "RaisePercent" }), level: Schema.Int.check( Schema.isBetween({ minimum: 1, maximum: 10 }, { expected: "a level from 1 to 10" }) )}).annotate({ identifier: "RaiseForm", messageUnexpectedKey: "unknown field" })const result = Schema.decodeUnknownResult(RaiseForm)( { percent: "x", level: 99, extra: 1 }, { errors: "all", onExcessProperty: "error" })if (Result.isFailure(result)) { console.log(SchemaIssue.makeFormatterStandardSchemaV1()(result.failure.issue).issues) // [ { path: ["extra"], message: "unknown field" }, // { path: ["employeeId"], message: "employee id is required" }, // { path: ["percent"], message: "Expected RaisePercent" }, // { path: ["level"], message: "Expected a level from 1 to 10" } ]}
.annotate(...) after .check(...) targets the last check.Schema.String.check(Schema.isMinLength(3)).annotate({ message }) customizes the length failure and leaves the type mismatch as Expected string.
A transformation has three message sites: the source schema, the getter's own issue, and the target schema.
Schema-side text or presentation-side text — pick one owner. Annotations suit messages that belong to the contract (or i18n keys); formatter hooks suit wording that belongs to one UI.
A getter may do asynchronous work or yield* a service. The service then appears in the schema's DecodingServices (or EncodingServices) and flows into the R of decodeUnknownEffect, where a layer satisfies it. An effectful schema needs an Effect runner (section 1 of Schema).
Fragment · Type-checked
ts
import { Context, Effect, Schema, SchemaGetter, SchemaIssue } from "effect"import type { Layer } from "effect"class EmployeeDirectory extends Context.Service<EmployeeDirectory, { readonly exists: (id: string) => Effect.Effect<boolean>}>()("app/EmployeeDirectory") {}const KnownEmployeeId = Schema.NonEmptyString.pipe( Schema.decode({ decode: SchemaGetter.transformEffect((id: string, options) => Effect.gen(function*() { const directory = yield* EmployeeDirectory if (yield* directory.exists(id)) return id return yield* Effect.fail( new SchemaIssue.InvalidValue({ message: "unknown employee" }, id, options) ) }) ), encode: SchemaGetter.passthrough() }))// typeof KnownEmployeeId.DecodingServices is EmployeeDirectoryconst RaiseBatch = Schema.Array( Schema.Struct({ employeeId: KnownEmployeeId, percent: Schema.Finite }))declare const DirectoryLive: Layer.Layer<EmployeeDirectory>// Eight lookups at a time; the requirement is discharged where the program is assembled.const decodeBatch = (input: unknown) => Schema.decodeUnknownEffect(RaiseBatch)(input, { concurrency: 8, errors: "all" }).pipe( Effect.provide(DirectoryLive) )
Need
Use
Convert with a service or async step
SchemaGetter.transformEffect((value, options) => Effect) — fail with a SchemaIssue
Keep the requirement visible. A lookup hidden inside a synchronous predicate cannot be provided, mocked, traced, or interrupted; a getter that names its service can. And keep the two questions apart: a schema answers "does this input have the required shape and local constraints, given reference data?"; whether the operation may happen now (budget left, cycle open) is domain policy that belongs in a service, with its own tagged error.
Reach for it when you need to validate, parse, serialize, or describe data crossing any boundary.
The modules behind Schema: the AST every schema compiles to, the parser and its ahead-of-time and JIT compilers, getters and transformations as plain data, schema representations, the issue tree and SchemaError, JSON Schema and Standard Schema adapters, JSON Patch and Pointer, data models, and TestSchema. Most applications use these indirectly; read a section when you generate artifacts from schemas, write tooling, or need to understand a failure at the issue level.
The introspectable tree behind every schema. Each Schema has an .ast: a discriminated-union node (String, Number, Literal, Objects, Arrays, Union, Suspend, Declaration, …) carrying checks, annotations, encoding links, and parse context. This layer makes derivation possible — JSON Schema, arbitraries, equivalence, and the parser all read the AST.
Mental model. The AST is the compiler's IR for schemas. A transformation is an encoding link on a node; a refinement is a check on a node; toType/toEncoded/flip are tree rewrites. The _tag on every node plus is* guards (isObjects, isUnion, isString, …) support tree walking.
Self-contained source · Type-checked
ts
import { Schema, SchemaAST } from "effect"const Employee = Schema.Struct({ name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 }))})// Every schema exposes its AST node.const ast = Employee.astconsole.log(ast._tag) // "Objects"// Walk it: list the field keys and the tag of each field's AST.if (SchemaAST.isObjects(ast)) { for (const ps of ast.propertySignatures) { console.log(ps.name, ps.type._tag) // "name" "String", "level" "Number" }}// Resolve annotations off any node without touching the Schema wrapper.const title = SchemaAST.resolveTitle(Schema.String.annotate({ title: "Name" }).ast)
Note: Handy AST utilities: SchemaAST.getAST(schema) (the node), toType/toEncoded/flip (memoized tree rewrites that power the Schema-level functions of the same name), annotate/appendChecks/replaceEncoding (build derived nodes), and resolveTitle/resolveDescription/resolveIdentifier (read annotations). The node classes — Objects, Arrays, Union, Literal, Declaration — are exported if you need to construct one. The SchemaAST and SchemaIssue nodes and the SchemaTransformation models are published as structural instance interfaces: new and instanceof still work, but a constructor's prototype is not part of the TypeScript API, so name the instance interface (SchemaAST.AST, SchemaTransformation.Transformation<T, E>) in type positions. SchemaGetter.Getter<T, E, R> is a tagged union with no constructor at all (SchemaGetter). SchemaAST.Base does not exist; accept SchemaAST.AST and narrow with the is* guards. SchemaAST.Context.constructorDefault holds the constructor-default Effect directly rather than a SchemaAST.Link; code that builds or reads a Context by hand passes or reads that Effect.
Reach for it when building tooling on top of schemas: custom JSON-Schema dialects, schema-driven UI generation, schema linters, or any code that reasons about a schema's structure rather than just runs it.
The AST-walking interpreter that runs a schema against a value. The decode*/encode*/is/asserts functions on the Schema module are thin re-exports of SchemaParser. SchemaParser.run walks the AST once and returns Effect<A, SchemaIssue.Issue>; every other function is that result re-clothed in a different type.
Mental model. One traversal, many output skins. Reaching into SchemaParser directly is what custom declare codecs do to decode their type parameters.
Self-contained source · Type-checked
ts
import { Effect, Schema, SchemaIssue, SchemaParser } from "effect"// The HRIS wraps paginated results in an envelope: { data: T }.interface Page<A> { readonly data: A }const isPage = (u: unknown): u is Page<unknown> => typeof u === "object" && u !== null && "data" in u// A custom container codec: use SchemaParser to decode the inner schema.const Page = <A extends Schema.Top>(item: A) => Schema.declareConstructor<Page<A["Type"]>, Page<A["Encoded"]>>()( [item], ([itemCodec]) => (u, ast, options) => { if (!isPage(u)) return Effect.fail(new SchemaIssue.InvalidType(ast, u, options)) return Effect.map( SchemaParser.decodeUnknownEffect(itemCodec)(u.data, options), (data) => ({ data }) ) } )const EmployeePage = Page(Schema.Struct({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String}))
Schema.is(schema) (type predicate) and Schema.asserts(schema, input) (TypeScript assertion) both originate here.
Self-contained source · Type-checked
ts
import { Schema } from "effect"const Rating = Schema.Literals(["exceeds", "meets", "below"])const isRating = Schema.is(Rating)isRating("exceeds") // true, and narrows to the rating unionconst input: unknown = "meets"Schema.asserts(Rating, input) // throws if not a rating; otherwise narrowsinput.toUpperCase()
Parsers look up each exact AST in a shared decoder registry. By default that entry is the interpreter; SchemaJITCompiler and SchemaAOTCompiler can install compiled entries whose optional synchronous decode, is, and make fast paths the parser tries first, falling back to the detailed decoder to build the issue when a fast path rejects the input. The SchemaParser API and its results stay the same either way.
Reach for it when writing a custom declare codec and needing to decode/encode inner schemas, or building a low-level tool that wants the raw Effect<A, Issue> traversal. Day to day, call through Schema.
The shared registry that maps an exact SchemaAST.AST to a CompiledDecoder: a required decodeEffect (complete decoding with detailed issues) plus optional is, decode, make, and makeEffect operations. The JIT and AOT compilers are both clients of this registry; SchemaCompiler.set(ast, decoder) is the manual entry point, and SchemaCompiler.invalid / SchemaCompiler.missing are the sentinels a fast path returns for "rejected, ask the detailed decoder" and "no value produced".
Mental model. A cache of parser implementations keyed by AST identity, never of parse results. A fast path only has to be right about valid input; everything else is delegated to decodeEffect, which produces the issue.
Self-contained source · Type-checked
ts
import { Effect, Schema, SchemaIssue } from "effect"import { SchemaCompiler } from "effect/schema"const EmployeeId = Schema.String.check(Schema.isPattern(/^E\d{6}$/))// A hand-written fast path for a hot identifier check. The decoder is trusted to// implement the AST's semantics exactly; decodeEffect supplies the detailed issue.SchemaCompiler.set(EmployeeId.ast, { decode: (input) => typeof input === "string" && /^E\d{6}$/.test(input) ? input : SchemaCompiler.invalid, decodeEffect: (input) => typeof input === "string" && /^E\d{6}$/.test(input) ? Effect.succeed(input) : Effect.fail(new SchemaIssue.InvalidValue({ message: "expected an employee id" }, input))})
set replaces an earlier entry for the same AST, but parser functions that have already resolved an entry keep it. Type-side (SchemaAST.toType) and flipped (SchemaAST.flip, used for encoding) ASTs are separate keys.
Reach for it when you are writing a compiler or an integration that supplies decoders for specific ASTs. Application code normally goes through SchemaJITCompiler or SchemaAOTCompiler instead; a hand-written entry that disagrees with its schema silently changes what decodes.
Generates decoder source for a schema at runtime and installs it through new Function. Two entry points: the side-effect import effect/schema/SchemaJITCompiler/enable compiles every schema lazily on first use, and SchemaJITCompiler.enable(schema.ast) compiles one schema and its parsing dependencies.
Mental model. A drop-in accelerator for the same parser. Operations compile lazily on first use; checks, transformations, and defaults are never executed at installation. Validators, structs, and homogeneous arrays get generated code; most transformations and all middleware still run through the interpreter, with compiled children.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { SchemaJITCompiler } from "effect/schema"const PayrollLine = Schema.Struct({ employeeId: Schema.NonEmptyString, grossCents: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), costCenters: Schema.Array(Schema.String)})// Selective: enable before the first decode of this schema anywhere in the process.SchemaJITCompiler.enable(PayrollLine.ast)const decodeLine = Schema.decodeUnknownSync(PayrollLine) // same API, same issues on failure// Global alternative, as the entrypoint's first import:// import "effect/schema/SchemaJITCompiler/enable"
In practice, a four-field struct decodes about three times faster with JIT enabled and produces identical results and error messages. Where dynamic function construction is blocked (a Content Security Policy without 'unsafe-eval', some edge runtimes), compilation fails silently and parsing stays interpreted: nothing breaks, nothing gets faster. Enable before first use: a parser function that has already run keeps its interpreted entry, while one created but not yet called picks up the compiled entry.
Reach for it when profiling shows schema decoding on a hot path (high-volume ingestion, large payload arrays) in a runtime that allows new Function. Leave it off otherwise; results do not change, only speed.
The build-time twin of the JIT compiler. SchemaAOTCompiler.compile(targets) returns the source of a static JavaScript module whose install(asts) export registers the generated decoders, so no code is constructed at runtime. The companion entrypoint effect/schema/SchemaAOTCompiler/Build exposes build(options), which loads your schema modules, compiles their directSchema exports, and writes a module that installs itself when imported. It needs FileSystem and Path and fails with BuildError or PlatformError.
Mental model. JIT output frozen into a file. Operations are opt-in per build ("decode" by default; add "encode", "is", "make"); anything not generated falls back to the interpreter.
Fragment · Type-checked
ts
import { NodeServices } from "@effect/platform-node"import { Effect } from "effect"import { build } from "effect/schema/SchemaAOTCompiler/Build"// A build script: compile the schemas exported by the payroll module.declare const loadPayrollSchemas: () => Promise<unknown> // () => import("./payroll/schemas.ts")const writeAotModule = build({ modules: { "./payroll/schemas.ts": loadPayrollSchemas }, baseUrl: new URL("../src/", import.meta.url), outFile: "src/generated/schemas.aot.js", operations: ["decode", "encode"]}).pipe( Effect.tap(({ schemas }) => Effect.log(`compiled ${schemas} schemas`)), Effect.provide(NodeServices.layer))// Application entrypoint, before any schema is used:// import "./generated/schemas.aot.js"
The generated module installs and decodes with globalThis.Function blocked. Benchmark the actual workload rather than assuming a performance equivalence with JIT. Regenerate the file whenever a schema definition or the Effect version changes; installation trusts that the ASTs match what was compiled. Bundler configurations that mark modules side-effect free must keep the generated import.
Reach for it when you want compiled decoders where new Function is unavailable (strict CSP, locked-down runtimes) or you want no code generation at startup. It trades a build step and a regenerate-on-change rule for that.
A Getter<T, E, R> is one direction of a conversion: takes an optional encoded value and returns an optional decoded value, possibly failing with an issue or requiring services. Getters are the atoms of the v4 transformation model.
Mental model. A validating, possibly-effectful map for one leg of a codec. Built-in getters: transform (pure map), transformEffect (map that can reject or use services), forbiddenEncoding (the encode leg of a decode-only conversion), transformOptional (operate on the Option of presence — key to optional-field migrations), checkEffect (async validation), passthrough/required/omit, and ready-made conversions String(), Number(), trim(), parseJson(), encodeBase64(). When a getter must see a missing value and run an Effect, use transformOptionalEffect((option, parseOptions) => Effect<Option>).
Getters are data, operated on by functions. A Getter is a tagged union (Passthrough, Transform, TransformOptional, TransformEffect, TransformOptionalEffect) whose values expose only pipe. Chain and run them with the dual functions SchemaGetter.map, SchemaGetter.compose, and SchemaGetter.run (there are no getter.map, getter.compose, or getter.run members, no public new SchemaGetter.Getter(...) constructor, and no SchemaGetter.onSome / onNone — use transformEffect for present values and transformOptionalEffect when the missing case matters).
Self-contained source · Type-checked
ts
import { Effect, Option, SchemaGetter } from "effect"// Parse a pasted salary, then clamp negatives to zero: two steps, one getter.const salaryCents = SchemaGetter.transform((text: string) => Number(text.replaceAll(",", ""))).pipe( SchemaGetter.compose(SchemaGetter.transform((cents: number) => Math.max(0, cents))), SchemaGetter.map(Math.round))// Run a getter outside a schema (tests, tooling). The result is always an Effect of an Option.const decoded = SchemaGetter.run(salaryCents, Option.some("12,500"), {})const value = Effect.runSync(decoded) // Option.some(12500)
Self-contained source · Type-checked
ts
import { Option, Schema, SchemaGetter } from "effect"// transformOptional is how v4 expresses optionalToRequired/requiredToOptional.// Here: a missing managerId decodes to null (a top-level exec), and null encodes// back to "missing".const orgEntry = Schema.Struct({ managerId: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))).pipe( Schema.decodeTo(Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), { decode: SchemaGetter.transformOptional(Option.orElseSome(() => null)), encode: SchemaGetter.transformOptional(Option.filter((value) => value !== null)) }) )})// Ready-made getters keep transformations terse. Normalize a pasted employee name.const TrimmedName = Schema.String.pipe( Schema.decode({ decode: SchemaGetter.trim(), encode: SchemaGetter.passthrough() }))
Effectful filters. Ordinary checks are synchronous and service-free. For "is this code still free?" validation, use a same-type transformation whose decode leg is SchemaGetter.checkEffect(f). The contract: f(value, options) returns an Effect that succeeds with undefined / true to pass, or with a message string or filter issue to fail — its error channel is never, and services it uses are tracked in the schema's DecodingServices. Being effectful, it needs an Effect runner.
Reach for it when defining a transformation and needing the decode or encode leg — especially for optional-field gymnastics (transformOptional), async checks (checkEffect), or built-in string/binary/JSON conversions.
A Transformation<T, E> bundles both directions of a conversion — decode (E → T) and encode (T → E) — into one reusable value. Passed as the second argument to decodeTo when a clean two-way mapping exists.
Mental model. A named codec-fragment. Prebuilts: transform/transformEffect constructors plus trim, toLowerCase, capitalize, numberFromString, dateFromString, optionFromNullOr, fromJsonString, uint8ArrayFromBase64String. These are how Schema.Trim, Schema.DateFromString, etc. are defined internally. At the public schema level use Schema.fromJsonString(inner, { reviver?, replacer?, space? }); the old Schema.UnknownFromJsonString constant is internal.
Self-contained source · Type-checked
ts
import { Schema, SchemaTransformation } from "effect"// Build your own two-way transformation in one shot. The HRIS stores an// employee's eligible departments as a comma-separated string.const csv = (separator: string) => Schema.String.pipe( Schema.decodeTo( Schema.Array(Schema.String), SchemaTransformation.transform({ decode: (s) => s.split(separator) as ReadonlyArray<string>, encode: (as) => as.join(separator) }) ) )const DepartmentIds = csv(",")Schema.decodeUnknownSync(DepartmentIds)("eng,design,ops") // ["eng", "design", "ops"]Schema.encodeUnknownSync(DepartmentIds)(["eng", "ops"]) // "eng,ops"// Or compose a prebuilt one (this is roughly how Schema.Capitalize is built).const TitleCased = Schema.String.pipe( Schema.decodeTo(Schema.String.check(Schema.isCapitalized()), SchemaTransformation.capitalize()))
Ready-made codecs, so you do not rebuild them: text — Schema.Trim, StringFromBase64, StringFromBase64Url, StringFromHex, StringFromUriComponent; numbers — FiniteFromString, NumberFromString, BigIntFromString, BigDecimalFromString; bytes — Uint8ArrayFromBase64, Uint8ArrayFromHex; time and web — DateFromString, DateFromMillis, DateTimeUtcFromString, DateTimeUtcFromMillis, URLFromString. Case codecs are assembled the way TitleCased is above: a checked target (Schema.isLowercased(), ...) plus SchemaTransformation.toLowerCase(), toUpperCase(), capitalize(), or uncapitalize(); snakeToCamel() serves key and identifier conversion.
Composing and wrapping. Chain two transformations with the dual SchemaTransformation.composeTransformation(first, second) or first.pipe(SchemaTransformation.composeTransformation(second)): decoding runs first then second, encoding runs them in reverse. There is no first.compose(second) method. Pair two existing getters with SchemaTransformation.makeTransformation({ decode, encode }). Transformation and Middleware values are Pipeable.
Self-contained source · Type-checked
ts
import { Schema, SchemaTransformation } from "effect"// Normalize a pasted work email: trim, then lowercase, as one reusable two-way step.const normalizeEmail = SchemaTransformation.trim().pipe( SchemaTransformation.composeTransformation(SchemaTransformation.toLowerCase()))const WorkEmail = Schema.String.pipe(Schema.decode(normalizeEmail))const email = Schema.decodeUnknownSync(WorkEmail)(" Ada.Lovelace@Example.COM ") // "ada.lovelace@example.com"
Reach for it when a transformation has a clean, symmetric decode/encode pair and you want it as a single reusable value, or when a library prebuilt covers the case.
A compiler and persistence pipeline for schema structure. A live Document holds a representation root plus shared references; unlike persisted JSON, it may still contain runtime compiler callbacks and non-JSON annotation values. toJson is the explicit storage/transport boundary.
Mental model. Lower a schema with Schema.toRepresentation(schema) (or its AST with SchemaRepresentation.toRepresentation(ast)), then choose a branch: persist with toJson; compile to JSON Schema with toJsonSchemaDocument; or wrap with toMultiDocument and generate TypeScript via toCodeDocument. Multiple roots use toRepresentations, sharing one reference environment.
Self-contained source · Type-checked
ts
import { Schema, SchemaRepresentation } from "effect"const CompBand = Schema.Struct({ level: Schema.Int, salaryMid: Schema.Int })// The live representation is the compiler input.const document = Schema.toRepresentation(CompBand)// Persistence is explicit. Non-JSON annotations are omitted.const persisted = SchemaRepresentation.toJson(document)const restoredDocument = SchemaRepresentation.fromJson(persisted)// Generate TypeScript source — e.g. typed comp models for a partner team.const multi = SchemaRepresentation.toMultiDocument(document)const codeDoc = SchemaRepresentation.toCodeDocument(multi)const firstCode = codeDoc.codes[0]if (firstCode) { console.log(firstCode.runtime) // the Schema.Struct({ ... }) expression as a string console.log(firstCode.Type) // the corresponding TypeScript type as a string}
fromRepresentation(document, { revivers }) reconstructs a runtime schema; no declaration/check revivers are installed implicitly — schemas such as Schema.SemVer, Schema.SemVerRange, Schema.Rational, and the Schema.isAscii check need their revivers (SemVerReviver, SemVerRangeReviver, RationalReviver, isAsciiReviver) passed explicitly, and a missing one fails with Missing reviver for <id>. toCodeDocument omits an annotation whose value cannot be written as a source literal rather than emitting a wrong object literal, so generated code may carry fewer annotations than the live schema. The multi-root twin is fromRepresentations. Persisted documents using an older representation format are not wire-compatible; regenerate them or perform an explicit migration before loading them with the current pipeline. That includes older documents containing a oneOf union, whose mode now lives at { options: { mode: "oneOf" } } (SchemaAST.Union.options?.mode, not a top-level field); the public Schema.Union(members, { mode }) call is unaffected. Importing external JSON Schema patterns also requires an explicit trust choice: the default is to reject them, { patterns: "apply" } evaluates patterns from a trusted document, and { patterns: "ignore" } knowingly weakens validation.
Reach for it when you need code generation, JSON Schema compilation/import, or a deliberately persisted schema representation with shared references.
The structured error tree produced when parsing fails. Leaf nodes: InvalidType, InvalidValue, MissingKey, UnexpectedKey, Forbidden, OneOf. Composite nodes: Composite, Filter, Pointer, Encoding, AnyOf. SchemaError (thrown/failed by runners) carries this tree in its .issue field.
Mental model. Parsing produces a tree of failures mirroring the data's shape. An issue does not format itself through String(issue); formatting is explicit. SchemaIssue.makeFormatterDefault() returns a readable string, while makeFormatterStandardSchemaV1() returns { issues: [{ path, message }, ...] }. Rejected inputs are omitted by default and are only attached when parsing with { reportInput: true }; use SchemaIssue.hasInput before reading one.
Self-contained source · Type-checked
ts
import { Effect, Result, Schema, SchemaIssue } from "effect"// A raw HRIS record we expect to decode into an Employee.const Employee = Schema.Struct({ name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 }))})const program = Schema.decodeUnknownEffect(Employee)({}, { reportInput: true, errors: "all" }).pipe( Effect.catchTag("SchemaError", (error) => { // error.issue is the structured tree; format it to { path, message }[]. const issues = SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues console.error(issues) // [ { path: ["name"], message: "Missing key" }, // { path: ["level"], message: "Missing key" } ] return Effect.void }))// Human-readable formatting is explicit; String(issue) is not the formatter.const result = Schema.decodeUnknownResult(Employee)({ name: 1, level: "senior" })if (Result.isFailure(result)) { console.log(SchemaIssue.makeFormatterDefault()(result.failure.issue))}
Customize wording with formatter hooks.makeFormatterStandardSchemaV1 accepts a leafHook (terminal issues: MissingKey, InvalidType, UnexpectedKey, ...) and a checkHook (failed filters; return undefined to keep the Expected ... fallback). A hook handles the tags it cares about and delegates the rest to SchemaIssue.defaultLeafHook / SchemaIssue.defaultCheckHook, which honor message annotations first. This keeps wording — or translation keys — a presentation concern at the boundary instead of scattering strings through schemas, and Schema.toStandardSchemaV1 accepts the same two hooks. The schema-side alternative is in Custom error messages.
Reach for it when you need to act on a validation failure: render field-level errors, build custom messages for rejected rows, localize messages, or pattern-match issue tags to react differently to distinct failure kinds.
The public error wrapper used by the high-level Schema.decode* and Schema.encode* adapters. Schema.SchemaError is tagged "SchemaError" and carries the raw SchemaIssue.Issue in .issue; its .message applies the default formatter. Schema.isSchemaError safely recognizes it, including across duplicated package copies. It lives in the Schema namespace; there is no standalone effect/SchemaError module.
JSON serialization and Node inspection expose only { _tag: "SchemaError", message }, not the issue's schema AST. Access .issue explicitly for programmatic diagnostics; do not depend on JSON.stringify(error) to preserve the issue tree. The formatted message can still contain input data, so compact serialization is not secret redaction.
Schema.makeEffect is another deliberate low-level exception: it fails with a raw SchemaIssue.Issue, not the wrapper. High-level sync/Promise runners throw or reject SchemaError; parser sync/Promise adapters throw a plain Error whose cause is the raw issue.
Existing classes: Use Schema.instanceOf(Constructor) when the boundary already contains instances. It checks identity only (and needs a public constructor; fall back to Schema.declare with an instanceof guard otherwise) — to validate the instance's fields too, add a Schema.makeFilter that runs a struct decoder such as Schema.decodeUnknownResult(Fields) over the instance and returns the failure's .issue. For a struct-on-the-wire codec, explicitly combine the struct, Schema.decodeTo, and a SchemaTransformation.transform that constructs and projects the class; or define the model with Schema.Class when you own it.
Reach for it when you need to detect, transport, or explicitly format high-level schema failures. Reach for raw SchemaIssue.Issue via SchemaParser when implementing codecs or issue-tree tooling.
Derive a JSON Schema document from any Schema and normalize/convert between JSON Schema dialects (Draft-07, Draft 2020-12, OpenAPI 3.0/3.1). Schema.toJsonSchemaDocument produces the document; this module handles dialect plumbing ($ref resolution, OpenAPI component keys, cross-dialect conversion). Annotations (description, title, custom keys via includeAnnotationKey) flow into output.
Self-contained source · Type-checked
ts
import { Schema } from "effect"// The request body for "set a salary band" on the compensation API.const CompBand = Schema.Struct({ level: Schema.Int.annotate({ description: "Job level, e.g. 5 for IC5" }), salaryMid: Schema.Int})const doc = Schema.toJsonSchemaDocument(CompBand)console.log(JSON.stringify(doc.schema, null, 2))// {// "type": "object",// "properties": {// "level": {// "type": "integer",// "minimum": -9007199254740991,// "maximum": 9007199254740991,// "description": "Job level, e.g. 5 for IC5"// },// "salaryMid": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }// },// "required": ["level", "salaryMid"],// "additionalProperties": true// }// Publish a closed contract instead: unknown properties are rejected by validators.const closed = Schema.toJsonSchemaDocument(CompBand, { onExcessProperty: "error" })// closed.schema.additionalProperties === false
Two things to know about documents you generate yourself with Schema.toJsonSchemaDocument. (OpenAPI documents derived by HttpApi are a separate path: OpenApi.fromApi emits closed objects, "additionalProperties": false — see HTTP API.)
Objects are open by default. Generation now mirrors Effect decoding, which ignores excess properties unless told otherwise, so a Struct emits "additionalProperties": true. The old { additionalProperties } generation option is gone: use { onExcessProperty: "ignore" } (the default) or { onExcessProperty: "error" } for a closed object, and model a schema-valued "rest" with Schema.Record or Schema.StructWithRest rather than an option. If a consumer relied on the previous closed default — a strict validator, a generated client, a structured-output provider — opt back in explicitly.
Check constraints and annotations are compacted into the node when possible ("type": "integer", "description": …) instead of being wrapped in allOf. Colliding numeric, length, item-count, and property-count bounds are tightened in place; redundant inclusive/exclusive bounds on the same side are removed. Other incompatible keyword collisions can still require allOf. Schema.Int / isInt emit exact JSON Schema integers with safe-integer bounds; composing a stricter bound keeps the tighter constraint, and exact integer union branches preserve oneOf. Snapshot tests of generated documents need refreshing.
On the import side (SchemaRepresentation.fromJsonSchemaDocument), unsupported references, validation keywords, and object-valued const/enum are now rejected with a path-qualified explanation instead of being silently weakened. $ref pointers may target locations below a top-level definition (#/$defs/Note/properties/title), including shared and recursive schemas; circular pointer aliases are rejected. includeAnnotationKey on fromJsonSchemaDocument / fromJsonSchemaMultiDocument keeps selected custom keywords (such as x-* extensions) as schema annotations. A contentSchema keyword that contains a $ref is not kept as an annotation, so generated schema code never carries a dangling reference. Intersections (allOf) of overlapping unions are supported when the alternatives are separated by root type or by a required literal property (including through references); incompatible alternatives are pruned first, and other intersections that would duplicate nested choices are still rejected.
Imported objects stay open. A JSON Schema object without additionalProperties imports as an open struct, so the imported decoder keeps excess keys the original Effect decoder would strip. The experimental { closeObjects: true } import option closes objects that declare properties when no contributing object sets additionalProperties; it runs after allOf composition, so inherited fields stay valid, and it leaves explicit additionalProperties constraints and free-form objects alone. A closed object then strips excess keys by default, or rejects them under onExcessProperty: "error".
What the document describes. Four rules explain most surprising output:
It describes the Encoded side. Generation goes through the canonical JSON codec, so a FiniteFromString field is { "type": "string" } and a Schema.Option(...) is a union of tagged objects — never the in-memory Type. For the same reason .annotate(...) on a transformation documents the decoded side, which JSON Schema never sees; use Schema.annotateEncoded({ description }) to reach the document. A Schema.fromJsonString(inner) field becomes { "type": "string", "contentMediaType": "application/json" }. Because the document describes the JSON codec, a payload it accepts can still fail the plain decoder: Schema.Number allows the strings "Infinity", "-Infinity", and "NaN", and Schema.optional(S) allows null, which only Schema.toCodecJson(schema) decodes. Validate such payloads with that codec, or use Schema.Finite and Schema.optionalKey when the published contract should be the narrower one.
identifier creates $ref definitions. The result is { dialect, schema, definitions }. A schema carrying an identifier annotation (a class identifier counts) is hoisted into definitions and referenced as { "$ref": "#/$defs/<identifier>" }. A recursive schema is always emitted through a definition; without an identifier the generator invents the name, so give it one. This is what controls reusable component names in OpenAPI documents and structured-output schemas.
Checks become keywords only when they know how. Built-in checks map to minLength, pattern, numeric bounds, uniqueItems, and so on. A custom Schema.makeFilter contributes nothing unless it carries a toJsonSchema annotation (section 5 of Schema); { generateDescriptions: true } turns each check's expected text into a description.
optionalKey and optional differ on the wire.optionalKey only removes the property from required; optional also widens the property to allow null, because JSON cannot carry undefined.
Self-contained source · Type-checked
ts
import { JsonSchema, Schema } from "effect"interface OrgNode { readonly name: string readonly reports: ReadonlyArray<OrgNode>}const OrgNode: Schema.Codec<OrgNode> = Schema.Struct({ name: Schema.String, reports: Schema.Array(Schema.suspend((): Schema.Codec<OrgNode> => OrgNode))}).annotate({ identifier: "OrgNode" }) // a stable $defs name for the cycleconst orgDoc = Schema.toJsonSchemaDocument(OrgNode)// orgDoc.schema -> { "$ref": "#/$defs/OrgNode" }// orgDoc.definitions -> { OrgNode: { "type": "object", ... "items": { "$ref": "#/$defs/OrgNode" } } }// Generation always targets Draft 2020-12; other dialects are pure conversions.const draft07 = JsonSchema.toDocumentDraft07(orgDoc) // also toDocumentDraft04, toMultiDocumentOpenApi3_1
Which model owns which artifact. A value schema knows a shape. It does not know methods, paths, parameter locations, status codes, per-endpoint errors, security, or media types; those facts live on the assembled HttpApi. So derive JSON Schema from Schema for value contracts, and derive the OpenAPI document from the API with OpenApi.fromApi. Point a generator at the wrong model and its output silently lacks everything that only the other model records.
Official guide: Schema to JSON Schema (it documents an additionalProperties generation option and closed-by-default output; use onExcessProperty, with open output by default).
Reach for it when you need a machine-readable value contract for external consumers: JSON Schema config validation, cross-language codegen of a payload, or structured-output LLM prompting. For an HTTP API description, generate OpenAPI from HttpApi instead.
The type definitions of the Standard Schema V1 specification — StandardSchemaV1, StandardTypedV1, and the experimental StandardJSONSchemaV1 — vendored verbatim so effect no longer depends on @standard-schema/spec. The module is types only; the conversion lives on Schema.
Schema.toStandardSchemaV1(schema, { leafHook?, checkHook?, parseOptions? }) returns a value that is both the original schema and a Standard Schema, so libraries that accept Standard Schema (form libraries, routers, tRPC-style tooling) can validate with an Effect schema. Validation runs the schema's decoder: the result is { value } or { issues }, where each issue carries a path and a message produced by the hooks. It is synchronous unless the schema needs an asynchronous step, in which case validate returns a Promise — consumers must handle both.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import type { StandardSchema } from "effect"const RaiseRequest = Schema.Struct({ employeeId: Schema.NonEmptyString, raisePercent: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 0.15 }))})// One value: still an Effect Schema, and also a Standard Schema V1.const standard = Schema.toStandardSchemaV1(RaiseRequest)// A library-facing signature can name the vendored type directly.const validateWith = <I, O>(schema: StandardSchema.StandardSchemaV1<I, O>, input: unknown) => schema["~standard"].validate(input)const result = validateWith(standard, { employeeId: "", raisePercent: 0.4 })if (!(result instanceof Promise) && result.issues) { result.issues.map((issue) => issue.path) // [["employeeId"], ["raisePercent"]]}
Only decoding is exposed — Standard Schema has no encode direction — and a schema that requires decoding services cannot be converted. Schema.toStandardJSONSchemaV1 targets a still-experimental extension of the spec; treat it as unstable. Its draft-07 and draft-2020-12 outputs carry the root $schema. Both converters return fresh copies, so hooks and parse options from one call never leak into another.
Integration facts: the vendor string is "effect"; the adapter collects all issues by default (pass { parseOptions: { errors: "first" } } to change that); leafHook / checkHook are the same hooks SchemaIssue formatters take; and a defect raised while decoding is not thrown but reported as one issue without a path, whose message is the rendered cause — stack trace included — so never show a path-less issue to an end user verbatim.
Compute and apply deterministic diffs over JSON values. A JsonPatch is an ordered list of add/remove/replace operations addressed by JSON Pointer paths (deterministic subset of RFC 6902). get(oldValue, newValue) produces the patch; apply(patch, value) replays it without mutating the input. apply throws on a malformed JSON Pointer escape (/a~2, or a trailing ~) rather than treating it as a literal key. For line- or character-level diffs of text, see TextDiff.
Self-contained source · Type-checked
ts
import { JsonPatch } from "effect"// A merit-cycle review: the plan before and after a manager's edits.const before = { recommendations: [{ employeeId: 1, newSalary: 185000 }], approved: false }const after = { recommendations: [{ employeeId: 1, newSalary: 192400 }, { employeeId: 2, newSalary: 150000 }], approved: true}const patch = JsonPatch.get(before, after)// [ { op: "replace", path: "/approved", value: true },// { op: "replace", path: "/recommendations/0/newSalary", value: 192400 },// { op: "add", path: "/recommendations/1", value: { employeeId: 2, newSalary: 150000 } } ]JsonPatch.apply(patch, before) // deep-equals `after`
Tip: For schema-typed values, Schema.toDifferJsonPatch(schema) gives you a Differ that diffs decoded values straight into a JsonPatch — handy for optimistic edits and audit logs where you want diffs of domain types, not raw JSON.
Reach for it when syncing state across a wire and wanting minimal diffs, or when needing an auditable record of exactly how structured data changed.
The RFC 6901 conversions underlying JsonPatch paths and JSON Schema $refs. escapeToken encodes ~→~0 and /→~1; unescapeToken reverses it. formatUriFragment(path) and parseUriFragment(fragment) convert a whole token path to and from the #/... URI-fragment form, adding percent-encoding; parsing returns undefined for a malformed fragment.
Self-contained source · Type-checked
ts
import { JsonPointer } from "effect"// A comp-band key like "eng/backend" needs escaping to live in a pointer path.JsonPointer.escapeToken("eng/backend~ic5") // "eng~1backend~0ic5"JsonPointer.unescapeToken("eng~1backend~0ic5") // "eng/backend~ic5"// Whole-pointer URI fragments, as used by "$ref".JsonPointer.formatUriFragment(["$defs", "eng/backend"]) // "#/$defs/eng~1backend"JsonPointer.parseUriFragment("#/$defs/eng~1backend") // ["$defs", "eng/backend"]JsonPointer.parseUriFragment("#/%") // undefined: not a valid fragment
Reach for it when building or parsing JSON Pointer paths by hand, particularly for keys containing slashes or tildes.
Define a domain model once and derive operation-specific variants: select, insert, update (database-facing) and json, jsonCreate, jsonUpdate (API-facing). Field declaration helpers encode per-variant behavior: Model.GeneratedByDb (omit on insert, present on select), Model.DateTimeInsertFromDate (set on insert), Model.DateTimeUpdateFromDate (set on update), Model.Sensitive (hidden from JSON), Model.FieldOption (nullable column ↔ Option).
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Model } from "effect/schema"export const EmployeeId = Schema.Int.check(Schema.isGreaterThan(0)).pipe(Schema.brand("EmployeeId"))// Every Model helper below is part of the unstable `effect/schema/Model` module.export class Employee extends Model.Class<Employee>("Employee")({ id: Model.GeneratedByDb(EmployeeId), // omitted on insert, present on select name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), baseSalary: Model.Sensitive(Schema.BigDecimal), // hidden from the JSON API createdAt: Model.DateTimeInsertFromDate, // set when inserting updatedAt: Model.DateTimeUpdateFromDate // defaults on insert and update}) {}Employee // select schema (the default variant)Employee.insert // insert schema — no `id`; both timestamps have constructor defaultsEmployee.update // update schemaEmployee.json // outward JSON API shape — no baseSalaryEmployee.jsonCreateEmployee.jsonUpdate// Any variant can be promoted to a real class with derived getters.class EmployeeJson extends Schema.Class<EmployeeJson>("EmployeeJson")(Employee.json) { get displayName() { return `${this.name} (L${this.level})` }}
Reach for it when persisted shape, write shape, and public API shape diverge — almost any real domain entity. Natural companion to the SQL modules: Employee.insert is exactly the schema an insert query wants.
The general "one definition, many variants" mechanism that Model is built on. VariantSchema.make({ variants, defaultVariant }) produces a toolkit — Struct, Class, Union, Field, FieldOnly, FieldExcept, fieldEvolve, extract — specialized to your variant names. Model is VariantSchema.make({ variants: ["select","insert","update","json","jsonCreate","jsonUpdate"], defaultVariant: "select" }).
Mental model. Fix a set of views over the same data, then declare each field's behavior per view: shared by all variants (plain schema), restricted to some (FieldOnly(["read"])), excluded from some (FieldExcept(["public"])), or given a different schema per variant (Field({ read: ..., write: ... })). The toolkit derives a real Schema for every variant.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { VariantSchema } from "effect/schema"// Define your own variant axis — what an employee sees vs. what an HRBP sees.const { Class, Field, FieldExcept } = VariantSchema.make({ variants: ["employee", "hrbp"], defaultVariant: "employee"})class CompProfile extends Class<CompProfile>("CompProfile")({ employeeId: Schema.Int.check(Schema.isGreaterThan(0)), baseSalary: Schema.BigDecimal, // present everywhere, but only HRBPs see the performance rating: rating: FieldExcept(["employee"])(Schema.String), // different schema per variant (e.g. employees see a masked band label): bandLabel: Field({ employee: Schema.String, hrbp: Schema.String })}) {}CompProfile // the "employee" variant (default)CompProfile.hrbp // the "hrbp" variant, including rating
Reach for it when you need Model's "derive many shapes from one" power with a different set of variants than the built-in DB/JSON ones.
Assertion helpers for testing schemas. new TestSchema.Asserts(schema) groups checks: decoding succeeds/fails as expected, encoding round-trips, make behaves, and the derived arbitrary generates valid values. Decoding and Encoding are also exported standalone.
Mental model. A schema has three behaviors — decode, encode, construct — plus a derived generator. arbitrary().verifyGeneration() property-tests that everything the schema's native Arbitrary produces actually satisfies Schema.is, catching impossible constraints and broken transformations.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { TestSchema } from "effect/testing"// An equity grant whose vesting math we want to trust for any generated value.const EquityGrant = Schema.Struct({ shares: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_000_000 })), vestingMonths: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 48 }))})// TestSchema is unstable end to end — every member used below is too.const asserts = new TestSchema.Asserts(EquityGrant)// Decoding: succeed (optionally asserting the transformed output) and fail-with-message.await asserts.decoding().succeed({ shares: 4000, vestingMonths: 48 })// Transformations: assert the decoded value differs from the input.await new TestSchema.Asserts(Schema.FiniteFromString).decoding().succeed("4000", 4000)await new TestSchema.Asserts(Schema.FiniteFromString).encoding().succeed(4000, "4000")// Sample the derived arbitrary and assert that generated grants satisfy the schema.// This is a useful property-based check, not a mathematical proof.asserts.arbitrary().verifyGeneration()
A requirement is done when both its accepted and its rejected case have a test. Pair every schema rule with the test that proves it:
Schema requirement
Proof
Required field
the same input without the key fails
Finite set of literals or tags
an unknown literal fails
Optional key
omitted input decodes, and a bad present value fails
Check (range, pattern, cross-field)
an invalid value fails; valid values pass through unchanged
Decoding default
omitted decodes to the default; an explicit falsy value is kept; an explicit invalid value fails
Transformation
decode output and encode output are each asserted, not only the round trip
Unknown ingress
the failure is a SchemaError in the error channel, not a defect
The minimum set per boundary is four cases: one valid wire object (decoded, then encoded back), one missing required field, one bad value, and one excess property under the policy that boundary chose (section 5 of Schema in Depth).
Two limits of derived generators shape the rest: Arbitrary.schema produces valid decoded Type values, so it can test invariants and round trips but never rejection, key omission, or malformed wire input — keep a handful of named encoded fixtures for those (and one regression fixture per representation bug). And it knows only the schema: a cross-field business rule must be a schema check (constructive where possible) or a residual Arbitrary.filter, which spends the discard budget. The round-trip law worth asserting is described in the Schema deep dive.
Reach for it when writing tests for schemas — especially custom transformations and refinements. verifyGeneration(options?) runs a native Arbitrary.checkEffect property (20 runs by default) that generated values satisfy Schema.is; verifyRoundTrip(options?) (with an Effect-returning verifyRoundTripEffect twin) checks decode∘encode round trips. Both take Arbitrary.CheckOptions ({ seed, runs, maxDiscards, maxShrinks, replay }) directly, bound unsuccessful generation, and report the shrunk input and replay token on failure. decoding().fail(input, message) pins down error messages; decoding().failEffect / encoding().succeedEffect / encoding().failEffect are the lazy-Effect twins of fail / succeed.
Effect ships structured logging, spans, and metrics as first-class runtime citizens. The export layer is separate — use a local collector for development, an OTLP endpoint for production, or skip export in tests.
This page covers instrumentation. Getting signals out of the process — OTLP, Prometheus, DevTools, and the OpenTelemetry SDK bridge — is on Telemetry Export.
Instrumentation is a design decision before it is an API call: every signal costs storage, exposes data, and needs an owner. Start from the question an operator will ask, pick the signal that answers it, and write its contract down before adding code.
What happened to this one payroll run, request, or employee record?
Numeric trends, alert thresholds, or a tamper-proof audit trail
Span (Effect.withSpan, Effect.fn)
Where did this request spend its time, and which step failed?
Fleet totals, readiness, or proof that a write committed
Metric (Metric.*)
How many, how fast, how full — across all requests?
The story of one request
Start with rate, errors, duration, saturation, and one domain outcome (for example approved raises per merit cycle), because those cover most alerts; add a signal only when a dashboard or alert names it.
Write one line per signal before shipping it: the question or alert it serves · a stable, bounded name · type, unit, and expected range · the allow-listed attributes and their series ceiling · how it correlates with other signals · privacy class and retention · volume budget · behavior under pressure (drop, truncate, aggregate) · owner. If no one can name the question a signal answers, it only adds spend and leaks data.
Cardinality: names and attribute sets are bounded
A span name identifies an operation type, never an instance, because backends group and index by name: hris.fetchCompBand, not hris.fetchCompBand E-1042. Employee ids, cycle ids, and normalized routes go in span attributes.
Every distinct combination of metric attribute values is a separate time series that the backend stores, queries, and bills for. Label by bounded vocabularies — outcome, status class, error tag, department, job level — and never by employee, request, session, or message id, raw URL or path, SQL text, error message, or free-form tenant input.
High-cardinality detail belongs in logs and span attributes, which are per-event records rather than aggregated series.
Metric.frequency needs a finite vocabulary too, because its state keeps one count per distinct string it has seen.
Hashing an identifier does not reduce cardinality; it only obscures the value.
Treat label limits, sampling, and an overflow policy (drop, a bounded other bucket, or reject) as exporter-edge policy, and count what was dropped on a separate bounded metric so one noisy workflow cannot silently exhaust the series budget.
Privacy: allow-list fields before they are buffered
Default-deny whole objects: config records, headers, cookies, request and response bodies, SQL and its parameters, connection strings, employee records, prompts and model output. Build each telemetry record from fresh, named fields — never spread an untrusted object and try to redact it afterwards.
Classify every field (public, internal, personal, credential, regulated) and apply drop, redact, truncate, or hash before the value reaches a logger queue or an exporter buffer; after that point it already sits in a production data store.
Sanitize keys as well as values when attribute names derive from input, and bound string length, attribute/event/link counts, and nesting depth.
Redacted protects a value only while it stays wrapped (see Keeping secrets masked in log payloads); once code calls Redacted.value and logs the result, nothing downstream can mask it.
Logs and traces are production data: they need access control, retention, and deletion rules like any other store that holds compensation data.
Telemetry is not readiness, liveness, or an audit log
Concern
Question
Decided by
Liveness
Should the host restart this process?
The process supervisor or probe
Readiness
Can this instance accept the work it promises?
The dependencies that work needs (database, HRIS) — never the collector
Telemetry
What happened over time, and why?
The exporter, best effort
Keep an optional collector out of readiness checks, because a collector outage would otherwise mark every instance unready at once and turn a telemetry problem into an outage. Decide fail-open or fail-closed per signal at startup; fail-open is the usual answer.
Absence of spans or logs is not absence of traffic — sampling, a disabled exporter, or a dropped batch all produce silence.
OTLP export is lossy by design: a batch is retried a few times and then dropped (see OtlpExporter). A regulated audit trail needs a durable, transactional store, not a log level.
Watch the exporter through a second path (a scraped gauge, a local log line) so a failing exporter can still report its own drops and last-success age.
A Logger<Message, Output> receives a log event (message, level, cause, fiber, timestamp, annotations, log spans) and produces output. The runtime calls every installed logger for every event. Multiple loggers run simultaneously; install with Logger.layer([...]).
Mental model.Logger is the sink of Effect's structured logging pipeline. Sources are Effect.log, Effect.logInfo, Effect.logError, etc. Annotations (Effect.annotateLogs) flow through the fiber automatically to every logger on every event. Logger is a service provided via layer — never threaded as an argument.
Severity is not outcome. An Effect.logError call can sit inside an effect that goes on to succeed, and a failing effect may log nothing, so alerts and tests should key "failed" off the Exit or the span status, never off the log level.
defaultLogger — The text logger every program starts with: [time] LEVEL (#fiber) logSpan=12ms: message followed by the annotations, written through the Console service.
tracerLogger — Records each log call as an event on the active span (message as the event name; annotations, effect.fiberId, effect.logLevel, and effect.cause as attributes). It is the second member of the default logger set, which is why logs show up inside traces without any setup.
consolePretty() — Human-readable TTY output with optional color. Development default. Options: colors ("auto" or a boolean — pass false for CI), mode ("auto", "tty", or "browser"), and formatDate. There is no stderr option — route pretty output to console.error instead with Layer.succeed(Logger.LogToStderr, true). To pin one renderer regardless of detection use Logger.consolePrettyTty or Logger.consolePrettyBrowser.
consoleJson / formatJson — One JSON object per line. For log aggregation pipelines (Datadog, Loki, CloudWatch).
consoleLogFmt / formatLogFmt — logfmt (key=value pairs). Compact, grep-friendly, popular in Go/Kubernetes ecosystems; level names are uppercase.
consoleStructured / formatStructured — Plain JS object per event. For in-memory inspection and custom transforms.
batched(logger, { window, flush }) — Collects entries for a time window then calls flush with the batch. Returns Effect<Logger, never, Scope>.
toFile(logger, path, options?) — Pipes a string logger to a file. Requires FileSystem (NodeFileSystem.layer on Node.js). Returns Effect<Logger, PlatformError, Scope | FileSystem>. Options are flag (default "a+", append), mode, and batchWindow (default 1 second). Output is always batched through Logger.batched; the pending batch is written when the logger's scope closes, so a hard crash can lose up to one window of lines. Only opening the file can fail with PlatformError — later write errors are ignored.
Official guide: PlatformLogger (there is no PlatformLogger module — the API is Logger.toFile, and the guide's "written as they arrive" remark does not match it: output is always batched, 1 second by default).
Adds a sink; with a console logger already installed every event now prints twice
Logger.layer([])
Empty
Silences logging, for example in a test Layer
Warning: Console, logfmt, and file output do not carry trace or span ids, so once tracerLogger is dropped nothing ties a log line to its span. OtlpLogger and OtelLogger attach the active traceId/spanId to each exported record, and both merge with the existing set by default (mergeWithExisting: true).
Bound every logger's queue and I/O.Logger.batched collects without an upper size limit for one window, so choose a window that fits the log rate, and keep the flush effect fast and unable to block on a dead aggregator (give it a timeout).
A file logger needs an owner for rotation and disk-full behavior, because toFile ignores write errors once the file is open.
Low-volume milestones: cycle opened, payroll run committed
Warn
Degradation that was recovered: retry succeeded, fallback band used
Error
An operation failed and someone should look; an expected rejection (raise above band) is a domain result, not automatically an error
Fatal
The process is about to end
Keep the event text stable and put the variables in fields — Effect.logInfo("raise approved", { cycleId }), not an interpolated sentence — so events can be grouped, counted, and asserted on.
Attach request or job annotations once at ingress (Effect.annotateLogs around the handler); child effects and forked fibers inherit them.
Log a failure once, where recovery or translation is decided, not at every layer it passes through.
Structured log calls and annotations — merit-cycle run
Self-contained source · Type-checked
ts
import { Effect } from "effect"// Annotate every log line inside a merit-calculation run with structured context.// Effect.annotateLogs injects key/value pairs into every log event emitted by the// wrapped effect. Effect.withLogSpan adds an elapsed-ms field named "merit-run".const runMeritCycle = (cycleId: string, employeeId: string) => Effect.fn("MeritCycle.run")( function*() { yield* Effect.logDebug("loading employee comp band") yield* Effect.logInfo("calculating merit increase", { cycleId, employeeId }) yield* Effect.logWarning("employee near band ceiling", { employeeId, bandMax: 180_000 }) yield* Effect.logError("HRIS lookup failed", { employeeId }) }, // Every log line emitted inside gets these key/value pairs attached. Effect.annotateLogs({ service: "comp-service", reviewCycle: cycleId, employeeId // PII — see the redaction example below }), // Adds a "merit-run=<elapsed_ms>" field to every log line. Effect.withLogSpan("merit-run") )
Nested annotation scopes combine: an inner Effect.annotateLogs extends the enclosing fields (its value wins when a key repeats), and the outer set is restored when the inner effect ends. That is what lets a test assert on fields instead of scraping message text.
Effect.annotateLogs wraps one effect. Effect.annotateLogsScoped is a statement instead: it annotates every later log call until the surrounding Scope closes, which fits Layer construction and handlers that are already scoped. It adds Scope to the requirements.
Log a sensitive value as a Redacted, not as a string, because the built-in loggers render a Redacted as <redacted> wherever it appears — in a message object or in an annotation — while the rest of the structure stays queryable. This is the first line of defense; it needs no custom logger.
Warning: The mask lasts only while the value stays wrapped. Redacted.value(token) inside a log call, a template string, or a span attribute emits the secret, and no logger can undo that. A custom logger also receives the original Redacted object, so it must not unwrap it either.
import { Formatter, Logger, References } from "effect"// Logger.make receives an Options object: { message, logLevel, cause, fiber, date }.// Log messages are commonly arrays, and annotations live in a fiber reference rather// than directly on the Options object.const piiRedactingLogger = Logger.make<unknown, void>((opts) => { const redactText = (value: unknown) => typeof value === "string" ? value.replace(/\b[Ee]mployee[Ii]d["\s:=]+[\w-]+/g, "employeeId=REDACTED") : value const messages = globalThis.Array.isArray(opts.message) ? opts.message : [opts.message] const safeMessage = messages.map((message) => Formatter.format(redactText(message))).join(" ") const annotations = opts.fiber.getRef(References.CurrentLogAnnotations) const safeAnnotations = Object.fromEntries( Object.entries(annotations).map(([key, value]) => [ key, key.toLowerCase() === "employeeid" ? "<redacted>" : redactText(value) ]) ) const suffix = Formatter.format(safeAnnotations) if (opts.logLevel === "Error" || opts.logLevel === "Fatal") { console.error(`[${opts.logLevel}] ${safeMessage} ${suffix}`) } else { console.log(`[${opts.logLevel}] ${safeMessage} ${suffix}`) }})
This example redacts the top-level employeeId annotation and matching strings. Treat a pattern-matching logger as the last line of defense, not the primary control: a regex only catches the shapes someone thought of, and it runs after the value has already been attached. The primary controls are an allow-list of fields at the call site (see Privacy) and Redacted for anything secret.
Reach for it when swapping log format, adding a file sink, shipping logs to a remote aggregator, or adding a redaction backstop on top of Effect's structured log events.
Official guide: Logging (its "Built-in Loggers" subsection headings — stringLogger, jsonLogger, and so on — are names this module does not export; its code samples use the correct Logger.format* / Logger.console* names).
LogLevel is the union "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None", plus helpers LogLevel.Order, isGreaterThan, isEnabled, and ordinal comparison. The runtime compares each event's level against References.MinimumLogLevel before dispatching to any logger.
Mental model. Levels form a linear severity scale. "All" is below every real level (lets everything through). "None" is above every real level (silences everything). Events below the minimum are dropped before any logger sees them.
Fragment · Type-checked with fixture
ts
import { Effect, Layer, References } from "effect"// Silence all Debug/Trace logs during a merit-cycle batch run to reduce noise.const quietMeritRun = runMeritBatch.pipe( Effect.provide(Layer.succeed(References.MinimumLogLevel, "Info")))// Completely disable logging inside a tight payroll-calculation hot path.const silentPayrollCalc = calculateAllRaises.pipe( Effect.provide(Layer.succeed(References.MinimumLogLevel, "None")))// Read the current minimum level from the fiber context.const checkLevel = Effect.gen(function*() { const min = yield* References.MinimumLogLevel yield* Effect.log(`comp-service minimum log level: ${min}`)})
The default minimum is "Info", so Effect.logDebug and Effect.logTrace are dropped until something lowers it. Two shapes cover most needs: a process-wide level read from configuration, and a lower level around a single operation.
Fragment · Type-checked
ts
import { Config, Effect, Layer, References } from "effect"// Process-wide: LOG_LEVEL=Debug node main.ts. Config.LogLevel accepts exactly the LogLevel literals.export const LogLevelLive = Layer.unwrap( Effect.gen(function*() { const level = yield* Config.LogLevel("LOG_LEVEL").pipe(Config.withDefault("Info")) return Layer.succeed(References.MinimumLogLevel, level) }))declare const recalculateBand: (employeeId: string) => Effect.Effect<void>// One operation: Debug logging for a single employee while everything else stays at Info.export const debugOneEmployee = (employeeId: string) => recalculateBand(employeeId).pipe( Effect.provideService(References.MinimumLogLevel, "Debug") )
The override is isolated to the wrapped effect and the fibers it forks. Two concurrent operations with different levels do not affect each other, and the level reverts when the wrapped effect ends — a property a mutable global flag cannot give you, and what makes per-request debug logging practical.
Prefer Effect.provideService over Effect.provide(Layer.succeed(...)) for a single effect; it sets the same reference without building a Layer.
Do not model log level, tracing switches, or similar knobs as a custom service. Services are for capabilities the application provides; a setting with a sensible default is a Reference.
Reach for it when adjusting log verbosity for a specific scope, comparing levels programmatically, or setting a global minimum via config.
A service wrapping the browser/Node.js console object. Every method (Console.log, Console.error, Console.warn, Console.group, Console.time, etc.) returns Effect<void>. The Console reference in context can be swapped for testing.
Mental model. Use Console.* for raw, unstructured side-effect output (debug dumps, CLI feedback). For production structured logging use Effect.log* + a Logger.
Self-contained source · Type-checked
ts
import { Console, Effect } from "effect"// Debug-dump an employee's comp snapshot to the console during local development.const dumpEmployeeComp = (employeeId: string, baseSalary: number, band: { min: number; max: number }) => Effect.gen(function*() { yield* Console.log(`comp snapshot for ${employeeId}`) yield* Effect.scoped(Effect.gen(function*() { yield* Console.group({ label: "band details", collapsed: true }) yield* Console.table([ { field: "baseSalary", value: baseSalary }, { field: "bandMin", value: band.min }, { field: "bandMax", value: band.max } ]) })) if (baseSalary > band.max) { yield* Console.error("salary exceeds band ceiling — review required") } })// In tests: swap Console to suppress output.import { Layer } from "effect"const SilentConsole = Layer.succeed(Console.Console, { log: () => Effect.void, error: () => Effect.void, warn: () => Effect.void, // ...rest of Console interface} as any)
Reach for it when you need testable console output or mix Effect with raw console calls in a CLI tool.
Value-formatting utility. format(input) applies a value's Redactable representation before pretty-printing arbitrary values (handles cycles, BigInt, typed arrays, class instances). formatJson(input) uses JSON semantics with the same redaction precedence, serializes a bigint as a quoted string with its n suffix, and omits circular object properties; other unsupported JSON values retain the normal JSON.stringify behavior. Also provides formatDate, formatPath, formatPropertyKey. Used internally by built-in loggers to render log messages and annotation values. When formatting an Error, format appends its cause — including a defined falsy one such as 0, false, "", or null (Error: band lookup failed (cause: 0)); only a missing or undefined cause is omitted.
Mental model. Rarely called directly. Effect.log("msg", someObject) renders someObject via Formatter.format inside the default logger. Reach for it explicitly when building a custom logger or serializing values in a custom Schema codec.
Reach for it when building a custom logger that needs to render Effect values consistently with the default logger, or for cycle-safe pretty-printing outside a logging context.
Low-level tracing model. A Tracer service creates Span objects when the runtime forks or executes traced operations. Each Span records name, parent, SpanKind, attributes, links, events, start/end time (as bigint nanoseconds), and whether it was sampled. Drive it through higher-level Effect APIs and swap the backend via layer.
Mental model. Every Effect.withSpan("name") creates a child span under the currently active span in fiber context (Tracer.ParentSpan). With no parent it becomes a trace root. The Tracer reference (Context.Reference) determines where spans go — the default in-memory NativeSpan is a no-op exporter; swap in an OTLP or OTel tracer to ship them.
The span tree is not the fiber tree. Forking a fiber does not create a span; only Effect.withSpan, Effect.fn("name"), Layer.withSpan, and instrumented libraries do. A forked child inherits the current parent span, so its spans nest correctly, but spans should mirror the operations an operator cares about (load band → fetch rating → compute raise), not the concurrency structure. Use FiberSet and friends when the question is "which fibers are alive".
With the @effect/opentelemetry tracer, spans without an Effect parent inherit the active OpenTelemetry span. When an Effect span has no Effect parent but the calling code already has an active OTel span (for example, an auto-instrumented HTTP framework), that OTel span becomes the Effect span's parent, so the tree connects across the OTel/Effect boundary without manual bridging. An Effect parent always takes precedence over the active OTel span. The native OtlpTracer does not read the OTel context API; with it, bridge explicitly with Tracer.externalSpan / Effect.withParentSpan.
Core tracing APIs — wrapping a merit-calculation run
Fragment · Type-checked with fixture
ts
import { Effect, Tracer } from "effect"// Wrap a merit calculation in a span so the entire run is visible in traces.const calculateMeritIncrease = (employeeId: string, cycleId: string) => Effect.gen(function*() { yield* Effect.annotateCurrentSpan({ "employee.id": employeeId, "merit.cycleId": cycleId }) // Each sub-step gets its own child span. const band = yield* fetchCompBand(employeeId).pipe( Effect.withSpan("hris.fetchCompBand", { attributes: { "db.table": "comp_bands", "employee.id": employeeId }, kind: "client" }) ) const rating = yield* fetchPerformanceRating(employeeId, cycleId).pipe( Effect.withSpan("review.fetchRating", { kind: "client" }) ) return yield* computeRaise(band, rating) }).pipe( Effect.withSpan("merit.calculateIncrease") )// Mark the nightly payroll export as a trace root so it starts a fresh trace,// not a child of whatever triggered it.const nightlyPayrollExport = runPayrollExport.pipe( Effect.withSpan("payroll.nightlyExport", { root: true }))// Bridge an incoming W3C trace-context header from the HRIS webhook.const bridgedSpan = Tracer.externalSpan({ traceId: webhookHeaders["x-trace-id"], spanId: webhookHeaders["x-span-id"], sampled: true})const handleHrisWebhook = processHrisEvent.pipe( Effect.withSpan("hris.webhook", { parent: bridgedSpan }))
Keep identifiers out of span names."merit.calculateIncrease" stays one operation in every backend view, while the employee and cycle ids above travel as attributes; a name such as `merit.calculate ${employeeId}` would create one operation per employee (see Cardinality). Span attributes are still exported data, so the privacy allow-list applies to them too.
The runtime and the exporters record several things without any code from you, so there is no need to mirror them by hand:
Recorded automatically
Source
Each Effect.log* call inside the span becomes a span event: event name = message, attributes = log annotations + effect.fiberId + effect.logLevel, plus effect.cause when a Cause was logged
The span ends with the wrapped effect's Exit (SpanStatus = Ended with exit) on success, failure, and interruption
Effect.withSpan / Effect.fn
Success → status Unset, never OK; with @effect/opentelemetry, a status you set directly on the OpenTelemetry span is kept
OtlpTracer and @effect/opentelemetry
Failure or defect → status ERROR with the first error's message, plus one exception event per error (type, message, stack trace); a failure with no error to report, such as an empty Cause, leaves the status Unset
OtlpTracer and @effect/opentelemetry
Interruption only → status Unset with attribute effect.fiber.interrupted: true (no error event)
OtlpTracer and @effect/opentelemetry
Unset on success follows the OpenTelemetry convention that OK is an explicit decision by the application, not an instrumentation default. Query "failed spans" as status = ERROR and "healthy spans" as status != ERROR; to mark a span OK on purpose under @effect/opentelemetry, call setStatus on the span from OtelTracer.currentOtelSpan.
Migration: Exported spans from OtlpTracer and OtelTracer used to carry status OK on success. Dashboards, alerts, and tail-sampling rules that match status = OK stop matching; rewrite them as status != ERROR.
A span is frozen once it ends. Later end, attribute, event, and addLinks calls are ignored, so logs and Effect.annotateCurrentSpan from a fiber that outlives its span (one forked with Effect.forkDetach, say) do not modify it, OtlpTracer never exports a span twice, and the DevTools tracer sends nothing more for it. Attach such work to its own span. Interrupting a fiber inside Effect.withSpan or Effect.fn records the interruption once.
A failing child marks every enclosing span as failed too unless something in between recovers, because each span ends with the Exit of the effect it wraps. A span proves that an effect ran and how it exited; it proves neither that a transaction committed nor that cleanup finished.
Span stable operations: a normalized route, a use case, a transaction, a queue publish or consume, an external call.
Parentage expresses causality. For batch and fan-in work use links rather than inventing a parent — RequestResolver.withSpan does exactly this for batched requests.
Fiber context reaches forked fibers, not serialized boundaries. Queues that carry plain data, workers, child processes, message buses, and third-party callbacks do not inherit the parent span: carry a standard trace header explicitly (HttpTraceContext.toHeaders / fromHeaders, see HttpTraceContext) and rebuild the parent with Tracer.externalSpan. Inject trace headers only toward destinations you trust.
Malformed inbound trace context is dropped, never rejected: HttpTraceContext.fromHeaders returns Option.none() for a missing or invalid header — including uppercase hex trace or span ids in traceparent, b3, and X-B3-*, and traceparent flags that are not two lowercase hex digits — and the built-in HTTP server middleware then creates the server span without a remote parent. Apply the same rule in custom adapters — bad trace headers must not fail otherwise valid traffic.
Server spans do not carry query values in failures.HttpServerError messages contain only the request path, and the failure HttpMiddleware.tracer records for a 5xx uses the redacted URL, so exporters that read the message after the response do not see query strings or URL credentials. The full request is still on the error object, so do not log that whole.
Correlate logs through the active trace; keep a separate request or job id only when operators need one that survives sampling.
Expected business rejections, cancellations, defects, and transport failures need not share one error status — decide which of them page someone.
Close a streaming span however the stream stops (it drains, fails, or is interrupted) by wrapping the entire stream effect rather than only the success path.
import { Effect } from "effect"// Effect.fn("label") creates a span named "label" for every invocation.// This is the idiomatic way to add tracing to service methods.const applyMeritIncrease = Effect.fn("CompService.applyMeritIncrease")( function*(employeeId: string, increaseAmount: bigint) { yield* Effect.annotateCurrentSpan({ "employee.id": employeeId, "merit.amount": Number(increaseAmount) }) yield* Effect.sleep("30 millis") // simulated HRIS write })
import { Effect, Tracer } from "effect"// After all approvers sign off on raise recommendations, link their spans.const finalizeApprovalChain = (priorApprovalSpan: Tracer.AnySpan) => Effect.annotateCurrentSpan({ "approval.step": "vp-review" }).pipe( Effect.withSpan("approvalChain.finalize", { links: [{ span: priorApprovalSpan, attributes: { "link.type": "prior-approval" } }] }) )
Reach for it when implementing a custom tracer backend, bridging an external trace context, or tuning sampling. For day-to-day use, Effect.withSpan and Effect.fn suffice.
Official guide: Tracing (annotated span dumps and a one-container local Grafana stack; the OpenTelemetry API and SDK packages are optional peers of @effect/opentelemetry, so install the ones you import explicitly).
Typed, composable metrics registry. Define counters, gauges, histograms, summaries, and frequency maps as values; update them anywhere; read or export state. Metrics are stored in a registry keyed by name + attributes — the same metric referenced from different modules accumulates to the same series.
Mental model. Metrics are pull-based: declare them, update as side-effects, then an exporter (Prometheus scrape, OTLP push, DevTools request) reads the registry at its own cadence. No push-on-update hot path by default — the registry is an in-memory map.
The registry is itself a Context.Reference, Metric.MetricRegistry (a Map; its type is exported as Metric.MetricRegistry). Every context that does not override it shares one default map, which is what makes metrics feel global. Provide a fresh map — Effect.provideService(Metric.MetricRegistry, new Map()) — to isolate a test or an embedded program: the same metric value then reads and updates the active registry, and each registry keeps its own state.
Series can also be removed: Metric.remove(metric) (unstable) deletes the series for the current Metric.CurrentMetricAttributes from the active registry, and Metric.registerUnsafe(metric, context, state) registers a series whose value is read at snapshot time and returns a handle with remove(). Use them for per-resource series (one per pool, per entity) so they disappear with the resource; the OTLP and OpenTelemetry exporters drop delta state for series that are no longer registered.
Accumulated deltas: employees processed, errors, retries. Set { incremental: true } to reject negative updates and enforce monotonic growth; without it a counter may go down, and OTLP export preserves the negative delta.
Metric.gauge
number | bigint
Instantaneous values: budget remaining, active review workflows
Metric.histogram
number
Distributions with pre-defined buckets: merit-calc latency, raise amounts
Metric.timer
Duration
A histogram of durations in milliseconds, tagged time_unit: milliseconds, with exponential default boundaries — the natural target of Effect.trackDuration
Metric.summary
number
Rolling-window quantiles (p50/p99) without bucket pre-definition. Quantiles are computed per process over maxAge/maxSize and cannot be merged across instances — prefer a histogram for fleet-wide latency
Metric.frequency
string
String occurrence counts over a finite vocabulary: performance ratings, approval outcomes
Metric.update and Metric.modify differ only where it matters most. For a counter both add the input. For a gauge, updatesets the level and modifyadds a delta — so budget drawdown and in-flight counts use modify, while "current queue depth as just measured" uses update.
Specify per metric, next to its definition: name, description, unit, where it is updated, expected range, attributes and their series ceiling, bucket boundaries, and the query that reads it.
Self-contained source · Type-checked
ts
import { Duration, Effect, Metric } from "effect"// Counter — total employees processed in a merit cycle.const employeesProcessed = Metric.counter("merit_employees_processed_total", { description: "Total employees processed in merit cycles"})// Gauge — remaining merit budget pool (BigInt for currency precision).const meritBudgetRemaining = Metric.gauge("merit_budget_remaining_usd", { description: "Remaining merit budget pool in USD cents", bigint: true})// Histogram — distribution of individual raise amounts.const raiseAmountMs = Metric.histogram("merit_raise_amount_usd", { description: "Distribution of approved raise amounts in USD", boundaries: Metric.linearBoundaries({ start: 0, width: 1000, count: 20 }) // normalized boundaries: $1000, $2000, ..., $18000, Infinity})// Summary — rolling-window merit-calculation latency quantiles.const calcLatency = Metric.summary("merit_calc_latency_ms", { maxAge: Duration.minutes(5), maxSize: 1000, quantiles: [0.5, 0.9, 0.99]})// Frequency — count each PerformanceRating value across a cycle.const ratingFrequency = Metric.frequency("merit_performance_ratings")const processMeritRecommendation = Effect.fn("merit.processRecommendation")( function*(employeeId: string, raiseCents: bigint, rating: string) { // ... apply raise logic ... yield* Effect.sleep("30 millis") yield* Metric.update(employeesProcessed, 1) yield* Metric.modify(meritBudgetRemaining, -raiseCents) // subtract from the current gauge yield* Metric.update(raiseAmountMs, Number(raiseCents)) yield* Metric.update(ratingFrequency, rating) }, // Time the whole call with the runtime's monotonic clock instead of reading the clock twice. // trackDuration records on success, failure, and interruption alike. Effect.trackDuration(calcLatency, Duration.toMillis))
Effect.track* attaches a metric to an effect as an aspect, so the update cannot be forgotten on one branch and the effect's type does not change.
Aspect
Feeds the metric with
Fires on
Effect.trackSuccesses(metric, f?)
The success value, or f(value)
Success
Effect.trackErrors(metric, f?)
The typed error, or f(error)
Typed failure
Effect.trackDefects(metric, f?)
The defect, or f(defect)
Defect
Effect.trackDuration(metric, f?)
The elapsed Duration (monotonic clock), or f(duration)
Every exit, interruption included
Effect.track(metric, f?)
The whole Exit, or f(exit)
Every exit
With a mapper, the mapper's parameter type bounds what it can be attached to: Effect.track(metric, f) and Effect.trackErrors(metric, f) reject an effect whose error type f does not accept, so a mapper written for one error union cannot silently be reused on a wider one.
Fragment · Type-checked
ts
import { Effect, Metric, Schema } from "effect"class BandLookupFailed extends Schema.TaggedError<BandLookupFailed>()("BandLookupFailed", { reason: Schema.Literals(["timeout", "not-found"])}) {}declare const approveRaise: (employeeId: string) => Effect.Effect<{ readonly amountUsd: number }, BandLookupFailed>// withConstantInput turns "count one" into a metric that ignores what it is fed.const approved = Metric.counter("raise_approvals_total", { incremental: true }).pipe( Metric.withConstantInput(1))const approvalFailures = Metric.frequency("raise_approval_failures") // keyed by a bounded reasonconst approvalLatency = Metric.timer("raise_approval_duration")export const approveRaiseInstrumented = (employeeId: string) => approveRaise(employeeId).pipe( Effect.trackSuccesses(approved), Effect.trackErrors(approvalFailures, (error) => error.reason), Effect.trackDuration(approvalLatency) ) // still Effect<{ amountUsd: number }, BandLookupFailed>
A gauge incremented when work starts must be decremented in a finalizer, because only a finalizer runs on all three exits. Code placed after yield* work runs on success only, so a typed failure leaves the gauge high; Effect.tap plus Effect.tapError covers success and failure but still misses interruption, which is how timeouts, races, and shutdown end work.
Self-contained source · Type-checked
ts
import { Effect, Metric } from "effect"const activeMeritCalculations = Metric.gauge("merit_calculations_active", { description: "Merit calculations currently in flight"})export const trackedAsActive = <A, E, R>(work: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => Metric.modify(activeMeritCalculations, 1).pipe( Effect.andThen(work.pipe(Effect.ensuring(Metric.modify(activeMeritCalculations, -1)))) )
Restore strategy
Success
Typed failure
Interruption
Statement after yield* work
restored
leaks
leaks
Effect.tap + Effect.tapError
restored
restored
leaks
Effect.ensuring / Effect.acquireRelease
restored
restored
restored
Effect.acquireUseRelease(Metric.modify(gauge, 1), () => work, () => Metric.modify(gauge, -1)) is the stricter spelling: the increment runs uninterruptibly, which also closes the narrow window where an interrupt lands after the increment but before the finalizer is installed. The same rule covers any "currently open" number: connections, queue consumers, leases.
Tagging metrics at call sites — per-department breakdown
Self-contained source · Type-checked
ts
import { Effect, Metric } from "effect"const employeesProcessed = Metric.counter("merit_employees_processed_total")// Add attributes at a specific call site without creating a new metric object.const processDepartmentBatch = (departmentId: string) => Metric.update( Metric.withAttributes(employeesProcessed, { department: departmentId, cycleYear: "2025" }), 1 )
Warning:department and cycleYear are safe labels because both have a small, known set of values. employeeId here would create one time series per employee — tens of thousands of series that no dashboard reads. Put the employee id on the span or the log line instead (see Cardinality).
Attributes can also be set for a whole region. Metric.CurrentMetricAttributes is a Context.Reference; providing it tags every metric updated inside the wrapped effect — the metric counterpart of Effect.annotateLogs. Metric.value(metric) returns the typed state (count, value, buckets, quantiles, or occurrences), which is how a test asserts on metrics without an exporter.
Fragment · Type-checked
ts
import { Effect, Metric } from "effect"const raisesApplied = Metric.counter("raises_applied_total", { incremental: true })declare const applyRaises: Effect.Effect<void>export const applyRaisesForRegion = (region: "amer" | "emea" | "apac") => Effect.gen(function*() { yield* applyRaises yield* Metric.update(raisesApplied, 1) // Read inside the same region: this is the { region } series. return (yield* Metric.value(raisesApplied)).count }).pipe(Effect.provideService(Metric.CurrentMetricAttributes, { region }))
A series is identified by name + the full attribute set, so Metric.value read outside the region (or with different attributes) reports a different, usually empty, series.
Attribute order does not matter: { a, b } and { b, a } address the same series.
Keep the region vocabulary bounded for the same reason as call-site attributes — a tenant attribute is only safe when the tenant list is small and controlled.
import { Effect, Metric } from "effect"// Add built-in fiber lifecycle metrics (fiber count, duration, etc.).// Provide this layer at the top of your program.const program = mainEffect.pipe( Effect.provide(Metric.enableRuntimeMetricsLayer))
Runtime metrics describe the fiber runtime (how many fibers started, how long they lived); they are not evidence that the application is healthy or doing useful work. Pair them with the domain and saturation metrics above.
Reach for it when tracking throughput, budget drawdown, raise distributions, or any numeric signal. Pair with OtlpMetrics or PrometheusMetrics to export.
Getting logs, spans, and metrics out of the process. Instrumentation stays in business code (Observability); export is a Layer chosen once per process. This page covers choosing and owning an export path, Effect's native OTLP exporters, the OTLP proxy for browser telemetry, Prometheus, the Effect DevTools, and the bridge to the OpenTelemetry Node and Web SDKs.
Instrumentation lives in business code; export is a Layer decision made once per process. The decisions below are about ownership — which component exports each signal, in what order it starts, who samples, and how long shutdown may wait.
Metrics only. Restrict who can reach the endpoint, and do not treat a 200 from it as health
Export each signal through exactly one path. With the SDK bridge and a direct OTLP layer both installed, logs and metrics are reported twice (both loggers sit in the logger set, and both exporters read the same registry), while for traces only one Tracer can be current, so one path silently replaces the other. Mixing paths across signals (OTLP traces, Prometheus metrics) is fine.
Install one exporter graph in the application scope — not per request, not inside a workflow, and not inside a library. A per-request exporter pays connection setup and a shutdown flush on every call, and a library that installs its own competes with the application's.
Build the root so that telemetry exists before anything that logs, traces, or forks:
Transport and resource prerequisites (FetchHttpClient.layer, OtlpSerialization, resource attributes).
Tracer, logger, and metric export Layers.
Application Layers, including any that fork background fibers at construction — a fiber forked before the tracer and logger are installed keeps the context it was forked with.
App.pipe(Layer.provide(ObservabilityLayer)) (or provideMerge) gives exactly this order: the provided Layer is built first and released last, so fibers forked while App is constructed — and the logs written by App's finalizers — go through the installed logger and tracer. On shutdown the sequence runs in reverse: stop admitting work, let application finalizers run while exporters still work, flush, finalize exporters, then release the HTTP client they post through.
Warning:Layer.merge(App, ObservabilityLayer) builds the two side by side. App is then constructed without the telemetry references in its context: logs from its eager fibers and finalizers bypass the merged logger, and the exporter may be released before App is. Merge is for independent Layers; telemetry is a dependency, so provide it.
Every flush needs a deadline, or a dead collector holds the process open. The OTLP layers bound their scope-close flush with shutdownTimeout (default 3 seconds per exporter); a hand-rolled exporter should wrap its release in Effect.timeoutOption, and so should a manual Flusher.flush.
Only a host that awaits shutdown can promise a completed flush. On pagehide in a browser or a serverless freeze, assert only that a best-effort flush started.
Before production, review: package stability (@stability unstable modules such as effect/observability), flush and shutdown behavior, sampling, redaction, and label limits.
sampled is options.sampled if given; otherwise false under an unsampled parent; otherwise the span's level compared with Tracer.MinimumTraceLevel (default "All"). There is no probabilistic sampler in core
Direct OtlpTracer
Exports only spans whose sampled flag is already true; it makes no sampling decision of its own
@effect/opentelemetry bridge
The configured OpenTelemetry sampler owns new-root decisions
Prometheus
No sampling — metrics are aggregates
A trace-level threshold is a filter, not a sampler: it drops whole classes of spans, not a percentage.
Tail sampling in a collector can only keep traces that reached it; it cannot recover what a head sampler dropped.
Never compute SLIs from sampled spans. Rates, error ratios, and latency objectives come from unsampled metrics.
Write down the head decision, parent-based behavior, tail rules, and how errors and slow traces are treated — and monitor the effective sampling rate.
Work up this ladder; each rung catches what the previous one cannot:
Recording Layers in unit tests. A capturing Logger.make, a Tracer.make that records spans, and a fresh Metric.MetricRegistry let a test assert fields, annotation inheritance, parent and link structure, span exit status, and that each span ends exactly once.
Privacy and cardinality tests on encoded output. Feed canary secrets and adversarial attribute keys through the real formatter and assert they are absent or masked, and that the series count stays under its ceiling.
Real exporter or scrape integration. Decode the OTLP body or parse the Prometheus exposition; asserting that "an HTTP call happened" proves nothing about content.
Propagation across real HTTP and queue boundaries, including malformed headers and unsampled parents.
Outage behavior: a 429, a slow collector, an exporter in its disabled window — the application keeps serving.
Shutdown of the built artifact with the collector absent and slow: the process exits within its deadline.
Operational proof: a cost and cardinality budget, an SLO query run against synthetic traffic, and an alert that actually routes.
A topology fixture should acquire telemetry before a Layer that forks an eager fiber and assert that the fiber records through the intended logger and tracer.
The first rung needs nothing but core modules:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Logger, Metric, References } from "effect"const approvals = Metric.counter("raise_approvals_total", { incremental: true })const approveRaise = (cycleId: string) => Effect.gen(function*() { yield* Metric.update(approvals, 1) yield* Effect.logInfo("raise approved") }).pipe(Effect.annotateLogs({ cycleId }))it.effect("records one approval with its fields", () => Effect.gen(function*() { const records: Array<{ readonly message: unknown; readonly annotations: Record<string, unknown> }> = [] const recording = Logger.make<unknown, void>((options) => { records.push({ message: options.message, annotations: { ...options.fiber.getRef(References.CurrentLogAnnotations) } }) }) const count = yield* Effect.gen(function*() { yield* approveRaise("2026-merit") return (yield* Metric.value(approvals)).count // read inside the same registry }).pipe( Effect.provide(Logger.layer([recording])), // A fresh registry: counts from other tests cannot leak in. Effect.provideService(Metric.MetricRegistry, new Map()) ) assert.strictEqual(count, 1) assert.deepStrictEqual(records, [ { message: ["raise approved"], annotations: { cycleId: "2026-merit" } } ]) }))
All-in-one OTLP layer. Wires OtlpLogger, OtlpMetrics, and OtlpTracer from a single config, posting to /v1/logs, /v1/metrics, and /v1/traces under a shared baseUrl.
Mental model.Otlp.layerJson({ baseUrl, resource }) activates full observability. Bundles serialization, batching, retry-on-429, and graceful flush at shutdown. Requires HttpClient. Every Otlp.layer* constructor provides the one OtlpExporter.Flusher shared by all three signals, so Layer.Layer<OtlpExporter.Flusher, never, HttpClient> is its type and a single flush drains logs, metrics, and traces — for example before a serverless instance is suspended. Per-signal export intervals: loggerExportInterval, metricsExportInterval, tracerExportInterval.
Fragment · Type-checked with fixture
ts
import { NodeRuntime } from "@effect/platform-node"import { Layer } from "effect"import { FetchHttpClient } from "effect/http"import { Otlp } from "effect/observability"// layerJson bakes in JSON serialization — no OtlpSerialization dep needed.export const ObservabilityLayer = Otlp.layerJson({ baseUrl: "http://localhost:4318", resource: { serviceName: "comp-service", serviceVersion: "2.0.0", attributes: { "deployment.environment": "production" } }, // Optional per-signal tuning: // loggerExportInterval: "2 seconds", // metricsExportInterval: "30 seconds", // tracerExportInterval: "5 seconds", // metricsTemporality: "delta"}).pipe(Layer.provide(FetchHttpClient.layer))Layer.launch(Main.pipe(Layer.provide(ObservabilityLayer))).pipe( NodeRuntime.runMain)
Prefer layerJson for most projects. Use layerProtobuf when the collector requires protobuf encoding. Use the lower-level layer when providing OtlpSerialization yourself.
Options beyond the ones shown:
Option
Default
Effect
shutdownTimeout
"3 seconds" per exporter
Upper bound on the flush that runs when the Layer's scope closes. With a dead collector the process exits after this long instead of hanging; raise it only if the host's termination grace period allows
loggerMergeWithExisting
true
Keeps the loggers already installed (so console output and tracerLogger span events survive). Set false to make OTLP the only log sink
loggerExcludeLogSpans
false
Omits Effect.withLogSpan timings from exported records
maxBatchSize
1000 (logs and traces)
Buffer size that triggers an early export
headers
none
Extra request headers on every export, for example collector authentication
compression
"none"
Opt into "gzip" for JSON or protobuf; uses HttpClientRequest.compressBody's default 1 KB minimum body size, so small batches remain uncompressed
Default export intervals are 1 second for logs, 5 seconds for traces, and 10 seconds for metrics. Otlp.layerFromConfig reads the endpoint, headers, schedule, and timeouts from the standard OTEL_* environment variables instead (an OTEL_EXPORTER_OTLP_TIMEOUT value becomes the shutdownTimeout), and installs no exporter when OTEL_SDK_DISABLED=true or no endpoint is set.
Reach for it when you want a single layer for logs + metrics + traces with zero boilerplate. Recommended starting point for new projects.
An Effect Logger that serializes log records as OTLP log records and ships them via HTTP. Includes log level, message, annotations, cause, fiber id, and current trace/span ids. Batches are flushed on scope finalization to prevent log loss on graceful shutdown.
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { FetchHttpClient } from "effect/http"import { OtlpLogger, OtlpSerialization } from "effect/observability"// Ship comp-service structured logs (with employeeId/cycleId annotations) to// a local OTLP collector. OtlpLogger.layer merges with existing loggers by default.export const CompServiceLogLayer = OtlpLogger.layer({ url: "http://localhost:4318/v1/logs", resource: { serviceName: "comp-service" }, exportInterval: "1 second", // excludeLogSpans: true — omit withLogSpan metadata from records}).pipe( Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer))
Use OtlpLogger.layerFromConfig() to read endpoint URL and headers from OTEL_EXPORTER_OTLP_* environment variables. All built-in signal exporters also accept compression: "gzip" | "none"; config-based layers read OTEL_EXPORTER_OTLP_COMPRESSION, with OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, and OTEL_EXPORTER_OTLP_TRACES_COMPRESSION taking precedence for their signal. Batches are compressed once before HTTP retries, not on each retry; compression failures follow the same temporary-disable path as transport failures.
Reach for it when exporting only logs, or assembling a custom observability stack per signal.
Periodically reads the Effect metric registry and posts snapshots to an OTLP metrics endpoint. Supports "cumulative" and "delta" aggregation temporality.
A Metric.summary is exported as one OTLP Summary metric named by its id (quantiles, count, and sum together), always cumulative regardless of temporality. Each metric's OTLP unit comes from its unit attribute (or the time_unit attribute that Metric.timer sets): nanoseconds, microseconds, milliseconds, seconds, and bytes are mapped to the UCUM units ns, us, ms, s, and By, other values pass through unchanged, and a metric with neither attribute exports an empty unit, not the dimensionless "1" — set unit: "1" on ratios and counts a backend should treat as dimensionless. Dashboards that matched separate <id>_quantiles, <id>_count, or <id>_sum series need updating.
Delta histograms omit min and max after the initial export: the registry's cumulative extrema cannot describe a later delta interval.
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { FetchHttpClient } from "effect/http"import { OtlpMetrics, OtlpSerialization } from "effect/observability"// Export merit-cycle throughput counters and budget gauges every 30 seconds.export const MeritMetricsLayer = OtlpMetrics.layer({ url: "http://localhost:4318/v1/metrics", resource: { serviceName: "comp-service" }, exportInterval: "30 seconds", temporality: "delta" // or "cumulative"}).pipe( Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer))
Reach for it when using metrics only, or assembling a custom per-signal stack.
Replaces the Effect runtime's Tracer with one that batches and exports finished spans over OTLP/HTTP. Spans include trace and span IDs, parent links, attributes, events, timing, kind, and status — ERROR for a failure or defect, otherwise Unset, including on success (see What ends up on a span).
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { FetchHttpClient } from "effect/http"import { OtlpSerialization, OtlpTracer } from "effect/observability"// Export merit-calculation spans to a staging collector using protobuf encoding.export const CompTracingLayer = OtlpTracer.layer({ url: "http://localhost:4318/v1/traces", resource: { serviceName: "comp-service", serviceVersion: "1.0.0", attributes: { "deployment.environment": "staging" } }, exportInterval: "5 seconds", maxBatchSize: 512}).pipe( Layer.provide(OtlpSerialization.layerProtobuf), // protobuf encoding Layer.provide(FetchHttpClient.layer))
Reach for it when exporting traces only, or composing a custom per-signal observability stack.
Shared batch-export engine used internally by OtlpLogger, OtlpMetrics, and OtlpTracer. Buffers items, posts encoded batches at a configurable interval, retries transient errors, honors HTTP 429 Retry-After, temporarily disables export after repeated failures (60 s backoff), and flushes on scope close. Typically not used directly.
For an explicit graceful-shutdown checkpoint, acquire OtlpExporter.Flusher — the Otlp.layer* constructors already provide it; per-signal layers need the shared OtlpExporter.layerFlusher provided once beside them — and run flusher.flush; it concurrently drains every registered signal exporter and cannot fail. There is no built-in timeout, so wrap it in Effect.timeoutOption when shutdown has a deadline. Registration is scoped, and exporters inside their temporary disabled window are skipped.
Delivery semantics, so nobody mistakes export for a guarantee:
The scope-close flush is bounded by the exporter's shutdownTimeout (3 seconds unless configured); whatever is still buffered after that is lost.
A Retry-After on 429 is honoured when it is whole non-negative seconds or an HTTP date; anything else (1.5, -5, Infinity) is ignored and the fixed delay applies.
A failed export is dropped, not queued. Transient HTTP failures are retried a few times; if the export still fails, the buffer is cleared, the exporter disables itself for 60 seconds, and everything pushed during that window is discarded.
The exporter announces its own failure only at Debug level ("Disabling exporter for 60 seconds"), which the default Info minimum hides — another reason to watch export health through a second path.
The exporter's own HTTP calls run with tracing disabled and without trace-header propagation, so exporting does not generate more spans to export.
An idle log or trace exporter keeps no timer pending. Its interval starts with the first buffered record and stops once an export empties the buffer, so a Node program kept alive only by an idle OtlpLogger or OtlpTracer exits. The metrics exporter is different: it exports on every interval, empty or not, so its timer runs for as long as its Layer is alive.
Reach for it when implementing a custom OTLP signal type that needs the same batching, retry, and graceful-shutdown behaviour as the built-in exporters.
Builds the OTLP Resource object (service name, version, arbitrary attributes) attached to every exported signal. OtlpResource.make({ serviceName, serviceVersion, attributes }) returns a Resource; fromConfig reads from a config record. Helpers entriesToAttributes and unknownToAttributeValue convert JS values to OTLP KeyValue/AnyValue; an integer outside the signed 64-bit range becomes a doubleValue (numbers) or stringValue (bigints) so collectors do not reject the batch, and NaN/Infinity are no longer written as null by OtlpSerialization.layerJson. fromConfig trims and percent-decodes OTEL_RESOURCE_ATTRIBUTES keys and values, keeps an entry with an empty value as "", skips entries without = or with an empty key, and lets the last repeated key win; invalid percent-encoding is a defect.
Reach for it when building a custom OTLP exporter that needs standard resource metadata, or inspecting how Effect maps JS values to OTLP attribute types.
A Context.Service class with three methods — traces(data), metrics(data), logs(data) — that convert in-memory OTLP data structures to HttpBody instances. Two implementations: OtlpSerialization.layerJson (JSON, default) and OtlpSerialization.layerProtobuf (binary protobuf, application/x-protobuf).
For custom OTLP payloads, the in-memory interfaces use schemaUrl on resource/scope records, and the JSON layer serializes those objects directly: it does not rename that property to schemaURL. Protobuf writes the numbered schema-URL field from schemaUrl. If a collector requires a different JSON spelling, supply an explicit custom OtlpSerialization rather than assuming a rewrite. Exported 64-bit trace ids are left-padded to 128 bits, consistently with outgoing traceparent headers. layerJson writes bytesValue attribute data — a Uint8Array or a Node Buffer — as the base64 string OTLP/JSON expects, and layerProtobuf omits startTimeUnixNano from a metric data point that has none instead of throwing.
Self-contained source · Type-checked
ts
import { OtlpSerialization } from "effect/observability"// JSON — zero extra deps, works everywhere.export const JsonSerialization = OtlpSerialization.layerJson// Protobuf — smaller on the wire, required by some collectors.export const ProtobufSerialization = OtlpSerialization.layerProtobuf
Reach for it when choosing or swapping serialization format, or writing a custom signal exporter in the same service graph.
Forwards browser OTLP exports through your own HTTP server, so vendor credentials stay on the server and the browser exports to its own origin. OtlpProxy.layer({ baseUrl, headers?, prefix?, signals?, urls?, maxBodySize?, timeout? }) mounts POST <prefix>/v1/traces, /v1/logs, and /v1/metrics on the HttpRouter in context and requires an HttpClient; layerFromConfig reads each upstream from OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT / OTEL_EXPORTER_OTLP_ENDPOINT and headers from the matching *_HEADERS (a signal without an endpoint gets no route); make returns the three handlers for mounting elsewhere, such as an HttpApi endpoint.
The payload passes through untouched. Only application/json and application/x-protobuf are accepted (415 otherwise); bodies are buffered up to maxBodySize (the HttpIncomingMessage.MaxBodySize reference, else 10 MiB; 413 beyond it) and not decoded.
The client cannot steer the upstream. The upstream URL comes only from configuration — the request path and query never reach it — only content-type and content-encoding are forwarded, and configured headers are applied last.
Back-off survives the hop. The upstream status and body come back with only content-type and retry-after; transport failures return 502, timeouts (timeout, default 10 seconds) 504. The proxy does not retry or batch, and its own upstream call is untraced.
It is an open credentialed endpoint. Anyone who can reach the routes sends telemetry with your credentials: compose authentication, CORS, and rate limiting around it. The proxy routes are traced like any other route unless you exclude them with HttpMiddleware.TracerDisabledWhen or HttpMiddleware.layerTracerDisabledForUrls.
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { FetchHttpClient, HttpRouter } from "effect/http"import { Otlp, OtlpProxy } from "effect/observability"// Server: POST /otlp/v1/{traces,logs,metrics} forwarded with the vendor key.export const OtlpProxyRoutes = OtlpProxy.layer({ baseUrl: "https://otlp.vendor.example", headers: { authorization: "Bearer server-side-key" }, prefix: "/otlp"}).pipe(Layer.provide(FetchHttpClient.layer))export const ServerRoutes = HttpRouter.serve(OtlpProxyRoutes)// Browser: export to the page's own origin; no credentials in the bundle.export const BrowserTelemetry = Otlp.layerJson({ baseUrl: "/otlp", resource: { serviceName: "comp-planning-ui" }}).pipe(Layer.provide(FetchHttpClient.layer))
Reach for it when a browser or other untrusted client must export OTLP to a vendor or collector that needs credentials or another origin.
Renders the Effect metric registry in Prometheus exposition format (text/plain version 0.0.4). PrometheusMetrics.format() returns Effect<string>; PrometheusMetrics.layerHttp() registers a GET /metrics route on the HttpRouter service in context.
Self-contained source · Type-checked
ts
import { Effect, Metric } from "effect"import { PrometheusMetrics } from "effect/observability"import { HttpRouter } from "effect/http"import { Layer } from "effect"// Standalone: format on demand — for a debug dump or a custom scrape route.const printMeritMetrics = Effect.gen(function*() { const text = yield* PrometheusMetrics.format({ prefix: "comp" }) yield* Effect.log(text)})// HTTP route: Prometheus scrapes this to collect merit-cycle throughput metrics.// PrometheusMetrics.layerHttp requires HttpRouter in context; provide HttpRouter.layer.const MetricsLayer = PrometheusMetrics.layerHttp({ prefix: "comp", path: "/metrics" }).pipe( Layer.provide(HttpRouter.layer))
Tip: Prometheus naming conventions expect snake_case. If Effect metrics use camelCase names, pass a metricNameMapper to format or layerHttp: metricNameMapper: (n) => n.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().
Restrict who can reach /metrics: metric names and attribute values describe the business, so serve the route on an internal listener or behind authentication.
A 200 from /metrics is not health. It proves the HTTP server answers, nothing about the database or HRIS; keep it out of readiness checks.
Prometheus has no sampling and no per-request detail — every attribute combination is a stored series, so the cardinality rules apply in full.
Reach for it when running a Prometheus-compatible stack (Prometheus + Grafana, Victoria Metrics, etc.) and want metrics scraped via a pull endpoint.
Tip:New project? Use effect/observability/Otlp*. No peer dependencies, works in Node, Bun, Deno, and browsers, purpose-built for Effect's data model. A single Otlp.layerJson({ baseUrl, resource }) covers logs, metrics, and traces.
Existing OpenTelemetry SDK in the picture? Use @effect/opentelemetry. It bridges Effect tracing/logging/metrics into the OTel API/SDK so existing SpanProcessor, MetricReader, and LogRecordProcessor pipelines keep working. The bridge is load-order sensitive for auto-instrumentation — read the NodeSdk docs carefully.
You can also mix them: use OtlpTracer for lightweight span export while keeping @effect/opentelemetry's NodeSdk for an existing metrics reader.
Application-side entry point for connecting to the Effect DevTools desktop app. DevTools.layer(url?) opens a WebSocket to ws://localhost:34437 (or a custom URL) and mirrors spans and metric snapshots to the DevTools process. Zero configuration required for local development. The client sends a Ping as soon as it connects, retries a failed or dropped connection every second (logging failures at Debug), so the DevTools app may start after the program, and on shutdown stops pending connections while still flushing telemetry queued on a healthy one. Spans that have already ended send no further events.
Mental model. DevTools is a development-only OTLP exporter that streams to a local GUI instead of a collector. Add DevTools.layer() alongside your ObservabilityLayer in development. Gate on NODE_ENV or remove in production.
Fragment · Type-checked with fixture
ts
import { NodeRuntime } from "@effect/platform-node"import { Config, Layer } from "effect"import { DevTools } from "effect/devtools"const DevToolsLayer = Layer.unwrap( Config.String("NODE_ENV").pipe( Config.withDefault("development"), Config.map((env) => env === "development" ? DevTools.layer() // connects to ws://localhost:34437 : Layer.empty ) ))Layer.launch(Main.pipe(Layer.provide(DevToolsLayer))).pipe( NodeRuntime.runMain)
DevTools.layerWebSocket(url) requires an explicit Socket.WebSocketConstructor in context. DevTools.layerSocket is the lowest-level variant accepting any Socket.Socket.
Reach for it when visually inspecting fiber topology, span trees, and live gauge values during development without setting up a collector.
Low-level socket protocol layer underneath DevTools. Drives the NDJSON duplex channel, queues Ping heartbeats, sends span starts/events/completions, responds to MetricsRequest messages by snapshotting the metric registry, and exposes DevToolsClient.layerTracer which installs a tracer that wraps the existing tracer and forwards events to the socket.
Reach for it when building a custom DevTools integration or embedding the DevTools protocol into a different transport (e.g. TCP socket, Unix pipe).
Server-side half of the DevTools protocol. DevToolsServer.run accepts a Client (a socket connection from a connected Effect application) and drives the conversation: receives span and metric data, sends metric snapshot requests and pong responses. Used by the Effect DevTools desktop app itself; not typically used in application code.
Schema definitions for the DevTools wire protocol — Span, SpanEvent, Ping/Pong, MetricsRequest, MetricsSnapshot, and the Request/Response discriminated unions. Both client and server use these schemas to encode/decode NDJSON frames over the WebSocket.
@effect/opentelemetry — import * as NodeSdk from "@effect/opentelemetry/NodeSdk" — @effect/opentelemetry
Bridge between Effect and the official OpenTelemetry Node.js SDK. NodeSdk.layer(config) accepts a lazy config factory (or an Effect) returning a Configuration object, and installs tracing (spanProcessor), metrics (metricReader), and logging (logRecordProcessor) based on which are present. Always provides Resource.Resource, reading from OTEL_* environment variables plus any explicit resource metadata.
Mental model.NodeSdk is not a replacement for OTLP exporters — it plugs Effect signals into the OTel SDK's own export pipeline. Your OTel SDK setup (exporters, batch processors, propagators) works as usual; NodeSdk.layer is the glue that routes Effect.withSpan, Metric.counter, and Effect.log into it.
Fragment · Type-checked
ts
import { NodeRuntime } from "@effect/platform-node"import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base"import { Layer } from "effect"import * as NodeSdk from "@effect/opentelemetry/NodeSdk"declare const Main: Layer.Layer<never>// Wire comp-service tracing into OTel's BatchSpanProcessor → OTLP exporter.// NodeSdk.layer takes a lazy factory: () => Configurationconst OtelLayer = NodeSdk.layer(() => ({ resource: { serviceName: "comp-service", serviceVersion: "1.0.0" }, spanProcessor: new BatchSpanProcessor( new OTLPTraceExporter({ url: "http://localhost:4318/v1/traces" }) ) // Add metricReader / logRecordProcessor to enable metrics / log export too.}))Layer.launch(Main.pipe(Layer.provide(OtelLayer))).pipe( NodeRuntime.runMain)
Warning: If using @opentelemetry/auto-instrumentations-node, register it before importing any modules to be patched. Node.js instrumentations hook module loading, so registration must come first in the entry point.
Install the OpenTelemetry packages you import.@effect/opentelemetry declares the OpenTelemetry API and SDK packages as optional peers, so a package manager will not add @opentelemetry/sdk-trace-base, an exporter, or the others for you.
NodeSdk and WebSdk are subpath imports only. The package root re-exports OtelLogger, OtelMetrics, OtelTracer, and Resource, so importing it does not need @opentelemetry/sdk-trace-node or sdk-trace-web. A root import still evaluates all four, so it fails at startup with ERR_MODULE_NOT_FOUND unless @opentelemetry/api, api-logs, sdk-logs, sdk-metrics, resources, and semantic-conventions are installed — even though the code type-checks. Install them, or import only the module you use by path: import * as OtelTracer from "@effect/opentelemetry/OtelTracer". The package requires Node.js 22.19.0 or later.
For a first look without a collector, swap the exporter for new ConsoleSpanExporter() from @opentelemetry/sdk-trace-base; finished spans print to stdout. Any OpenTelemetry SpanProcessor, including a vendor's, fits the same spanProcessor slot.
Do not also install OtlpTracer for traces once the bridge owns them (see One export path per signal); with the bridge, sampling belongs to the OpenTelemetry sampler.
Migration:import { NodeSdk } from "@effect/opentelemetry" and import { WebSdk } from "@effect/opentelemetry" no longer compile; use import * as NodeSdk from "@effect/opentelemetry/NodeSdk" and import * as WebSdk from "@effect/opentelemetry/WebSdk".
Reach for it when your platform team manages an OTel SDK setup, you need OTel-native auto-instrumentation (HTTP, gRPC, DB drivers), or integrating with a service that uses @opentelemetry/sdk-node.
@effect/opentelemetry — import * as WebSdk from "@effect/opentelemetry/WebSdk" — @effect/opentelemetry
Browser equivalent of NodeSdk. Structurally identical API — pass spanProcessor, metricReader, logRecordProcessor — but uses the OTel web tracer provider. Use in browser bundler targets where NodeSdk would pull in Node-only internals.
Self-contained source · Type-checked
ts
import * as WebSdk from "@effect/opentelemetry/WebSdk"import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base"const OtelLayer = WebSdk.layer(() => ({ resource: { serviceName: "comp-planning-ui" }, spanProcessor: new SimpleSpanProcessor( new OTLPTraceExporter({ url: "/otlp/v1/traces" }) )}))
Reach for it when running Effect in a browser and bridging into an existing OTel web SDK setup.
@effect/opentelemetry — import { OtelTracer } from "@effect/opentelemetry" — @effect/opentelemetry
Effect↔OTel tracer bridge. OtelTracer.layer installs an Effect Tracer that creates OtelSpan instances backed by the active OTel TracerProvider. Exposes OtelTracer, OtelTracerProvider, OtelTraceFlags, OtelTraceState services, and currentOtelSpan to retrieve the live OTel span from fiber context. When an Effect span ends, the bridge sets ERROR only for a failure or defect; on success or interruption it leaves the status alone, so a status you set on the span from currentOtelSpan is what gets exported (otherwise Unset).
Reach for it when composing Effect's span model with OTel-native span APIs (e.g. setting OTel-specific span status or accessing the raw OTel Span for a library that requires it).
@effect/opentelemetry — import { OtelMetrics } from "@effect/opentelemetry" — @effect/opentelemetry
Bridges Effect's metric registry into an OTel MetricReader. OtelMetrics.layer(evaluate, options?) accepts a lazy factory returning a MetricReader or non-empty array of readers and registers a MetricProducer that converts Effect metric snapshots to OTel metric data on each collection cycle. Supports cumulative and delta temporality via the temporality option.
Self-contained source · Type-checked
ts
import { OtelMetrics } from "@effect/opentelemetry"import { PrometheusExporter } from "@opentelemetry/exporter-prometheus"// Expose merit-cycle metrics via Prometheus scrape endpoint through OTel SDK.const MetricsLayer = OtelMetrics.layer(() => new PrometheusExporter({ port: 9464 }))
Reach for it when you have an existing OTel metric reader (Prometheus, OTLP push) managed by your platform team and want Effect's built-in metrics to flow into it.
@effect/opentelemetry — import { OtelLogger } from "@effect/opentelemetry" — @effect/opentelemetry
An Effect Logger that forwards log records to an OTel LoggerProvider. OtelLogger.layer({ mergeWithExisting }) installs it alongside or instead of the default logger. OtelLogger.layerLoggerProvider builds and scopes the OTel LoggerProvider from one or more LogRecordProcessors.
Log records receive the current Effect span's OpenTelemetry span context, so the backend can link logs to their traces without copying trace ids into application annotations. This is correlation, not an audit-delivery guarantee.
Reach for it when Effect logs (including structured annotations) need to flow through an existing OTel logging pipeline, e.g. a BatchLogRecordProcessor shipping to a vendor.
@effect/opentelemetry — import { Resource } from "@effect/opentelemetry" — @effect/opentelemetry
Provides the OTel Resource service used by all @effect/opentelemetry modules. Resource.layer({ serviceName, serviceVersion, attributes }) builds from explicit config; Resource.layerFromEnv(additionalAttributes?) merges additional attributes with OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES (read with Config.Record, so a structured config value works too; keys and values are percent-decoded, and a variable with invalid encoding is discarded with a warning); Resource.layerEmpty provides a minimal no-attribute resource. NodeSdk.layer and WebSdk.layer manage this automatically — only needed directly when composing individual OTel bridge layers.
Self-contained source · Type-checked
ts
import { OtelTracer, Resource } from "@effect/opentelemetry"import { Layer } from "effect"// Manually compose: Resource (from env) → TracerProvider → Effect Tracer.// Resource.layerFromEnv merges OTEL_SERVICE_NAME/OTEL_RESOURCE_ATTRIBUTES env vars// with any additional attributes passed as a plain Record<string, unknown>.const CustomTracingLayer = OtelTracer.layer.pipe( Layer.provide(OtelTracer.layerGlobalProvider), Layer.provide(Resource.layerFromEnv({ "service.name": "comp-service", "service.version": "1.0.0" })))
Reach for it when composing individual @effect/opentelemetry bridge layers manually rather than using NodeSdk / WebSdk.
Caching avoids repeating the same lookup result; batching combines many logically independent requests into fewer physical calls. Cache stores both successful and failed lookup Exit values, while ScopedCache owns resource lifetimes. Request and RequestResolver describe data fetching so Effect can deduplicate and batch it safely.
Official example: The release-matched ai-docs batching example builds a batched RequestResolver.
Official guides:Batching (it enables batching with Effect.forEach(..., { batching: true }), an option Effect.forEach does not have — see RequestResolver for what triggers a batch here). These guides track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Repeated work shows up on a dashboard as "too many HRIS calls", but it has several shapes, and each tool fixes exactly one of them. Measure first — hit ratio, lookup count per request, resolver batch size — then pick the smallest tool.
Waste shape
What the measurement looks like
Tool
Why the neighbors do not help
One expensive effect, no key — load all comp bands, fetch a service token
The same effect runs once per caller instead of once per freshness window
Single-flight is not batching. Single-flight collapses concurrent cold gets of the same key into one lookup. Batching collapses concurrent requests for different keys into one backend call. A service often needs both, and they compose: RequestResolver.withCache and RequestResolver.asCache put a cache in front of a batched resolver.
Effect.cached(effect) has the type Effect<Effect<A, E, R>>: running the outer effect creates a memo cell and returns a handle; the first evaluation of the handle runs the work, and later and concurrent evaluations share that one stored Exit.
Mental model. A lazy, single-slot, single-flight cache with no key. Construct it once where the owner lives — usually a Layer — and hand out the handle.
Fragment · Type-checked
ts
import { Context, Effect, Exit, Layer, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {}) {}declare const loadAllCompBands: Effect.Effect<ReadonlyMap<string, number>, HrisUnavailable>export class CompBands extends Context.Service<CompBands, { readonly all: Effect.Effect<ReadonlyMap<string, number>, HrisUnavailable> readonly invalidate: Effect.Effect<void>}>()("app/CompBands") { static readonly layer = Layer.effect( CompBands, Effect.gen(function*() { // Yield the outer effect ONCE; every caller of `all` shares the inner handle. const [all, invalidate] = yield* Effect.cachedInvalidateWithTTL(loadAllCompBands, "5 minutes") return { all, invalidate } }) )}// Exit-based TTL: successes live 5 minutes; failures and interruptions are not retained.export const makeCompBandsHandle = Effect.cachedWithTTL( loadAllCompBands, (exit) => Exit.isSuccess(exit) ? "5 minutes" : 0)
API
Keeps the result
Reset
Effect.cached(e)
For as long as the handle lives
None
Effect.cachedWithTTL(e, ttl)
For ttl, a Duration.Inputor(exit) => Duration.Input
Expiry, read from the Clock — TestClock.adjust controls it in tests
Effect.cachedInvalidateWithTTL(e, ttl)
For ttl, a Duration.Inputor(exit) => Duration.Input
Expiry, or the returned invalidate effect (an invalidation while the effect is running discards that run's result instead of caching it)
Yield the outer effect once and share the handle.yield* Effect.cached(load) at every call site builds a fresh, empty cell each time and caches nothing.
Failures are stored — interruptions are not. With Effect.cached or a fixed-TTL cachedWithTTL, a transient HrisUnavailable is replayed to every caller until expiry, which for cached is never. Branch on the Exit and return 0 for non-success so the next caller retries. Interrupted computations are never cached: the pending work is interrupted only after every waiting caller has been interrupted (abandonment), and the next caller then starts a fresh computation.
Cache applies the same abandonment rule: an interrupted Cache.get lookup is never retained; the next caller starts fresh.
Reach for Cache as soon as there is a key, and for Resource when the value needs scheduled refresh or owns a resource.
Official guide: Caching Effects (its "once" heading is not an API name; the code under it uses Effect.cached).
Effectful memoization table with bounded capacity and optional TTL. A lookup effect is provided at construction; the cache handles concurrent requests, LRU eviction, and TTL expiry. When several fibers ask for an absent key at once, the lookup runs once and all of them await its result.
Mental model. Bounded Map<Key, Deferred<A, E>> that deduplicates concurrent misses. The first fiber to request a missing key starts the lookup and parks a deferred; subsequent fibers await that same deferred. On completion its full Exit is stored, so failures are cached too. Reading an existing entry—including a pending or failed one—moves it to the end of the map, and capacity pressure evicts the least recently accessed entry.
Lookup outcome
Stored?
Consequence
Success
Yes, until its TTL passes or it is evicted
Later get calls are hits
Typed failure or defect
Yes, for the same TTL
Every caller receives the stored failure without a new lookup — protection against a stampede on a failing backend, and a recovery delay if the TTL is long (see Failure and freshness policy)
Interruption
No — interrupted results are never cached
Concurrent callers share the lookup; the lookup is interrupted only once every waiting caller has been interrupted (abandonment). A call made while the abandoned computation is still finalizing starts a fresh lookup. Keep lookups safe to interrupt and to repeat
The TTL is measured from the moment the lookup completes and is read from the Clock; a hit moves the entry to the fresh end of the eviction order but does not extend its TTL.
Self-contained source · Type-checked
ts
import { Cache, Effect } from "effect"// CompBand describes the salary range for a job level (e.g. L3, L4, L5).// Fetching from the HRIS is slow; cache bands for 30 minutes so every// render of the org chart hits memory instead of the API.interface CompBand { readonly level: string readonly minSalary: number readonly midSalary: number readonly maxSalary: number}const fetchCompBandFromHris = (level: string): Effect.Effect<CompBand, string> => Effect.suspend(() => { const bands = new Map<string, CompBand>([ ["L3", { level: "L3", minSalary: 90_000, midSalary: 105_000, maxSalary: 120_000 }], ["L4", { level: "L4", minSalary: 120_000, midSalary: 140_000, maxSalary: 160_000 }], ["L5", { level: "L5", minSalary: 160_000, midSalary: 185_000, maxSalary: 210_000 }] ]) const band = bands.get(level) return band ? Effect.succeed(band) : Effect.fail(`No comp band found for level ${level}`) })const program = Effect.gen(function*() { const compBandCache = yield* Cache.make<string, CompBand, string>({ capacity: 50, // at most 50 levels cached at once timeToLive: "30 minutes", // bands re-fetched after 30 min lookup: fetchCompBandFromHris }) // First call hits the HRIS; second call is instant (cache hit) const l4Band = yield* Cache.get(compBandCache, "L4") const l4Again = yield* Cache.get(compBandCache, "L4") // no HRIS hit console.log(l4Band, l4Again) // Force a fresh HRIS lookup after a comp cycle update yield* Cache.refresh(compBandCache, "L4") // Invalidate a single level after an out-of-cycle band change yield* Cache.invalidate(compBandCache, "L5") // Inspect cache state const size = yield* Cache.size(compBandCache) const keys = yield* Cache.keys(compBandCache) console.log(`${size} bands cached, levels:`, [...keys])})
Cache stores entries in a MutableHashMap, so keys are compared with Effect's Equal and Hash. That comparison is structural for primitives, plain objects, arrays, dates, and Data/Schema classes alike: two separately built { region: "us", level: "L4" } values address the same entry. Identity problems therefore come from the input, not from object references — "L4", "l4", and " L4 " are three keys, and so are hris.example and HRIS.example.
Normalize where raw input enters (trim, case-fold, canonical URL, sorted id list), so equal real-world things become equal values before anything looks them up.
Carry the key as a small value class — Data.Class or Schema.Class — so the type says "this is a stable identity", there is one constructor to normalize in, and nobody passes a whole employee record as a key.
Fragment · Type-checked
ts
import { Cache, Data, Effect } from "effect"class BandKey extends Data.Class<{ readonly region: string; readonly level: string }> { // The only way in: normalize once, at ingress. static fromInput(region: string, level: string): BandKey { return new BandKey({ region: region.trim().toLowerCase(), level: level.trim().toUpperCase() }) }}declare const fetchBandMidpoint: (key: BandKey) => Effect.Effect<number>export const program = Effect.gen(function*() { const midpoints = yield* Cache.make({ capacity: 500, timeToLive: "30 minutes", lookup: fetchBandMidpoint }) yield* Cache.get(midpoints, BandKey.fromInput("US", "l4")) // lookup yield* Cache.get(midpoints, BandKey.fromInput(" us ", "L4")) // hit — same logical key})
Keep keys small and immutable. Hashing and equality walk the key's structure, and a key mutated after insertion may never be found again.
Symptom of a skipped step: a low hit ratio and duplicate lookups for keys that look identical in the logs.
To opt a value out of structural comparison, wrap it with Equal.byReference.
Dynamic TTL — vary per key or per outcome. A zero TTL means "share the in-flight lookup, retain nothing afterwards".
Cache.get(cache, key)
Get or compute. Concurrent misses share one lookup.
Cache.getOption(cache, key)
Read without starting a lookup. Returns None if absent/expired, awaits an existing pending entry, returns Some<A> on success, and fails with the cached lookup error on failure.
Cache.getSuccess(cache, key)
Non-blocking peek: Some<A> only for an entry that has already resolved successfully; None for missing, expired, pending, or failed entries. Never fails.
Cache.refresh(cache, key)
Force and await a new lookup. An existing entry remains readable by other fibers until it completes, then is replaced. Unlike concurrent get misses, concurrent refresh calls are not deduplicated.
Cache.invalidate(cache, key)
Remove one entry, whatever its outcome.
Cache.invalidateWhen(cache, key, predicate)
Remove the entry only if it holds a successful value matching the predicate; returns whether it did. A cached failure is never removed this way.
Cache.invalidateAll(cache)
Clear everything.
Cache.set(cache, key, value)
Manually populate an entry (useful for seeding).
Cache.has(cache, key)
Check for an unexpired entry without lookup.
Cache.size / keys / values / entries
Inspect the table. Expiry is lazy: size counts stored entries, including ones whose TTL has passed but that nothing has touched yet, while keys, values, and entries skip (and drop) expired ones; values and entries list successful entries only.
Tip: By default, services needed by lookup are captured at construction time. Pass requireServicesAt: "lookup" to instead capture them at call time — useful when the lookup needs request-scoped services that weren't available when the cache was built.
A cached failure lives exactly as long as a cached success unless you say otherwise. With Cache.make({ timeToLive: "30 minutes" }), one transient HrisUnavailable is replayed to every caller for thirty minutes after the HRIS has recovered. Give failures their own, deliberately chosen lifetime with Cache.makeWith and branch on the Exit:
Fragment · Type-checked
ts
import { Cache, Effect, Exit, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {}) {}declare const fetchBandMidpoint: (level: string) => Effect.Effect<number, HrisUnavailable>export const makeMidpointCache = Cache.makeWith(fetchBandMidpoint, { capacity: 500, // Long for successes, short for failures. The key is available as the second argument. timeToLive: (exit) => Exit.isSuccess(exit) ? "30 minutes" : "5 seconds"})
Failure TTL
Behavior
Choose it when
Same as success (the Cache.make default)
The failure is served for the full TTL
Almost never what you want
Short (seconds)
Callers share one failure briefly, then one of them retries
The usual answer: it shields a struggling backend from a stampede and still recovers quickly
Zero
Concurrent callers share the in-flight lookup; the next caller starts a new one
The lookup is cheap, or an outer retry policy already paces the calls
TTL is a deadline; invalidation is an event. When something tells you an entry is wrong now — a comp-band update arrived, a retry path just saw a transient failure — call Cache.invalidate (any outcome), Cache.invalidateWhen (successful values only), or Cache.refresh (replace while readers keep the old value). Do not shorten the TTL to approximate an event you could have handled.
Correctness guarantees.invalidateWhen never deletes a replacement entry that was written while it was reading the old value; an interrupted or zero-TTL refresh of a missing key never removes a newer value written by Cache.set; refresh never pushes the table past capacity when its key is evicted mid-refresh; and a synchronously interrupted lookup is never retained. A cache hit also re-stores the entry under the key instance you just passed to get/getOption, not the instance used to create it, so replacing an equal-but-distinct key object (for example, a rebuilt Data.Class) does not keep the old object pinned in the map. The same guarantees apply to ScopedCache.
Count lookups with a Ref, move time with TestClock, and prove overlap with a Deferred gate instead of a sleep. Assert just before and just after each deadline.
Self-contained source · Type-checked
ts
import { assert, describe, it } from "@effect/vitest"import { Cache, Deferred, Effect, Exit, Fiber, Ref } from "effect"import { TestClock } from "effect/testing"describe("band midpoint cache", () => { it.effect("retries a failure after its own TTL, keeps a success for the long one", () => Effect.gen(function*() { const lookups = yield* Ref.make(0) const cache = yield* Cache.makeWith( (_level: string) => Ref.updateAndGet(lookups, (n) => n + 1).pipe( Effect.flatMap((n) => n === 1 ? Effect.fail("HrisUnavailable" as const) : Effect.succeed(140_000)) ), { capacity: 10, timeToLive: (exit) => Exit.isSuccess(exit) ? "30 minutes" : "5 seconds" } ) assert.isTrue(Exit.isFailure(yield* Effect.exit(Cache.get(cache, "L4")))) yield* TestClock.adjust("4 seconds") assert.isTrue(Exit.isFailure(yield* Effect.exit(Cache.get(cache, "L4")))) // replayed assert.strictEqual(yield* Ref.get(lookups), 1) yield* TestClock.adjust("1 second") // failure TTL reached assert.strictEqual(yield* Cache.get(cache, "L4"), 140_000) yield* TestClock.adjust("29 minutes") assert.strictEqual(yield* Cache.get(cache, "L4"), 140_000) assert.strictEqual(yield* Ref.get(lookups), 2) })) it.effect("collapses concurrent cold gets into one lookup", () => Effect.gen(function*() { const lookups = yield* Ref.make(0) const started = yield* Deferred.make<void>() const release = yield* Deferred.make<void>() const cache = yield* Cache.make({ capacity: 10, lookup: (_level: string) => Ref.update(lookups, (n) => n + 1).pipe( Effect.andThen(Deferred.succeed(started, undefined)), Effect.andThen(Deferred.await(release)), Effect.as(140_000) ) }) const callers = yield* Effect.forkChild( Effect.all([Cache.get(cache, "L4"), Cache.get(cache, "L4"), Cache.get(cache, "L4")], { concurrency: "unbounded" }) ) yield* Deferred.await(started) // the lookup is running; no caller has a value yet assert.strictEqual(yield* Ref.get(lookups), 1) yield* Deferred.succeed(release, undefined) assert.deepStrictEqual(yield* Fiber.join(callers), [140_000, 140_000, 140_000]) assert.strictEqual(yield* Ref.get(lookups), 1) }))})
TestClock is provided by it.effect; see TestClock for the clock itself.
When to use: effectful computation (HTTP call, expensive decode) hit by many callers with the same keys, where you want deduplication of in-flight requests plus time-bounded staleness.
Official guide: Cache (it shows timeToLive as a required option; the API makes it optional and defaults to no expiry).
Cache variant for entries that own resources. Each cached value gets its own Scope; on eviction, invalidation, or TTL expiry, that scope closes and all acquired resources are released. The cache itself lives inside an outer scope; closing it tears down every remaining entry.
Mental model. One live resource per key (e.g., a connection per tenant shard) with automatic teardown when a key falls out of use. The lookup receives Scope.Scope in its environment, so Effect.acquireRelease works directly inside it — the cache wires up the lifetimes.
Self-contained source · Type-checked
ts
import { ScopedCache, Effect, Scope } from "effect"// A live streaming connection to a payroll-system tenant shard.interface PayrollShardConn { readonly query: (sql: string) => Effect.Effect<unknown[]> readonly close: Effect.Effect<void>}const openPayrollConn = ( shardId: string): Effect.Effect<PayrollShardConn, never, Scope.Scope> => Effect.acquireRelease( Effect.sync(() => { const conn: PayrollShardConn = { query: (sql) => Effect.succeed([{ shardId, sql }]), close: Effect.sync(() => console.log(`closing payroll shard ${shardId}`)) } console.log(`opened payroll shard ${shardId}`) return conn }), (conn) => conn.close )const program = Effect.scoped( Effect.gen(function*() { // ScopedCache itself needs a Scope — it's scoped! const cache = yield* ScopedCache.make<string, PayrollShardConn>({ capacity: 10, timeToLive: "5 minutes", lookup: (shardId) => openPayrollConn(shardId) }) // Connection is opened lazily and kept alive while the entry exists const conn = yield* ScopedCache.get(cache, "us-west-2") const rows = yield* conn.query("SELECT employee_id, gross_pay FROM payroll_run") console.log(rows) // Invalidating the shard closes its scope → conn.close runs yield* ScopedCache.invalidate(cache, "us-west-2") }))// When the outer Effect.scoped closes, any remaining shard connections are released.
Warning: If your value has no resources to release, use Cache instead. ScopedCache runs scope machinery on every entry. Reach for it only when your lookup calls Effect.acquireRelease, opens a socket, or otherwise needs cleanup on eviction.
ScopedCache.makeWith accepts the same (exit, key) => Duration policy as Cache.makeWith, and the key and failure TTL guidance applies unchanged. Three lifetime details are specific to it: ScopedCache.invalidateAll detaches every entry from the table before closing the entry scopes (concurrently), so an entry that a finalizer re-creates is kept and released later instead of being discarded unreleased; invalidateAll and owner-scope shutdown attempt every entry release and then propagate all release defects together, and a release failure discovered by expiry during a keys / values / entries scan, where no caller observes it, is logged at References.UnhandledLogLevel; and after the cache's own scope has closed, get, set, refresh, and the invalidation operations are interrupted rather than reopening anything — including a get or getOption already waiting on a lookup that finishes after the close, whose fresh entry scope is closed instead of cached. A shared lookup also survives any single caller's interruption — if every waiter leaves while the lookup is still pending, the lookup itself is interrupted and its scope closed, and missing-key lookups (including refresh) run in a daemon fiber so one caller's cancellation never corrupts the entry for the others.
Lookups are not traced under the caller's span. An entry is shared by every later caller, so a lookup does not inherit the span active when get or refresh triggered it; spans created inside the lookup become children of the span that was active when the cache was constructed, if any, and the entry's finalizers do not keep the first caller's span alive. A caller that needs the wait in its own trace wraps the get in Effect.withSpan, which times the wait without parenting the shared lookup.
When to use: the cached value holds a resource (live connection, file handle, in-process child) that must be released precisely on expiry or eviction.
Typed, data-only description of one thing to fetch from a data source. A Request<A, E> is not an effect — it is a plain object carrying the input fields a resolver needs, plus phantom types for success (A) and error (E). Used by RequestResolver and Effect.request for batching and deduplication.
Mental model. A record in a to-do list processed in bulk by a resolver. Multiple fibers each add their own request; when the resolver runs it receives the whole batch and completes each entry exactly once via entry.completeUnsafe(exit).
Fragment · Type-checked with fixture
ts
import { Request } from "effect"// Option 1: Request.Class — the idiomatic, typed constructor.// First type param = field shape, second = success type, third = error type.class GetEmployeeById extends Request.Class< { readonly id: number }, Employee, EmployeeNotFound> {}// Option 2: for tagged unions, use Request.TaggedClass.// The tag is automatically set as _tag; remaining fields come from the shape param.class GetManagerById extends Request.TaggedClass("GetManagerById")< { readonly id: number }, Manager, EmployeeNotFound> {}// Constructing requests — fields are passed to the constructor as an objectconst req = new GetEmployeeById({ id: 42 })console.log(req.id) // 42// Type utilitiestype EmployeeSuccess = Request.Success<GetEmployeeById> // Employeetype EmployeeError = Request.Error<GetEmployeeById> // EmployeeNotFound
The completion helpers are Effect-returning counterparts of entry.completeUnsafe(exit), so they drop straight into Effect.forEach inside a resolver:
Helper
Completes the entry with
Request.succeed(entry, value)
A success
Request.fail(entry, error)
A typed failure
Request.failCause(entry, cause)
A full Cause (defects, interruption)
Request.complete(entry, exit)
An Exit you already hold
Request.completeEffect(entry, effect)
Whatever effect produces — runs it, then completes with its success or typed failure
An entry can be completed once; later completions are ignored.
Requests are structural values: Equal.equals and Hash read a request's own fields, whatever order they were supplied in, so two new GetEmployeeById({ id: 42 }) values are the same key for RequestResolver.withCache. The comparison reads fields only, not the class — give requests that share a field shape and a cache a _tag (Request.TaggedClass).
When to use: building a RequestResolver. Request is the typed declaration of what each resolver call produces; it is rarely used in isolation.
Executes batches of Request values. Core job: receive an array of pending request entries, fetch data (ideally in one batch call), then call entry.completeUnsafe(Exit.succeed/fail(...)) on each entry. Pairing with Effect.request collapses concurrent N+1 queries into a single round-trip.
Mental model. Effect collects all concurrent Effect.request calls within a configurable batching window, groups them by resolver, and fires one resolver.runAll(entries) call. The resolver fans the single response out to each waiting fiber. Equivalent to DataLoader, but typed and composable.
What actually forms a batch. Batching is a property of the resolver, not of the call site — Effect.forEach and Effect.all have no batching option. Every Effect.request registered against the same resolver (and the same grouping key) before the resolver's delay effect finishes lands in one batch. The default delay is a single Effect.yieldNow, so only requests issued concurrently meet:
Call site
Batches the resolver sees for ids 1, 2, 3
Effect.forEach(ids, get) (sequential)
[1], [2], [3] — each request suspends its fiber until it is answered, so nothing else can join
Effect.forEach(ids, get, { concurrency: 2 })
[1, 2], [3] — the concurrency limit caps the batch size
RequestResolver.setDelay("10 millis") widens the window so requests from different fibers and handlers can meet, at the price of that much latency on every batch.
Self-contained source · Type-checked
ts
import { Context, Effect, Exit, Layer, Request, RequestResolver, Schema, Tracer } from "effect"// --- Domain errors --------------------------------------------------------export class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()( "EmployeeNotFound", { id: Schema.Int.check(Schema.isGreaterThan(0)) }) {}// --- Domain models --------------------------------------------------------export class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.String, managerId: Schema.Int.check(Schema.isGreaterThan(0))}) {}export class Manager extends Schema.Class<Manager>("Manager")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, departmentId: Schema.Int.check(Schema.isGreaterThan(0))}) {}// --- Request definitions --------------------------------------------------class GetEmployeeById extends Request.Class< { readonly id: number }, Employee, EmployeeNotFound> {}class GetManagerById extends Request.Class< { readonly id: number }, Manager, EmployeeNotFound> {}// --- Hris service with batched resolvers ----------------------------------// Building an org chart fires one GetEmployeeById and one GetManagerById per// node. Without batching that's 2N HRIS calls. With batching it's 2.export class Hris extends Context.Service<Hris, { getEmployeeById(id: number): Effect.Effect<Employee, EmployeeNotFound> getManagerById(id: number): Effect.Effect<Manager, EmployeeNotFound>}>()("app/Hris") { static readonly layer = Layer.effect( Hris, Effect.gen(function*() { // Simulate HRIS data store const employees = new Map<number, Employee>([ [1, new Employee({ id: 1, name: "Ada Lovelace", level: "L5", managerId: 10 })], [2, new Employee({ id: 2, name: "Alan Turing", level: "L4", managerId: 10 })], [3, new Employee({ id: 3, name: "Grace Hopper", level: "L4", managerId: 11 })] ]) const managers = new Map<number, Manager>([ [10, new Manager({ id: 10, name: "Charles Babbage", departmentId: 1 })], [11, new Manager({ id: 11, name: "Emmy Noether", departmentId: 2 })] ]) // One batch call satisfies every fiber waiting for an Employee. const employeeResolver = yield* RequestResolver.make<GetEmployeeById>( Effect.fn(function*(entries) { for (const entry of entries) { const emp = employees.get(entry.request.id) entry.completeUnsafe( emp ? Exit.succeed(emp) : Exit.fail(new EmployeeNotFound({ id: entry.request.id })) ) } }) ).pipe( RequestResolver.setDelay("10 millis"), RequestResolver.withSpan("Hris.getEmployeeById.resolver"), RequestResolver.withCache({ capacity: 2048 }) ) // Separate resolver for Manager lookups — same batching pattern. const managerResolver = RequestResolver.make<GetManagerById>( Effect.fn(function*(entries) { for (const entry of entries) { const mgr = managers.get(entry.request.id) entry.completeUnsafe( mgr ? Exit.succeed(mgr) : Exit.fail(new EmployeeNotFound({ id: entry.request.id })) ) } }) ).pipe( RequestResolver.setDelay("10 millis"), RequestResolver.withSpan("Hris.getManagerById.resolver") ) const getEmployeeById = (id: number) => Effect.request(new GetEmployeeById({ id }), employeeResolver).pipe( Effect.withSpan("Hris.getEmployeeById", { attributes: { employeeId: id } }) ) const getManagerById = (id: number) => Effect.request(new GetManagerById({ id }), managerResolver).pipe( Effect.withSpan("Hris.getManagerById", { attributes: { managerId: id } }) ) return { getEmployeeById, getManagerById } as const }) )}// --- Build an org chart — all lookups collapsed into two batch calls ------export const buildOrgChart = Effect.gen(function*() { const { getEmployeeById, getManagerById } = yield* Hris const employeeIds = [1, 2, 3, 1, 2] // duplicates deduplicated by withCache // All five GetEmployeeById requests arrive concurrently → // resolver sees at most [1, 2, 3] after dedup. const employees = yield* Effect.forEach(employeeIds, getEmployeeById, { concurrency: "unbounded" }) // Now fetch each unique manager in one batch. const managerIds = [...new Set(employees.map((e) => e.managerId))] yield* Effect.forEach(managerIds, getManagerById, { concurrency: "unbounded" })})
Note: A resolver cannot require services. RequestResolver<A> has no requirements parameter and runAll is typed with R = never, so a yield* SomeService inside RequestResolver.make is a type error. Build the resolver where the services are in scope — inside Layer.effect, as Hris.layer does, closing over the client it needs — and expose only query functions. Effect.request also accepts an Effect<RequestResolver> as its second argument and propagates that effect's errors and requirements to the caller. Per-caller context stays available as entry.context.
A resolver is a small protocol, and part of it is enforced at runtime:
Settle every entry you receive, exactly once — with entry.completeUnsafe(exit) or the Request.* helpers. If runAll succeeds and leaves an entry untouched, that caller dies with the defect Effect.request: RequestResolver did not complete request. The classic trigger is a batch endpoint that silently omits unknown ids.
Join results to entries by identity, never by position. Index the rows by id once, then iterate the entries. Backend row order is not a contract, and positional pairing hands callers each other's data without any error.
Decide what a missing row means — a typed failure or a domain "empty" success — and complete the entry with it. Skipping is not a decision (see rule 1).
Deduplicate the backend call yourself. Base batching collects entries; it does not collapse equal requests, so ids L4, L5, L4 reach the resolver as three entries. Send the distinct ids to the backend and still complete all three entries. Only withCache / asCache collapse equal requests before they reach the resolver.
Let a failed batch fail. When runAll itself fails with Request.Error<A>, every still-pending entry in that batch receives the failure; there is no need to fail entries one by one. Fail individual entries only when the batch call succeeded and that row is the problem.
Fragment · Type-checked
ts
import { Effect, Request, RequestResolver, Schema } from "effect"class CompSummaryUnavailable extends Schema.TaggedError<CompSummaryUnavailable>()( "CompSummaryUnavailable", { employeeId: Schema.String }) {}interface CompSummary { readonly employeeId: string readonly baseSalary: number}class GetCompSummary extends Request.Class< { readonly tenantId: string; readonly employeeId: string }, CompSummary, CompSummaryUnavailable> {}// One payroll API call per tenant; rows come back in any order and may omit unknown ids.declare const fetchCompSummaries: ( tenantId: string, employeeIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<CompSummary>, CompSummaryUnavailable>export const CompSummaryResolver = RequestResolver.makeGrouped<GetCompSummary, string>({ // The grouping key decides what may share a round trip: one batch per tenant. key: (entry) => entry.request.tenantId, resolver: Effect.fn("CompSummaryResolver.runAll")(function*(entries, tenantId) { // Rule 4: distinct ids only. const employeeIds = [...new Set(entries.map((entry) => entry.request.employeeId))] // Rule 5: if this fails, every pending entry of the batch fails with the same error. const rows = yield* fetchCompSummaries(tenantId, employeeIds) // Rule 2: join by identity. const byId = new Map(rows.map((row) => [row.employeeId, row])) // Rules 1 and 3: iterate ENTRIES (duplicates included) and settle each one. yield* Effect.forEach(entries, (entry) => { const row = byId.get(entry.request.employeeId) return row === undefined ? Request.fail(entry, new CompSummaryUnavailable({ employeeId: entry.request.employeeId })) : Request.succeed(entry, row) }, { discard: true }) })})
Batched resolver: runAll(entries, key) answers a non-empty batch. Default window: one Effect.yieldNow.
RequestResolver.makeGrouped({ key, resolver })
Like make, with a grouping key computed from each entry: key: (entry) => K, resolver: (entries, key) => …. The key decides what may share a round trip — a constant key puts every request in one batch, while keying by tenant, shard, or data source batches within each group and never mixes requests bound for different backends. Keys are compared with Equal in the pending batch map and released as soon as their batch stops pending, including after interruption; the resolver does not retain every historical key. RequestResolver.grouped(f) adds the same grouping to an existing resolver.
RequestResolver.fromEffect(f)
No batch endpoint: f(entry) runs once per entry, concurrently, and its Exit completes that entry. Each entry runs with its own caller's context, never another caller's services. You still get one call site for caching, tracing, and delay.
One handler per request _tag; each returns an iterable of results in the same order as its entries (arrays, iterators, and generators all work). A handler's typed error, defect, or interruption completes every entry of that tag with it. This is the one positional API — prefer make when the backend does not guarantee order.
RequestResolver.fromFunctionBatched(f)
Quick path: map entries to successes with a pure function; no explicit completions needed. Also positional.
RequestResolver.setDelay(duration)
Wait before draining — more entries collected, higher latency on first call. setDelayEffect takes an arbitrary effect.
RequestResolver.batchN(n)
Limit maximum batch size to n; a full batch runs immediately instead of waiting out the delay.
RequestResolver.withSpan(name, options?)
Wrap each batch in an OTel span (attribute batchSize) and add each distinct requesting parent span as a span link. options may be a function of the batch; every span option it returns is applied.
Put a bounded in-memory cache in front, keyed by request equality: equal requests in one batch collapse to one entry, and completed results are replayed. strategy is "lru" (default) or "fifo". Entries never expire by time and failures are cached like successes (interrupted results are not), so a transient failure stays until it is evicted by capacity.
Convert the resolver into a Cache (requests are the keys). Use this instead of withCache when you need a TTL — timeToLive: (exit, request) => Duration, so the failure policy applies — or invalidate / refresh.
Back the resolver with a Persistence store (cross-restart caching). With staleWhileRevalidate, a stale entry is served while it refreshes; only refresh results are persisted, a whole-batch refresh failure replaces the stale value, and a refresh that completes no entries leaves the original expiry unchanged.
RequestResolver.race(a, b)
Run two resolvers concurrently and use whichever responds first.
RequestResolver.around(before, after)
Bracket each batch run with setup/teardown effects.
Tip: Request equality is structural. Request.Class and Request.TaggedClass instances with equal fields are equal, and so are plain objects built with Request.of / Request.tagged, because Equal.equals compares plain objects structurally. Equality only matters to withCache and asCache, though (persisted keys its store by PrimaryKey) — a resolver without one of them receives every entry, duplicates included. The same key normalization rules apply: { id: "e-42" } and { id: "E-42" } are different requests.
Correctness guarantees.withCache never retains an entry for a pending request whose caller was cancelled, and it keeps the completed result when the losing side of RequestResolver.race is interrupted, so the next equal lookup does not hit the backend again. persisted preserves completed results and propagates resolver failures. fromEffectTagged preserves a handler's typed errors, defects, and interrupts, and consumes its results as an iterable.
Note: Inside the resolver, entry.context holds the Context from the issuing fiber. RequestResolver.withSpan collects the distinct Tracer.ParentSpan values and records them as links on the batch span, rather than making multiple caller spans its children. Custom resolvers can inspect the same context with Context.getOption(entry.context, Tracer.ParentSpan).
Give the fake backend the three behaviors a real one has — shuffled rows, an omitted id, a duplicated request — and assert the four properties of the resolver obligations: one backend call, distinct ids, results in caller order, every entry settled.
Self-contained source · Type-checked
ts
import { assert, describe, it } from "@effect/vitest"import { Effect, Exit, Request, RequestResolver } from "effect"class GetBandMidpoint extends Request.Class<{ readonly level: string }, number, "UnknownLevel"> {}describe("band midpoint resolver", () => { it.effect("one call, distinct ids, caller order, every entry settled", () => Effect.gen(function*() { const backendCalls: Array<ReadonlyArray<string>> = [] const midpoints = new Map([["L5", 185_000], ["L4", 140_000]]) // reversed on purpose; no "L9" const resolver = RequestResolver.make<GetBandMidpoint>((entries) => Effect.gen(function*() { const levels = [...new Set(entries.map((entry) => entry.request.level))] backendCalls.push(levels) const rows = [...midpoints].filter(([level]) => levels.includes(level)) const byLevel = new Map(rows) yield* Effect.forEach(entries, (entry) => { const midpoint = byLevel.get(entry.request.level) return midpoint === undefined ? Request.fail(entry, "UnknownLevel" as const) : Request.succeed(entry, midpoint) }, { discard: true }) }) ) const results = yield* Effect.forEach( ["L4", "L5", "L4", "L9"], (level) => Effect.exit(Effect.request(new GetBandMidpoint({ level }), resolver)), { concurrency: "unbounded" } ) assert.deepStrictEqual(backendCalls, [["L4", "L5", "L9"]]) // one call, duplicates removed assert.deepStrictEqual(results, [ Exit.succeed(140_000), Exit.succeed(185_000), Exit.succeed(140_000), // the duplicate entry was settled too Exit.fail("UnknownLevel" as const) // a typed failure, not the "did not complete request" defect ]) }))})
No clock is involved with the default Effect.yieldNow window. A resolver built with setDelay sleeps on the Clock, so under it.effect fork the callers, TestClock.adjust past the delay, then join. A delay that completes synchronously, such as setDelay(0) under TestClock, is safe: the request is registered before the delay starts.
When to use: service methods that individual fibers call independently but which support batch APIs underneath (lookups, permission checks, external API calls). The N+1 problem on deeply nested data is the canonical trigger.
Tiny protocol: define [PrimaryKey.symbol](): string on a class or object to advertise a stable string identifier. Effect's persistence layer uses this key to store and retrieve serialized exits.
Mental model. Natural key in a database: a deterministic, human-readable string uniquely identifying a particular request or entity. Anything implementing PrimaryKey can be used as a key in a Persistable store without a separate keyspace function.
Fragment · Type-checked with fixture
ts
import { PrimaryKey, Request } from "effect"// Adding PrimaryKey to a request lets the persistence layer// store the result under a stable key derived from the employee ID.class GetEmployeeById extends Request.TaggedClass("GetEmployeeById")< { readonly id: number }, Employee, EmployeeNotFound > implements PrimaryKey.PrimaryKey{ [PrimaryKey.symbol](): string { return `employee:${this.id}` }}const req = new GetEmployeeById({ id: 42 })console.log(PrimaryKey.value(req)) // "employee:42"console.log(PrimaryKey.isPrimaryKey(req)) // true
When to use: building a Persistable request or any custom type that needs a stable string key for caching, logging, or deduplication across process restarts.
Effect 4 ships three stacked layers: a fully typed HTTP client (request as value, Schema-decoded response, built-in retries), a low-level server (router as Layer, middleware as function), and HttpApi — a schema-first API description that derives a server, a typed client, and OpenAPI/Swagger/Scalar docs from one definition, with the contract checked end-to-end at compile time.
Four cooperating modules: HttpClient is the service you acquire and decorate with policy; HttpClientRequest is an immutable request built with pipes; HttpClientResponse decodes a raw response through a Schema; HttpClientError is the tagged error family for transport/status/body failures. Composing a schema decoder also adds SchemaError. Idiomatic use: wrap the union in a domain service so callers never touch headers.
A service (HttpClient.HttpClient) representing the ability to execute an HTTP request. Acquire from context, decorate with policy, execute requests. Decorators (mapRequest, filterStatusOk, retryTransient, followRedirects, withRateLimiter) return a new client with that behavior baked in — configure once, every call inherits it.
Mental model. Middleware-wrapped fetch in the Effect world. The base implementation comes from a Layer (FetchHttpClient.layer, NodeHttpClient, or BunHttpClient) — never constructed directly. Convenience methods client.get/.post/.execute return Effect<HttpClientResponse, HttpClientError>.
Self-contained source · Type-checked
ts
import { Context, Effect, flow, Layer, Schedule, Schema } from "effect"import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse} from "effect/http"// The decoded shape we want callers to receive — an employee record from the HRIS.class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), baseSalary: Schema.Finite}) {}// One wrapper error so callers see a single failure type, not the raw zoo.class HrisError extends Schema.TaggedError<HrisError>()( "HrisError", { cause: Schema.Defect() }) {}class Hris extends Context.Service<Hris, { readonly allEmployees: Effect.Effect<ReadonlyArray<Employee>, HrisError> getEmployee(id: number): Effect.Effect<Employee, HrisError> recordRaise(raise: Omit<Employee, "id">): Effect.Effect<Employee, HrisError>}>()("comp/Hris") { static readonly layer = Layer.effect( Hris, Effect.gen(function*() { // Acquire the base client and decorate it with policy, ONCE. const client = (yield* HttpClient.HttpClient).pipe( HttpClient.mapRequest(flow( HttpClientRequest.prependUrl("https://hris.acme.internal"), HttpClientRequest.acceptJson )), HttpClient.filterStatusOk, // fail unless the status is 2xx HttpClient.retryTransient({ // network/timeouts + 408/429/500/502/503/504 schedule: Schedule.exponential(100), times: 3 }) ) const allEmployees = client.get("/employees").pipe( Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Array(Employee))), Effect.mapError((cause) => new HrisError({ cause })), Effect.withSpan("Hris.allEmployees") ) const getEmployee = Effect.fn("Hris.getEmployee")(function*(id: number) { yield* Effect.annotateCurrentSpan({ id }) return yield* client.get(`/employees/${id}`, { urlParams: { format: "json" } }).pipe( Effect.flatMap(HttpClientResponse.schemaBodyJson(Employee)), Effect.mapError((cause) => new HrisError({ cause })) ) }) const recordRaise = Effect.fn("Hris.recordRaise")(function*( raise: Omit<Employee, "id"> ) { return yield* HttpClientRequest.post("/raises").pipe( HttpClientRequest.bodyJsonUnsafe(raise), client.execute, Effect.flatMap(HttpClientResponse.schemaBodyJson(Employee)), Effect.mapError((cause) => new HrisError({ cause })) ) }) return Hris.of({ allEmployees, getEmployee, recordRaise }) }) ).pipe( // Choose the implementation here. Swap to NodeHttpClient/BunHttpClient freely. Layer.provide(FetchHttpClient.layer) )}
HttpClient.get (runs immediately) and HttpClientRequest.get (builds a value) are two paths to the same result — the request-value path gives more control. Every decorator is a pure transform, so you can derive multiple specialized clients from one base. Requests carry a span, so retries and timings appear in tracing automatically.
Decorator
What it does
mapRequest / mapRequestEffect
Transform every outgoing request (prepend base URL, add auth, set headers).
filterStatusOk / filterStatus
Turn non-2xx (or a custom predicate) into a StatusCodeError.
retry / retryTransient
Retry on a Schedule; retryTransient covers transport/timeouts and 408, 429, 500, 502, 503, 504.
followRedirects
Chase 3xx responses up to a hop limit.
timeout
Fail a request that has no response within a duration, as an HttpClientError the retry decorators treat as transient; see below.
withRateLimiter
Throttle outgoing requests through a RateLimiter — handy to stay under API quotas.
tap / tapRequest / tapError
Observe requests/responses/errors without changing them.
catch / catchTag / catchTags
Recover inside the client: both overloads of catch require the handler to produce another HttpClientResponse. To recover to any other value, use Effect.catch on the result of client.execute(request).
transformResponse
Wrap every response Effect, for policies no dedicated decorator covers.
withCookiesRef
Maintain a cookie jar in a Ref<ReadonlyArray<Cookie>>: response cookies are merged per response URL, and each request gets the cookies matching the host, path, and scheme of its final URL — after later prependUrl transforms or an HttpApiClientbaseUrl, and again on every redirect hop when followRedirects is applied after it.
withScope
Tie every request the client sends to the caller's Scope, so a response body or socket stays open until that scope closes; see below.
withCircuitBreaker
Stop calling an origin that keeps failing; see below. Experimental.
HttpClient.isTransientError(error) and HttpClient.isTransientResponse(response) are the predicates retryTransient uses (timeouts, TransportError, and the transient statuses), exported for custom retry policies and circuit classifiers.
Migration:withCookiesRef takes Ref<ReadonlyArray<Cookies.Cookie>> instead of Ref<Cookies>. Seed it with Cookies.mergeIntoArray, or with cookies that set a domain; a host-less cookie in the seed is never sent.
withRateLimiter can learn limits and reset delays from response headers and automatically retry HTTP 429 responses. Those 429 retries are unlimited by default: set times to a finite production budget, or times: 0 to return/fail on the first 429. responseHeaders remaps non-standard limit/remaining/reset/retry header names. disableResponseInspection disables adaptive updates and header delays, but deliberately does not disable the 429 retry loop.
followRedirects defaults to at most ten hops and follows Fetch-style method changes: POST becomes GET for 301/302, and non-GET/HEAD becomes GET for 303. On a cross-origin redirect it strips authorization, proxy-authorization, and cookie before issuing the next request, preventing credentials from leaking to the new origin. When the hop limit is reached it returns the last 3xx response rather than failing; an invalid Location also returns the redirect response unchanged. The next request uses the resolved Location exactly as sent (its query is not re-encoded), a switch to GET also drops the body headers (Content-Encoding, Content-Language, Content-Location), and each discarded redirect body is released. A failure in request preprocessing (a failing mapRequestEffect) does not bypass response-level recovery such as HttpClient.catch when redirects are enabled.
Warning:With FetchHttpClient the platform fetch follows redirects before Effect ever sees them (probed on Node 26: a 302 arrives as the final 200, and response.url reports the final URL). HttpClient.followRedirects — and any per-hop validation you hang on it — only takes over when the underlying fetch is told not to: provide FetchHttpClient.RequestInit with { redirect: "manual" }. In a browser a manual redirect is an opaque response, so hop-by-hop control is a server-side technique.
retryTransient honors a valid Retry-After on a response or response-bearing error: integer seconds or an HTTP date, measured against the Effect Clock. Its delay is the maximum of the schedule delay and the server's delay, not an additional sleep; malformed headers (negative, fractional, or exponent values such as 1.5 or 1e3) fall back to the schedule and past dates add no wait. Headers.parseRetryAfter / Headers.retryAfterDelay expose the same parsing. The header does not make a non-transient response retryable or override the schedule/count limit. withRateLimiter also interprets HTTP dates as dates, not seconds.
Every call gets a finite budget. No client has a timeout until you add one. HttpClient.timeout("10 seconds") bounds each attempt when placed beforeretryTransient and the whole retry loop, backoff included, when placed after it. An expired request is interrupted (which aborts the transport while it still waits for headers) and fails with an HttpClientError whose reason is a TransportError with a Cause.TimeoutError cause, so the client keeps the plain HttpClient type and retryTransient retries it. HttpClient.transformResponse(Effect.timeout(...)) bounds the same span but adds a bare Cause.TimeoutError to the client's error channel instead.
The budget ends when the response arrives. The timer starts after request preprocessing and stops when the wrapped client returns a response — for a plain client, when the headers arrive. Response middleware applied beforetimeout (a tap, a retry) runs inside the budget, including any body it reads; a body read by the caller (response.json, schemaBodyJson, response.stream) is not covered, so give a large or streamed body its own Effect.timeout. Under withScope, a timeout that fires after the headers have arrived does not abort the connection; it stays open until the scope closes.
Interruption cancels the request, not just the wait. The client hands the platform an AbortSignal and aborts it when the calling fiber is interrupted — by a timeout, a lost race, or a closed scope (probed: the remote server observes the disconnect). Wrapping a non-Effect SDK yourself? Forward the signal Effect.tryPromise gives you; see the request-cancellation recipe.
retryTransient does not look at the method. It replays a POST as readily as a GET. After a timeout or a dropped connection the first attempt may already have been applied, so retry only requests that are replay-safe: reads, or mutations protected by an idempotency key the server honors. Derive two clients from one base instead of retrying everything.
Retry budgets are finite (times, or a bounded Schedule), and withRateLimiter's 429 loop needs its own times as noted above.
Self-contained source · Type-checked
ts
import { Effect, flow, Schedule } from "effect"import { HttpClient, HttpClientRequest } from "effect/http"export const makeHrisClients = Effect.gen(function*() { const base = (yield* HttpClient.HttpClient).pipe( HttpClient.mapRequest(flow( HttpClientRequest.prependUrl("https://hris.acme.internal"), HttpClientRequest.acceptJson )), HttpClient.timeout("5 seconds"), // per attempt HttpClient.filterStatusOk ) // Reads are replay-safe: retry transient faults inside a total budget. const reads = base.pipe( HttpClient.retryTransient({ schedule: Schedule.exponential("100 millis"), times: 3 }), HttpClient.timeout("20 seconds") // whole call, backoff included ) // Writes are sent once unless the caller supplies the key the HRIS deduplicates on. const writeOnce = base const idempotentWrite = (idempotencyKey: string) => base.pipe( HttpClient.mapRequest(HttpClientRequest.setHeader("idempotency-key", idempotencyKey)), HttpClient.retryTransient({ schedule: Schedule.exponential("200 millis"), times: 2 }) ) return { reads, writeOnce, idempotentWrite } as const})
Without withScope, a request is aborted when its caller is interrupted before the response arrives or while it reads the body, and a response nobody starts reading is aborted once it is garbage-collected (after five seconds on runtimes without FinalizationRegistry). HttpClient.withScope(client) adds Scope to the client's requirements and hands ownership to that scope instead: use it when a response body, an upgraded socket, or a HttpClientResponse.toWeb hand-off must stay open after the response effect has completed, and close it by closing the scope.
Ownership follows the execution, not the request value. Every request the transport sends while the scoped client executes belongs to the scope — each redirect hop, each retry attempt, each request rewritten by middleware — wherever withScope sits relative to followRedirects, withCookiesRef, or retryTransient. Running the same request value, or the same response effect, concurrently under different scopes gives each execution its own owner.
Closing the scope aborts. Pending requests and open response bodies are aborted when the scope closes, and a request sent after the scope has closed is aborted before the transport starts it. Interrupting a request before its response arrives still aborts it; once the response has been returned, its body is released only by the scope.
Helper requests are captured too. A request that middleware sends with another client while this one executes — a token fetch inside mapRequestEffect, say — joins the same scope; with nested withScope, the innermost scope owns it. To give such a helper its own lifetime, apply withScope to the helper client and run its request in its own Effect.scoped.
Fragment · Type-checked
ts
import { Effect, Stream } from "effect"import { HttpClient } from "effect/http"declare const appendToFile: (chunk: Uint8Array) => Effect.Effect<void>// The connection stays open while the body streams, and is aborted when the scope closes —// on success, failure, or interruption.export const downloadExport = Effect.scoped( Effect.gen(function*() { const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk, HttpClient.withScope) const response = yield* client.get("https://hris.acme.internal/exports/payroll.csv") yield* Stream.runForEach(response.stream, appendToFile) }))
Migration:withScope used to track only the request value passed to it, so redirect hops, retries, and requests rewritten after it could escape the scope. It now owns every request sent during the execution, including requests other clients send from inside its middleware; give those their own scoped client if they must outlive or predate the caller's scope.
HttpClient.withCircuitBreaker({ breaker, key?, classify? }) guards each request with a CircuitBreaker and adds CircuitBreakerError to the client's error channel when a circuit rejects a call. Circuits are keyed by request origin unless key says otherwise. The default HttpClient.circuitBreakerClassifier counts transport failures, timeouts, and 408/500/502/503/504 as failures (carrying any Retry-After hint), ignores 429, and counts every other response as success; supply classify to treat, for example, a 200 with an error body as a failure. The same status rules apply whether a status arrives as a response or as a StatusCodeError from filterStatusOk; other errors are ignored. CircuitBreaker.make needs a CircuitBreakerStore (such as CircuitBreaker.layerStoreMemory()) and a Scope. Both APIs are experimental.
A URL that comes from a user — a webhook target, an "import payroll file from URL" field, an avatar link — turns your server into a proxy for whoever typed it (server-side request forgery). Treat the destination as untrusted input:
Allow-list scheme and port (https: only, 443 or a short list) after parsing with Url.fromString; reject userinfo (user:pass@host).
Resolve the host and reject non-public addresses: loopback, private ranges, link-local (which includes the 169.254.169.254 cloud metadata endpoint), unique-local IPv6, IPv4-mapped IPv6, multicast, and the unspecified address. effect/net has the predicates.
Re-validate at every hop. A public URL can redirect to an internal one, so disable platform redirects (redirect: "manual", see the warning above) and run the same check on each location — or do not follow redirects at all. Re-check after DNS resolution too: connect to the address you vetted, or a second lookup can answer differently.
Bound everything else: a short timeout, a response-size cap, no credentials or internal headers on the outgoing request, and a response the caller cannot read verbatim if they should not learn what an internal address answers.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { NetAddress } from "effect/net"export class ForbiddenDestination extends Schema.TaggedError<ForbiddenDestination>()( "ForbiddenDestination", { reason: Schema.String }) {}const isPublicAddress = (ip: NetAddress.IpAddress): boolean => !NetAddress.isUnspecified(ip) && !NetAddress.isLoopback(ip) && !NetAddress.isLinkLocal(ip) && // 169.254.0.0/16 (cloud metadata) and fe80::/10 !NetAddress.isMulticast(ip) && (NetAddress.isIpv4Address(ip) ? !NetAddress.isPrivate(ip) // 10/8, 172.16/12, 192.168/16 : !NetAddress.isUniqueLocal(ip) && !NetAddress.isIpv4Mapped(ip))// `resolvedAddresses` comes from your resolver capability (for example `dns.lookup(host, { all: true })`).export const assertPublicDestination = Effect.fn("assertPublicDestination")(function*( url: URL, resolvedAddresses: ReadonlyArray<string>) { if (url.protocol !== "https:" || url.username !== "" || url.password !== "") { return yield* new ForbiddenDestination({ reason: "scheme or credentials not allowed" }) } if (resolvedAddresses.length === 0) { return yield* new ForbiddenDestination({ reason: "host did not resolve" }) } for (const text of resolvedAddresses) { const ip = yield* Effect.fromResult(NetAddress.ipFromString(text)).pipe( Effect.mapError(() => new ForbiddenDestination({ reason: "unparseable address" })) ) if (!isPublicAddress(ip)) { return yield* new ForbiddenDestination({ reason: "non-public address" }) } } return url})
Reach for it when you call any HTTP service and want retries, decoding, tracing, and a clean domain API instead of raw fetch.
The fetch-backed HttpClient implementation. Provide FetchHttpClient.layer anywhere a client is needed. Works in browsers, serverless, Node, Bun, and Deno. Swap the underlying fetch via FetchHttpClient.Fetch (tests or custom agent); set default RequestInit options via FetchHttpClient.RequestInit.
Self-contained source · Type-checked
ts
import { Effect, Layer } from "effect"import { FetchHttpClient } from "effect/http"// Force credentials: "include" on every fetch by layering RequestInit —// so the HRIS session cookie rides along on each call.const ClientLayer = FetchHttpClient.layer.pipe( Layer.provide(Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" })))
Per-request method, headers, body, and the abort signal always come from the client and override the same fields in RequestInit; everything else (credentials, cache, redirect, integrity) is yours to set. A bodyStream request is sent as a Web ReadableStream with duplex: "half", and any content-length header is dropped, because fetch computes framing itself. On a runtime whose fetch cannot stream request bodies, a stream body fails with an EncodeError before anything is sent, instead of silently uploading [object ReadableStream]; provide FetchHttpClient.StreamBodyFallback set to "buffer" to collect the stream in memory and send it whole (unsafe for large or unbounded uploads). Support is detected once, on the first stream body, using the global Request. CORS, cookie, redirect, and streaming-upload behavior is otherwise the runtime's, not Effect's, so test uploads on the host you deploy to.
HttpClientResponse.toWeb(response) returns the original Web Response of a fetch-backed response as Some (and None for other backends), so its body can be handed to a platform API such as Cloudflare R2 without copying.
Reach for it when you want the portable, zero-dependency client — which is most of the time. Use NodeHttpClient/BunHttpClient only when you need native streaming or connection-pool control.
An immutable request description built with combinators. Start from a verb (get, post, put, patch, delete, head, options, query) and pipe on URL pieces, query params, headers, auth, and a body. Nothing executes until a client runs it.
HttpClientRequest.query(url) builds an HTTP QUERY request: a safe, idempotent read that carries its query in the body, so the search above could be HttpClientRequest.query("/employees/search") with the same body builder. Clients have a matching client.query(url, options) method and HttpClient.query accessor. Many servers, proxies, and caches do not route QUERY yet, so confirm support on the whole path before switching from POST.
Mental model. A value, not an action — stash, clone, and pass around. Factor out reusable request fragments and apply them per-call or, via HttpClient.mapRequest, to a whole client.
Self-contained source · Type-checked
ts
import { Effect, Redacted } from "effect"import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"const program = Effect.gen(function*() { const client = yield* HttpClient.HttpClient // Search the HRIS for employees in a given comp band. const request = HttpClientRequest.post("/employees/search").pipe( HttpClientRequest.prependUrl("https://hris.acme.internal"), HttpClientRequest.setUrlParams({ page: 1, limit: 20 }), // numbers are coerced HttpClientRequest.bearerToken(Redacted.make("hris-service-token")), HttpClientRequest.acceptJson, HttpClientRequest.bodyJsonUnsafe({ level: 5, departmentId: "ENG" }) ) return yield* client.execute(request).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk) )})
Tip:Body builders.bodyJsonUnsafe (sync, throws on circular data) and bodyJson (effectful, safe) for JSON; bodyText, bodyUint8Array, bodyUrlParams, bodyFormData/bodyFormDataRecord for the rest; bodyStream for streaming uploads; bodyFile to send a file from disk. For type-checked request bodies, schemaBodyJson(MySchema) encodes through a Schema before sending.
Use updateHeaders(f) for a whole-map immutable transform and removeHeader(name) for one field. Replacing a request body also synchronizes its content-type and content-length: metadata supplied by the new body replaces stale values, and an empty or FormData body removes both so the platform can derive the right headers.
compressBody("gzip" | "deflate", { minSize? }) is an effectful request transform using global CompressionStream. The default threshold is 1024 known bytes; unknown-length streams are always compressed. It preserves content type, updates byte-body content length, and removes stream content length. Empty, FormData, raw, below-threshold, and already encoded bodies (even identity) are unchanged. Byte-compression failures are defects, not a new typed error channel; stream failures surface while sending.
For client-wide compression use HttpClient.mapRequestEffect(HttpClientRequest.compressBody("gzip")). Retry preprocessing recompresses each attempt: compress a large replayable body once before execute instead. Compression does not make a one-shot stream replayable. Fetch streaming uploads still need runtime support for duplex: "half"; Safari/Firefox support must not be assumed.
NodeHttpClient.makeDispatcherOptions / layerDispatcherOptions accept typed Undici agent options: connect: { socketPath } for Unix sockets (or Windows named pipes), and connect: { ca, cert, key, servername, rejectUnauthorized } for TLS/mTLS. The scoped dispatcher is destroyed on release. URL origin still supplies the Host header/path for Unix connections. BunHttpClient.layerOptions and DenoHttpClient.layerOptions give the same typed Unix-socket and TLS settings through each runtime's native fetch options. NodeHttpClient.layerNodeHttp encodes FormData bodies without loading undici. This is native-transport configuration, not portable Fetch behavior. Per-request Undici timeouts override agent header/body timeouts; use Effect.timeout for application budgets. Never disable certificate verification as a routine fix for a connection error.
Reach for it when a request needs more than a URL, or when you want a reusable request transform.
Typed wrapper around a raw response, plus decoders. schemaBodyJson(schema) reads the body, parses JSON, and validates against a Schema in one effectful step. Transport/body-read/JSON failures are HttpClientError; a value that parses as JSON but violates the schema is SchemaError. schemaJson (decode status + headers + body together) has the same union. Also: filterStatusOk/filterStatus, matchStatus (branch on status code), and stream for incremental consumption.
response.url is the resolved request URL including query parameters and excluding the hash; after redirects it is the final URL, and it is an empty string when the platform cannot tell. Compare its origin with the one you asked for when redirects are allowed; use UrlParams.redactUrl(response.url) before logging it rather than leaking signed query parameters or credentials (URL redaction).
Every decoder takes parse options as a second argument — schemaBodyJson(schema, options), and schemaJson and schemaNoBody honor them too — so { onExcessProperty: "error" } makes an unexpected upstream field a SchemaError instead of a silent drop, and { errors: "all" } reports every issue. The JSON decoders also accept reviver, passed to JSON.parse, for upstreams that need one (for example, reading large integers from the source text).
Mental model. A response is status, headers, and an unread body. Decoders bridge to your domain type — decode failures become typed errors, so a malformed payload can't slip through as any.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"const Employee = Schema.Struct({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String})const getEmployee = (id: number) => Effect.gen(function*() { const client = yield* HttpClient.HttpClient const response = yield* client.get(`/employees/${id}`) // Branch on the status code, decoding each case differently. return yield* HttpClientResponse.matchStatus(response, { 200: HttpClientResponse.schemaBodyJson(Employee), 404: () => Effect.succeed(null), // not on the HRIS roster orElse: (res) => Effect.fail(new HttpClientError.StatusCodeError({ request: res.request, response: res, description: "Unexpected HRIS response" })) }) })
Reach for it when you need decoded, validated data or status-aware branching from a response.
import { Effect } from "effect"import { HttpClient } from "effect/http"const safe = Effect.gen(function*() { // filterStatusOk transforms the CLIENT (adding HttpClientError to its channel), // so apply it to the client, then make the request. const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk) return yield* client.get("https://hris.acme.internal/employees/42")}).pipe( // v4 wraps failures in a single HttpClientError; discriminate on reason._tag. Effect.catchTag("HttpClientError", (e) => e.reason._tag === "StatusCodeError" ? Effect.logWarning(`HRIS HTTP ${e.reason.response.status}`) : Effect.logError("HRIS unreachable", e)))
HttpClient.retryTransient covers transport/timeouts plus statuses 408, 429, 500, 502, 503, and 504 — these are rarely caught by hand solely to implement retry.
An HttpClientError is safe to log: its message and toJSON (and inspection) show the request as its method and redacted URL and the response as its status, never request headers, query values, or bodies. The full request and response remain available as properties, so do not serialize those yourself into logs or client-facing errors.
The URL is redacted with the union of the UrlParams.CurrentRedactedNames in effect where the request executed, where the error was created, and where it is rendered. Names provided around a call therefore still apply when the error is logged later by an unrelated fiber, such as a span exporter or a top-level error reporter, and a body-decoding error created from the response carries them too; a fiber with a shorter list can add redaction but never remove it.
Keep them distinct all the way to the wrapper error; each one calls for a different response.
Class
Appears as
What it means
Policy
Transport
HttpClientError with reason._tag"TransportError" (also "InvalidUrlError", "EncodeError" before anything is sent)
no usable response: DNS, connect, reset, abort
retry if the request is replay-safe; otherwise surface "outcome unknown"
Status
reason._tag === "StatusCodeError" — only when a filterStatus* decorator is applied
the peer answered, and said no
branch on reason.response.status; most 4xx are permanent, 408/429/5xx may be transient
Decode
reason._tag"DecodeError" / "EmptyBodyError" (the body could not be read or parsed), or a separate SchemaError (it parsed but has the wrong shape)
contract drift or a wrong assumption
never retry; alert, and keep the issue path out of user-facing text
Check the status before decoding the success schema. Without filterStatusOk, a 404 whose body is { "error": "not found" } is fed to schemaBodyJson(Employee) and reported as a schema failure — the one class that looks like your bug instead of the peer's answer. Filter first (on the client, or with HttpClientResponse.filterStatusOk per response), or branch with matchStatus and give each status its own decoder. When you do read an error body, bound it and decode it with its own schema; never echo an upstream error payload to your caller.
Reach for it when you need to distinguish network failures, 404s, and Schema mismatches and handle each differently.
Mental shift: a router is a Layer, a handler is an Effect, and middleware is a function from one app-effect to another. Build routes as Layers, merge them, serve with a platform-specific server Layer. Most production apps use the separate HttpApi topic; this layer is right for webhooks, health checks, file exports, and anything without a schema contract.
The mutable radix-tree engine under HttpRouter. make<A>() creates a router; on(methods, path, handler) and all(path, handler) register values; find(method, url) returns the handler plus decoded path and search parameters, while has only tests a route. Options control trailing/duplicate slash handling, case sensitivity, and maximum parameter length.
Use it when implementing a router adapter or a specialized dispatch table. Application routes should normally use HttpRouter or HttpApi so handlers, services, and schemas remain integrated.
The adapter boundary between an Effect HTTP application and a host. toWebHandler(app) produces a Web (Request) => Promise<Response> handler; toWebHandlerLayer(layer) builds the dependency Layer immediately when the handler is created and returns { handler, dispose }. A request that arrives mid-build waits for it; if the build fails, every request rejects with the build error instead of surfacing an unhandled rejection. Eager construction moves cold-start cost to module load and makes a misconfigured deployment fail its first health check rather than its first user. fromWebHandler adapts an existing Web handler back into the current Effect request. The lower-level toHandled owns request scopes, applies middleware and pre-response hooks, and converts failures into responses — on a handler failure, the request Scope still closes with the original cause, so a scope finalizer or middleware can tell a failed request from a successful one even after it's been turned into a response.
For a layer-backed handler, retain the returned dispose function and await it during test/process teardown; calling it again returns the same promise. Pre-response handlers and HttpMiddleware.withLoggerDisabled apply to exactly one server request, and HttpEffect.appendPreResponseHandlerUnsafe takes the fiber context rather than the request. Advanced streaming adapters use scopeTransferToStream so a request scope remains alive until the response body finishes: the scope then closes with the body stream's exit, but only once both the body has ended and the request has finished, including middleware and tracing, so request finalizers never run before a middleware or span that still uses request resources. scopeDisableClose turns off only the close at the end of the request; whoever disabled it must close the scope on every path. Misuse can leak resources, so high-level server code should let the supplied host adapter manage both.
The app runs uninterruptibly unless it opts in.toHandled, and therefore toWebHandler, HttpServer.serve, and the Node, Bun, and Deno adapters, run the app, its middleware, and the response send in an uninterruptible region. A client disconnect, an aborted request.signal, or a server shutdown requests interruption immediately, but it takes effect only once the app has produced its response — unless the app makes itself interruptible. HttpRouter routes (and therefore every HttpApi handler) are interruptible unless added with uninterruptible: true; a bare app passed to HttpEffect.toWebHandler or HttpServer.serve needs Effect.interruptible(app).
Aborting after headers have returned interrupts the transferred response-body scope, even if nobody keeps pulling the body, so its resources are released; request abort listeners are removed when the request fiber ends. This is cancellation, not rollback of work already committed.
The shared body/headers model implemented by server requests and client responses: headers, optional remoteAddress, and effectful json, text, urlParamsBody, arrayBuffer, and byte stream accessors. schemaBodyJson, schemaBodyUrlParams, and schemaHeaders decode either side through Schema; the underlying body error is unioned with SchemaError.
HttpIncomingMessage.MaxBodySize is the fiber-scoped limit for collected bodies. inspect renders an incoming message without exposing sensitive headers. Prefer the more specific HttpServerRequest and HttpClientResponse helpers in ordinary handlers; use this interface for code that intentionally accepts either.
The host service behind local-file/Web-File responses and compression. Node, Bun, Deno, and Web layers implement platform, fileResponse, fileWebResponse, and a compressor supporting gzip, deflate, br, and optionally zstd. Most application code calls HttpServerResponse.file or HttpMiddleware.compression rather than this service directly.
A file response's Content-Type is, in order: the contentType option or an explicit content-type header, then a non-empty File.type (Web files), then a type inferred from the file extension — a .csv file with no explicit content type answers text/csv on the core and Node layers. HttpServerResponse.file has no contentLength option; the length always comes from the file and the requested range.
Compression negotiates Accept-Encoding, adds Vary, and skips statuses/bodies that must not be transformed, already encoded responses, Cache-Control: no-transform, and small or non-compressible payloads. It preserves the response Content-Type for file, raw, stream, and byte-array bodies — including a header you set after constructing the body. Do not enable both Effect and Deno automatic compression. Opt secret-plus-attacker-controlled responses out because compressed length can leak information (BREACH-style attacks).
A safe static-file application built over FileSystem, Path, and HttpPlatform. make({ root, index?, spa?, cacheControl?, mimeTypes? }) returns an HTTP app; layer({ ..., prefix? }) mounts GET routes in HttpRouter. It confines paths below the configured root, resolves directory indexes, derives MIME types, supports byte ranges and 206/416 responses, and handles conditional requests: If-Match / If-Unmodified-Since failures answer 412 before cache validation and ranges, ETag/last-modified matches answer 304 (keeping Content-Location, Date, Expires, and Vary; If-None-Match is parsed as a list of quoted entity tags, so a tag that itself contains a comma still matches), and HTTP dates are read as UTC. A directory URL without a trailing slash is redirected with 301 to the slash form (query and router prefix preserved), so clients that do not follow redirects must request the canonical URL.
A Range header is honored only on GET and only for a single bytes= range (open-ended bytes=500- and suffix bytes=-500 forms included). A malformed or multi-range header falls back to the full 200 response; a start at or beyond the file size gets 416 with Content-Range: bytes */<size>; and offsets are parsed as exact integers, so ranges stay correct past Number.MAX_SAFE_INTEGER.
Set spa: true for eligible navigation requests to fall back to the index; it does not indiscriminately rewrite every missing asset. Provide the host aggregate/HTTP platform layers at the application edge.
HTTP trace propagation interop. toHeaders(span) emits W3C traceparent and compact B3. fromHeaders(headers) safely tries W3C, compact B3, then multi-header B3 and returns Option<Tracer.ExternalSpan>; w3c, b3, and xb3 are individual decoders.
Parsing is strict: trace and span IDs must be lowercase hex in traceparent, b3, and X-B3-*, and traceparent flags must be two lowercase hex digits; anything else returns Option.none() (probed: an uppercase traceparent starts a new trace instead of continuing it). Effect's normal HTTP client/server tracing already uses these helpers. Reach for them only when injecting context into, or extracting it from, a non-Effect HTTP library.
The callback-driven incremental multipart/form-data parser used by platform adapters. make(config) returns { write(chunk), end() }; callbacks receive field values, file chunks (ending with null), completion, or structured errors. Limits cover parts, total bytes, per-part bytes, and field bytes. Helpers include defaultIsFile and charset-aware decodeField.
Errors distinguish invalid boundaries/dispositions, malformed headers, a reached limit, and an unexpected end. Exceeding the part-count, part-size, or field-size limit stops parsing and terminates every active file callback with failure; an unexpected end-of-body also terminates active files instead of leaving consumers hung. High-level applications should use Multipart and HttpServerRequest; MultipartParser, plus its public HeadersParser and Search submodules, is for host adapters and custom streaming sinks.
Request router expressed as Layers. HttpRouter.add(method, path, handler) produces a Layer for one route; HttpRouter.addAll([...]) contributes many. Merge them like any other Layers and pass to HttpRouter.serve (real server) or HttpRouter.toWebHandler (Fetch-style handler for serverless). Path params, prefixes, CORS, and middleware all compose at this level.
Mental model. Each route is a Layer that registers itself on an HttpRouter. Route dependencies flow through Layer composition — no global app object; the router is the wiring.
The method is "*" or one of GET, POST, PUT, PATCH, DELETE, OPTIONS, and QUERY — the safe, idempotent HTTP method that carries its query in the request body (read it with request.json or a schema body decoder, as for POST). HttpRouter.route accepts any HttpMethod.
HttpRouter.addAll(routes, { prefix: "/internal" }) mounts a batch under a prefix. Inside a prefixed route request.url has the prefix removed (request.originalUrl keeps it), and router.prefixed("/v1").prefixed("/comp") nests outer-first, serving /v1/comp/....
Prefix removal counts matched URL segments, including parameterized prefixes, rather than slicing by the pattern's character length. Slash normalization preserves the query string. Prefer HttpRouter.params and ParsedSearchParams over reparsing request.url with assumptions about the original mount path.
For typed route middleware, HttpRouter.middleware tracks services it provides, errors it handles, errors it may add, and requirements that remain. Its .layer supplies both provided request services and handlers for the declared handles errors. Global middleware errors remain visible in the error channel returned by HttpRouter.toHttpEffect; they are not silently erased.
Warning:Every entrypoint builds its own router in a fresh, forked layer memo map.HttpRouter.serve(appLayer) merges appLayer with a newHttpRouter rather than reusing one the app provides itself — a route registered via Layer.provide(HttpRouter.layer)insideappLayer builds against that private router and is never mounted on the router serve actually serves. Pass routes as Layers merged directly into the argument of serve (as in the example below), not nested behind their own HttpRouter.layer provision. The same rule governs every entrypoint — serve, toWebHandler, toHttpEffect — so layers first built inside one entrypoint are private to it: a stateful service built there is not shared with a sibling entrypoint or the surrounding application, and building the same service inside two entrypoints can construct it twice depending on build order. Provide services that must be shared outside an entrypoint higher up, outside serve's argument, so every entrypoint's forked memo map reuses the already-built instance instead of rebuilding it. This also governs composing RPC over HTTP: put the RPC protocol and its handler layer in the app passed to serve, for example HttpRouter.serve(RpcLayer.pipe(Layer.provideMerge(RpcServer.layerProtocolHttp({ path: "/rpc" })))), not behind a separately-provided router.
Self-contained source · Type-checked
ts
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"import { Effect, Layer } from "effect"import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"import { createServer } from "node:http"// A handler is just an Effect that yields an HttpServerResponse.const HealthRoute = HttpRouter.add( "GET", "/health", Effect.succeed(HttpServerResponse.text("comp-service ok")))// Handlers can be functions of the request, and can require services.const PayrollWebhookRoute = HttpRouter.add( "POST", "/webhooks/payroll", Effect.gen(function*() { const request = yield* HttpServerRequest.HttpServerRequest const body = yield* request.text return HttpServerResponse.text(body) }))// Path params come from HttpRouter.params.const EmployeeRoute = HttpRouter.add( "GET", "/employees/:id", Effect.gen(function*() { const { id } = yield* HttpRouter.params return yield* HttpServerResponse.json({ id }) }))// Merge routes, add CORS, and serve. serve() returns a Layer you launch.const AllRoutes = Layer.mergeAll( HealthRoute, PayrollWebhookRoute, EmployeeRoute, HttpRouter.cors())const ServerLayer = HttpRouter.serve(AllRoutes).pipe( Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })))Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)
Note:Serverless, same routes. Swap to HttpRouter.toWebHandler(AllRoutes.pipe(Layer.provide(HttpServer.layerServices))) for { handler, dispose } — a (Request) => Promise<Response> for Cloudflare Workers, Vercel, Deno, or tests. Route definitions unchanged.
Reach for it when you want hand-rolled routes — webhooks, health endpoints, file exports — without a full schema-described API.
Abstract server service plus the functions that run an HTTP app. HttpServer.serve(handler) binds an app-effect to the bound socket; HttpServer.logAddress/withLogAddress log the listen address; HttpServer.layerServices supplies platform-neutral services to a handler. Provide a concrete server Layer — NodeHttpServer.layer(createServer, { port }) or the Bun equivalent.
The service's address field is a NetAddress.SocketAddress — an InetAddress (IP plus port) or a UnixPathAddress, replacing the old TcpAddress | UnixAddress pair. Narrow it with NetAddress.isInetAddress before reading port, or render it with HttpServer.formatAddress(address). NodeHttpServer.layerTest binds port 0 and supplies an HttpClient already prefixed with the assigned address. On Bun and Deno, a listen address that cannot be converted fails the Layer with ServeError, and a request that arrives while the listener is bound but no app is being served yet is answered 503 Service Unavailable with Cache-Control: no-store and an advisory Retry-After: 1, rather than a 404 a cache or health check could mistake for a missing route.
Every request runs in a fiber the server owns, inside a request Scope. When the client goes away before the response has finished, the host adapter interrupts that fiber (Node marks the interrupt as a client abort; for a request that had not started responding, the logger records 499), so finalizers run and downstream calls are cancelled. The interrupt lands only where the handler is interruptible: HttpRouter routes and HttpApi handlers are by default, while a bare app given to HttpServer.serve runs uninterruptibly until it has produced its response unless wrapped in Effect.interruptible (see HttpEffect; probed with toWebHandler: the plain app ran to completion and answered 200, the interruptible one stopped and answered 499). The guarantee also holds only while the work is in the fiber:
Escape
What is lost
Effect.runPromise(...) or a second runtime inside a handler
the inner run has no parent; a disconnect cannot reach it
Effect.forkDetach, or a fork into a longer-lived scope
the work outlives the request on purpose — fine for a durable hand-off, a leak otherwise
await-ing a promise that ignores the AbortSignal passed by Effect.tryPromise
the fiber is interrupted but the I/O keeps running
A streaming response keeps the request Scope open until the body ends, which is also what makes disconnect cancellation provable: a completed response, or an Effect you interrupt by hand, says nothing about sockets. The proof needs the response to be open when the client leaves.
Self-contained source · Type-checked
ts
import { NodeHttpServer } from "@effect/platform-node"import { Deferred, Effect, Exit, Layer, Schedule, Stream } from "effect"import { HttpRouter, HttpServer, HttpServerResponse } from "effect/http"import { NetAddress } from "effect/net"import * as Http from "node:http"export const disconnectInterruptsTheHandler = Effect.gen(function*() { const acquired = yield* Deferred.make<void>() const released = yield* Deferred.make<"completed" | "interrupted" | "failed">() const PayrollExport = HttpRouter.add( "GET", "/payroll/export", Effect.gen(function*() { // Request-scoped finalizer: records HOW the request ended. yield* Effect.addFinalizer((exit) => Deferred.succeed( released, Exit.isSuccess(exit) ? "completed" : Exit.hasInterrupts(exit) ? "interrupted" : "failed" ) ) yield* Deferred.succeed(acquired, undefined) const rows = Stream.fromSchedule(Schedule.spaced("20 millis")).pipe( Stream.map((n) => new TextEncoder().encode(`row ${n}\n`)) ) return HttpServerResponse.stream(rows) // never ends on its own }) ) const ServerLive = HttpRouter.serve(PayrollExport, { disableLogger: true, disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layer(Http.createServer, { port: 0, host: "127.0.0.1" })) ) return yield* Effect.gen(function*() { const { address } = yield* HttpServer.HttpServer if (!NetAddress.isInetAddress(address)) return yield* Effect.die("expected a TCP listener") // A raw client: read the first chunk, then drop the connection. const request = Http.get({ host: "127.0.0.1", port: address.port, path: "/payroll/export" }, (response) => { response.once("data", () => request.destroy()) }) request.on("error", () => {}) yield* Deferred.await(acquired) return yield* Deferred.await(released) // "interrupted" }).pipe(Effect.provide(ServerLive))})
Run the normal-completion case as a separate test (a finite stream, a client that reads to the end) and assert the inverse: "completed", one acquisition, one release. For the same guarantee across a non-Effect host, see the request-cancellation recipe.
Own the listener: acquire late, bind port 0, prove release
Allocate during Layer acquisition, never at module evaluation. A module-level createServer(), Ref, or counter is shared by every build of the Layer, so two tests (or two tenants) silently share state. Pass the constructor (NodeHttpServer.layer(createServer, options)), and create mutable state inside Layer.effect.
Let the OS pick the port in tests (listen on 0, then take the real port from HttpServer.address), because a hard-coded port breaks as soon as test files run in parallel.
Prove release at the OS level. Build the server Layer into a Scope you hold, show that binding a plain node:net server to the same host and port fails with EADDRINUSE, close the Scope, and show that the same bind now succeeds. A finalizer flag, or a bind to a different ephemeral port, is not evidence that the listener is gone.
A constructor that returns a live server and requires Scope must not close that Scope itself — the caller owns the lifetime.
Shutdown is graceful by default on Node, Bun, and Deno. Closing the serve scope stops accepting connections and gives in-flight requests up to gracefulShutdownTimeout (20 seconds unless set) to finish; a request still running after that is interrupted and answered with 503 (probed on Node). An uninterruptible handler is not cut short: shutdown waits for it to finish even after the timeout. On Node, connected WebSockets are sent a 1001 (Going Away) close frame as soon as shutdown starts, other upgraded connections are ended, and any still open when the timeout expires are destroyed; Bun likewise force-closes the connections left at the timeout, so an unread request body cannot hold shutdown open. disablePreemptiveShutdown: true removes the grace period, and on Node then destroys upgraded connections right after closing them, so a close frame may not reach the peer — prefer a short timeout when clients need it. Size your orchestrator's termination grace period above the timeout, and see owning lifetimes, startup, readiness, and shutdown and the graceful entrypoint recipe.
NodeHttpServer.make / layer / layerConfig also accept Http2.createServer and Http2.createSecureServer (including allowHTTP1): HTTP/2 requests hide pseudo-headers, toURL uses :scheme and :authority, and connection-specific response headers are dropped. NodeHttpServerRequest.toIncomingMessage / toServerResponse then return a union of the HTTP/1 and HTTP/2 objects, so narrow before using HTTP/1-only members. Request headers are converted to Headers, so Headers.CurrentRedactedNames applies when they are logged.
Reach for it when wiring the actual listener, choosing a port, or swapping Node vs Bun by replacing one Layer.
Incoming request available as a service inside any handler (yield* HttpServerRequest.HttpServerRequest). Exposes URL, method, headers, cookies, and body — plus schema* helpers that decode parts through a Schema, failing into the error channel on bad input.
Mental model.schemaBodyJson, schemaHeaders, schemaCookies, schemaSearchParams, schemaBodyForm, and schemaBodyUrlParams each take a Schema and return typed data — the same philosophy as client response decoders, pointed inward.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"const RaiseRequest = Schema.Struct({ employeeId: Schema.Int.check(Schema.isGreaterThan(0)), newBaseSalary: Schema.Finite})const RaiseRoute = HttpRouter.add( "POST", "/raises", Effect.gen(function*() { // Decode + validate the JSON body. Bad input -> typed SchemaError. // schemaBodyJson reads the request from context; it is not curried over it. const raise = yield* HttpServerRequest.schemaBodyJson(RaiseRequest) return yield* HttpServerResponse.json({ recorded: raise.employeeId }, { status: 201 }) }))
request.stream of a request without a body is an empty stream rather than a failure, on the core request and on Node, Bun, and Deno alike, so a streaming handler needs no special case for a bodyless POST. Buffered reads (text, json, arrayBuffer, urlParamsBody) honor HttpIncomingMessage.MaxBodySize on every adapter, including requests built with HttpServerRequest.fromClientRequest.
Connection details: remoteAddress (replaced by trusted proxy middleware), peerAddress (always the transport peer), and protocol ("http" | "https" | undefined, set by trusted proxy middleware and read by toURL). request.upgrade takes over the raw connection, and request.upgradeWith({ headers }) does the same while adding headers to the 101 response (WebSocket upgrades fail when headers are given); custom HttpServerRequest implementations must provide both.
Reach for it when a handler needs the body, headers, query string, or cookies validated rather than stringly-typed.
Response builder. Constructors: text, json, html/htmlStream, uint8Array, stream, file/fileWeb, redirect, empty, raw. Pipeable modifiers: setStatus, setHeader(s), cookie family. schemaJson(schema) encodes a domain value through a Schema into a JSON response — the symmetric partner of the request decoders.
Mental model. An immutable value assembled with pipes, just like a client request.
HttpServerResponse.toWeb — and the Bun and Deno adapters — send no body for statuses 204, 205, and 304, or when asked for a bodyless (HEAD) response, even if one was constructed; a raw ReadableStream body is cancelled instead of leaking. HttpServerResponse.omitsBody(response) exposes the same predicate to custom adapters. Dropping the body of a raw Web Response keeps that Response's headers and Set-Cookie values; a 204, 205, or 304 keeps the outer status and status text, while HEAD keeps the raw Response's. Cookies set on the outer response are appended to the native Set-Cookie headers instead of replacing them.
setBody keeps content-type and content-length aligned with the replacement body and removes stale values when it has no corresponding metadata. Because pipes apply in order, put an explicit setHeader after the body constructor when that header must override body-derived metadata.
For a raw Web Response, toWeb returns it unchanged when there are no outer headers/cookies to merge. Otherwise it merges into a copy, so immutable headers (such as a fetched response's) work and the original response is not mutated. Outer headers replace matching native headers; cookies append. Its optional signal interrupts Effect-backed stream bodies on abort.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { HttpServerResponse } from "effect/http"// A JSON response with a custom status, header, and a Set-Cookie.const response = HttpServerResponse.json({ ok: true }, { status: 201 }).pipe( Effect.map((res) => res.pipe( HttpServerResponse.setHeader("x-request-id", "abc-123"), HttpServerResponse.setCookieUnsafe("session", "tok", { httpOnly: true, path: "/" }) ) ))// schemaJson encodes a value THROUGH a schema (the encode direction).import { Schema } from "effect"const Employee = Schema.Struct({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String})const employeeResponse = HttpServerResponse.schemaJson(Employee)({ id: 1, name: "Ada Lovelace" })
Reach for it when producing any response, especially with a schema-encoded body or cookie/header control.
Middleware as a plain function: takes the "rest of the app" (an Effect producing a response) and returns a new one. Built-ins: logger (applied automatically by HttpRouter.serve unless disabled), tracer, cors, xForwardedHeaders, searchParamsParser. Define custom middleware with HttpMiddleware.make.
HttpMiddleware.xForwardedHeaders({ trustedProxies }) takes a list of IpNetworks or a predicate on the peer's NetAddress.IpAddress, and applies X-Forwarded-* only when the connecting peer is trusted. It reads X-Forwarded-For from the right, skipping trusted hops, so a client-spoofed leftmost entry is ignored; X-Forwarded-Host / X-Forwarded-Proto are used only when they line up one-to-one with it, replacing host and setting request.protocol. request.peerAddress keeps the transport peer after remoteAddress is replaced, and HttpServerRequest.toURL reads request.protocol rather than the raw header. Migration: the bare HttpMiddleware.xForwardedHeaders value became this function; pass your proxy networks explicitly.
Self-contained source · Type-checked
ts
import { HttpMiddleware } from "effect/http"import { IpNetwork } from "effect/net"export const behindLoadBalancer = HttpMiddleware.xForwardedHeaders({ trustedProxies: [IpNetwork.fromStringUnsafe("10.0.0.0/8")]})
The tracer middleware redacts the URL in the failure it records for a 5xx, and also redacts the query and header names an HttpApi endpoint declares with HttpApi.RedactedNames in that request's span, and compression ignores empty Accept-Encoding members such as gzip,. To modify the response, register via HttpRouter.middleware (the serve-level option runs around the whole chain but can't change the final response).
HttpMiddleware.decompression({ maxDecompressedSize? }) lazily decompresses gzip and zlib-format deflate through global DecompressionStream; raw deflate is not accepted. Stacked encodings are undone in reverse order and identity members ignored. Unsupported codings return 415 with Accept-Encoding: gzip, deflate without running the app.
The replacement request's body accessors (including stream and multipart) see decompressed bytes, and its headers omit Content-Encoding and Content-Length. Malformed data fails the body read with RequestParseError (multipart: MultipartError, reason Parse). The size limit applies to decompressed bytes through every accessor: explicit maxDecompressedSize, otherwise HttpIncomingMessage.MaxBodySize, otherwise 10 MiB. Exceeding it fails with RequestParseError (multipart: reason BodyTooLarge). Keep ingress compressed-byte limits too: neither bound substitutes for the other.
request.source remains compressed. HttpServerRequest.toWeb returns that original source when it is already a Web Request; on Node it builds from the decompressed view. Do not pass the source to a downstream parser expecting the replacement headers/body. This is independent of response compression.
Self-contained source · Type-checked
ts
import { Clock, Effect } from "effect"import { HttpMiddleware, HttpServerResponse } from "effect/http"// A timing middleware that adds a header to every comp-service response.// `app` is the rest of the chain; we run it and decorate the result.const withTiming = HttpMiddleware.make((app) => Effect.gen(function*() { const start = yield* Clock.currentTimeMillis // never new Date() / Date.now() const response = yield* app const elapsed = (yield* Clock.currentTimeMillis) - start return HttpServerResponse.setHeader(response, "x-response-time", `${elapsed}ms`) }))
Warning: The built-in logger middleware is on by default via HttpRouter.serve. Pass { disableLogger: true } to serve, or layer HttpRouter.disableLogger, to opt out. It logs the method, the path without its query string, and the status; a failed request also logs its Cause, so keep secrets Redacted rather than relying on the logger to hide them.
Warning:HttpRouter.cors() with no options answers Access-Control-Allow-Origin: *. Pass an allow-list for anything that is not a public, credential-free API. With a predicate or two or more allowedOrigins, the request's Origin is echoed only when it is allowed (a predicate is called only for requests that carry an Origin header; a request without one gets no allow-origin header), and Vary: Origin is always sent — merged with any Vary the response or compression already set — so a shared cache cannot serve one origin's answer to another. A single allowed origin is sent as a constant, also with Vary: Origin. With allowedHeaders left empty, a preflight reflects whatever Access-Control-Request-Headers the browser asked for. allowedMethods defaults to GET, HEAD, PUT, PATCH, POST, and DELETE; a browser only sends a cross-origin QUERY request after you add "QUERY" to that list.
Several server limits are unbounded until you set them. Decide each one explicitly; "whatever the default is" is not a policy.
Concern
Default
Set it with
Collected request body (text, json, arrayBuffer, buffered multipart total)
no limit
HttpIncomingMessage.MaxBodySize (a ByteSize), provided as a Layer or per route; an over-limit buffered or decompressed body fails with a BodyTooLargeRequestParseError answered 413 (probed on Node, which drains the body so the response reaches the client; Bun, Deno, and toWebHandler enforce it too)
Multipart part count / file size
no limit
Multipart.MaxParts, Multipart.MaxFileSize, or per endpoint with HttpApiSchema.asMultipart({ maxParts, maxFileSize, maxTotalSize })
Multipart text field size
10 MiB
Multipart.MaxFieldSize
Path parameter length, trailing-slash and case rules
router defaults
HttpRouter.serve(app, { routerConfig })
CORS origins
*
HttpRouter.cors({ allowedOrigins, credentials })
Headers hidden from logs and spans
authorization, cookie, set-cookie, x-api-key
Headers.CurrentRedactedNames
Graceful shutdown window (Node, Bun, Deno)
20 seconds
gracefulShutdownTimeout on the server Layer
Beyond what the library models, write down: header-size, connection-count, and keep-alive limits on the host (node:http server options, or the proxy in front); connect, header, idle, total, and drain timeouts (Effect.timeout per route for the total; the rest belong to the host or proxy); response size and streaming limits for exports; TLS termination; and proxy trust — HttpMiddleware.xForwardedHeaders({ trustedProxies }) (see HttpMiddleware) applies forwarded headers only for connections from proxies you name.
For cookie-authenticated browsers: set httpOnly, secure, an explicit sameSite, and a narrow path; and because CORS does not stop a cross-site form post, protect every state-changing route with a CSRF defense (a same-site cookie policy plus an Origin check or a per-session token). WebSocket upgrades are not covered by CORS at all — check Origin in the upgrade handler.
For uploads: treat the client's filename and MIME type as untrusted labels (derive the type with Mime, generate your own storage name), bound concurrent uploads, and let the request Scope own temporary files — schemaBodyForm persists files into a scoped temp directory that is removed when the request ends, so copy what you keep before responding. Fixture rules for tests that use real listeners, ports, and temp directories are in Testing an Effect application.
Reach for it when you need cross-cutting behavior — auth, timing, request IDs, CORS — without repeating it per handler.
Unified body representation shared by client requests and server responses. The higher-level constructors (e.g. HttpServerResponse.json, HttpClientRequest.bodyText) usually build these for you, but the module provides explicit control: HttpBody.text, json/jsonUnsafe, jsonSchema (encode through a Schema), uint8Array, urlParams, formData/formDataRecord, stream, file. Construction failures surface as HttpBodyError, which HttpBody.isHttpBodyError guards an unknown error down to.
Reach for it when building a body by hand — streaming batches, multipart uploads, or schema-encoded JSON — rather than via a verb helper.
Immutable, case-insensitive header map with redaction support. Headers.fromInput builds one — from a record (array values are joined with ", ") or from an iterable of pairs, where repeated names are likewise joined rather than the last one winning (do not forward a joined set-cookie as one header; read response.cookies instead); pure operations: get/set/merge/remove. redact (and the CurrentRedactedNames reference) strips sensitive headers like authorization from logs and traces automatically.
Headers.CurrentRedactedNames defaults to authorization, cookie, set-cookie, and x-api-key. String patterns match header names case-insensitively and regular expressions (including global or sticky ones) are tested against the name. The list governs what HttpMiddleware.logger redacts in log output. Header capture on server spans is opt-in: HttpMiddleware.TracerHeaderFilter controls which header names are added as http.request.header.* / http.response.header.* span attributes — the default records no headers. When you do enable capture, CurrentRedactedNames still applies and redacted headers are recorded as "<redacted>". Add your own secrets-bearing names (x-hris-signature, a session header) once, at the server edge:
Content-Length values are parsed strictly across the HTTP modules: a malformed or unsafe value is ignored rather than coerced into a number.
Typed date and Retry-After values: Headers.parseHttpDate / formatHttpDate read all three RFC 9110 date forms as UTC and write IMF-fixdate; Headers.parseRetryAfter accepts whole non-negative seconds or an HTTP date and returns a RetryAfter (a Duration or a DateTime.Utc), and Headers.retryAfterDelay(value, now) never returns a negative delay. Parse failures are HeaderParseError. Schema.DateTimeUtcFromHttpDate and Schema.RetryAfterFromString expose the same parsing for HttpApi headers.
Reach for it when you manipulate headers directly, or need redaction to keep credentials out of logs.
Immutable cookie jar plus a Cookie type with all attributes (httpOnly, secure, sameSite, maxAge, path, domain). Parse a request's Cookie header with parseHeader; fromSetCookie parses one or more response Set-Cookie header values into a jar. Build with set/setUnsafe and expire with expireCookie. The safe constructors validate the cookie name, value, domain, and path and return CookiesError; reserve *Unsafe forms for already-trusted values. The error's tag is "CookiesError", so recover with Effect.catchTag("CookiesError", ...) and branch on error.reason._tag (InvalidCookieName, InvalidCookieValue, InvalidCookieDomain, InvalidCookiePath, …); Cookies.isCookiesError guards an unknown error down to this type. fromSetCookie skips any Set-Cookie header whose name is not a valid RFC 6265 token instead of storing it. On the server use HttpServerResponse.setCookie; on the client, a Ref<ReadonlyArray<Cookies.Cookie>> wired via HttpClient.withCookiesRef gives a persistent session.
For a client-side jar, Cookies.mergeIntoArray(stored, url, cookies, now) stores response cookies scoped to the response URL, and Cookies.toRequestCookieHeader(stored, url, now) selects the unexpired cookies matching a request's host, path, and scheme; HttpClient.withCookiesRef is built on both. Parsing follows RFC 6265: spaces around a name and value are trimmed, and a malformed Max-Age is ignored rather than read by numeric prefix.
Reach for it when setting auth/session cookies on responses or maintaining a cookie jar across client calls.
Type-level vocabulary for HTTP verbs: the HttpMethod union, the all set, isHttpMethod guard, and hasBody (false for GET, HEAD, OPTIONS, and TRACE, true for POST, PUT, DELETE, PATCH, QUERY, and any other string; given an HttpMethod it narrows to HttpMethod.WithBody, given a plain string it returns a boolean). QUERY is also in all, and HttpClient, HttpRouter, and HttpApiEndpoint each have a query constructor or accept the method.
A received request's method (HttpServerRequest.method, HttpClientRequest.method, since a client request converted from a Web or server request can carry any method, and forwarded methods such as AI HTTP error details) is typed as string, because clients can send extension methods such as PROPFIND. Migration: an exhaustive switch on request.method needs a default branch, or narrow first with HttpMethod.isHttpMethod.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { HttpMethod, HttpServerRequest, HttpServerResponse } from "effect/http"export const describe = Effect.gen(function*() { const request = yield* HttpServerRequest.HttpServerRequest if (!HttpMethod.isHttpMethod(request.method)) { return HttpServerResponse.empty({ status: 501 }) } return HttpServerResponse.text(HttpMethod.hasBody(request.method) ? "has body" : "no body")})
Reach for it when branching on request method or validating a method string.
Safe, immutable helpers over the native URL. Url.fromString parses (returns a Result — bad URL is a value, not a throw); Url.make(url, params, hash) constructs a URL while appending UrlParams and returns a typed UrlError; mutate applies a mutation to a copy; pipeable setters (setHostname, setPathname, setProtocol, setUrlParams, …) edit without mutation. URL construction lives here — the old UrlParams.makeUrl entry point is gone.
Self-contained source · Type-checked
ts
import { Url } from "effect/http"const url = new URL("https://hris.acme.internal/employees")// mutate copies first, so the original is untouched.const updated = Url.mutate(url, (u) => { u.pathname = "/v2/employees" u.searchParams.set("page", "1")})
Reach for it when parsing or transforming URLs with immutability and parse errors as values.
Immutable, order-preserving query-string model with correct repeated-key handling. Build with make/fromInput, read with getAll/getFirst/getLast, edit with set/append/remove. Accepts coercible inputs — numbers, booleans, bigints. The schemas for these HTTP data types live in effect/Schema: Schema.UrlParams, Schema.RecordFromUrlParams, and Schema.JsonFromUrlParamsField(field, { reviver? }), which round-trips a JSON-encoded query param through a Schema (the former UrlParams.schemaJsonField, schemaRecord, and UrlParamsSchema). Schema.Headers, Schema.Cookie, Schema.Cookies, and Schema.RecordFromCookies moved the same way.
UrlParams.CurrentRedactedNames governs inspection, HTTP spans, and HTTP error URLs. Defaults are X-Amz-Signature, X-Amz-Credential, X-Amz-Security-Token, AWSAccessKeyId, Signature, sig, and X-Goog-Signature; a custom list replaces them, so retain the defaults when adding names. Values can themselves be Redacted strings: inspection hides those independently of the name list, while the actual request sends their unwrapped values. Redaction changes diagnostics, not the wire request.
UrlParams.redactUrl(url, names?) also hides URL userinfo (username/password), independent of query-name patterns. Use it for diagnostic URLs rather than logging UrlParams.toString, a raw URL, or an application-created error message. Fragments and arbitrary path secrets are not an application secret scrubber; avoid putting credentials there. Header redaction uses a separate Headers reference.
Self-contained source · Type-checked
ts
import { UrlParams } from "effect/http"// Filter the employee roster by several departments at once.const params = UrlParams.fromInput({ dept: ["ENG", "SALES"], page: 2 }).pipe( UrlParams.append("dept", "OPS"))UrlParams.getAll(params, "dept") // ["ENG", "SALES", "OPS"]UrlParams.toString(params) // "dept=ENG&dept=SALES&page=2&dept=OPS"
Reach for it when building or parsing query strings, especially with repeated keys or typed values.
Streaming multipart/form-data parsing. Distinguishes Field (text) from File parts; can persist uploads to disk (PersistedFile). Exposes Schemas (FilesSchema, SingleFileSchema, PersistedFileSchema) for typed decoding. Safety limits — MaxParts, MaxFileSize, MaxFieldSize, FieldMimeTypes — are Context.References tunable per route; only MaxFieldSize has a finite default (see the edge policy checklist). Failures: MultipartError, which Multipart.isMultipartError guards an unknown error down to. Multipart.isPart accepts every branded part including PersistedFile; Multipart.isStreamPart is true only for a text Field or a streamed File, which is the guard a streaming consumer wants. A request body that fails while a file part is streaming fails that file's stream instead of leaving its consumer waiting, and persisting a file passes a MultipartError from the body through unchanged instead of re-wrapping it as an InternalError reason. Parts are emitted to the consumer as soon as they're parsed rather than held back until more input arrives, so a slow part behind a fast one doesn't stall the ones already decoded.
Mental model. An upload is a stream of parts, not a blob. Typically used via HttpServerRequest.schemaBodyForm(schema) or schemaBodyMultipart(schema) — Multipart + Schema handle parsing and validation together.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { HttpRouter, HttpServerRequest, HttpServerResponse, Multipart } from "effect/http"// Decode a merit-cycle upload: a label field plus a CSV of recommendations.const MeritUploadForm = Schema.Struct({ cycle: Schema.String, file: Multipart.SingleFileSchema // a persisted file on disk})const UploadRoute = HttpRouter.add( "POST", "/merit-cycles/upload", Effect.gen(function*() { // schemaBodyForm reads the request from context; it is not curried over it. const form = yield* HttpServerRequest.schemaBodyForm(MeritUploadForm) return yield* HttpServerResponse.json({ cycle: form.cycle, path: form.file.path }) }))
Reach for it when accepting file uploads or mixed form posts — stream, size-limit, and decode into typed values.
Server tagged error family: RequestParseError (schema decode failed), RouteNotFound, InternalError, ResponseError, ServeError (listener couldn't bind). The framework maps these to sensible status codes (parse error → 400, an over-limit body → 413, missing route → 404); causeResponse turns a failure cause into a response. Error messages include only the request method and path, never query values or URL credentials, so they are safe in span errors and logs; the full request is still on the error.
Reach for it when you want to override how parse or not-found failures are rendered, or react to a bind failure on startup.
Interface that lets any value describe how it becomes a response. Implement the HttpServerRespondable symbol on a class (e.g. a tagged error) and the router converts it to an HttpServerResponse automatically — a handler can fail with a domain error and have it rendered without a manual mapping step. toResponse/toResponseOrElse perform the conversion.
Reach for it when you want domain errors or DTOs to render themselves as responses instead of per-error response code.
ETag generation for caching and conditional requests. Etag.Generator service produces strong or weak tags from file info; provide Etag.layer (strong) or Etag.layerWeak (weak) and the static-file machinery uses it to support If-None-Match and 304 responses.
Reach for it when serving files or cacheable resources and wanting conditional-request support without hand-rolling hashes.
Effectful tagged-template literal for building HTML (or any string) where interpolations can themselves be Effects, Options, or Streams. Template.make resolves embedded effects (concurrently) and produces Effect<string>; Template.stream produces Stream<string> for progressive rendering. Pair with HttpServerResponse.html/htmlStream for streaming server-side rendering.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { HttpServerResponse, Template } from "effect/http"// Render a comp summary page, resolving the employee name async inside the markup.const renderCompPage = (employeeName: Effect.Effect<string>) => Effect.gen(function*() { const html = yield* Template.make`<h1>Comp plan for ${employeeName}</h1>` return HttpServerResponse.html(html) })
Reach for it when rendering HTML server-side with async data and streaming composing naturally inside the markup.
The single source of truth that maps readable status names to numeric codes. HttpStatus.fromLiteral("Conflict") returns the literal type 409, and HttpStatus.Literal is the union of known names ("OK", "Created", "NoContent", "UnprocessableEntity", …). HttpApiSchema.status consumes it, so an endpoint annotation can say HttpApiSchema.status("Conflict") instead of a bare 409.
Self-contained source · Type-checked
ts
import { HttpStatus } from "effect/http"const conflict = HttpStatus.fromLiteral("Conflict") // 409const unprocessable = HttpStatus.fromLiteral("UnprocessableEntity") // 422// Accept a status by name in your own helpers without a second lookup table.const describe = (status: HttpStatus.Literal) => `${status} → ${HttpStatus.fromLiteral(status)}`
Reach for it when a status code is part of a contract or a log line and a name reads better than a number.
MIME lookup backed by a vendored standard registry (the mime runtime dependency was removed). Three pure functions, each returning an Option: Mime.getType(pathOrExtension), Mime.getExtension(type), and Mime.getAllExtensions(type). Lookups are case-insensitive on the extension, and type parameters and whitespace are normalized, so "application/json; charset=utf-8" resolves to json. The lookup tables are built lazily on first call rather than at module evaluation, so importing this module without calling a lookup lets bundlers drop the tables and the MIME data they index.
Self-contained source · Type-checked
ts
import { Option } from "effect"import { Mime } from "effect/http"Mime.getType("reports/q4.CSV") // Option.some("text/csv")Mime.getType("LICENSE") // Option.none() — no extension to go onMime.getExtension("application/json; charset=utf-8") // Option.some("json")Mime.getAllExtensions("image/jpeg") // Option.some(Set { "jpg", "jpeg", "jpe" })// Never trust a client-supplied content type for a download: derive it from the stored name.const contentTypeFor = (fileName: string) => Option.getOrElse(Mime.getType(fileName), () => "application/octet-stream")
Reach for it when choosing a Content-Type for a file response or validating an upload's extension against its declared type.
Describe the API once as data: groups of endpoints, each with Schema-typed path params, query, payload, success, and errors. Derive a server (implement handlers, get validation free), a fully typed client (method names and argument/return types mirror the definition), and OpenAPI + Swagger + Scalar docs. Rename an endpoint or change a field and every consumer fails to compile.
Tip: Keep the API definition (HttpApi, groups, endpoints, error schemas, middleware interfaces) in a module with no server code. The server implements handlers against it; clients derive from it. This lets a frontend import the exact same contract the backend serves, with zero server code crossing the boundary.
Official example: Effect's release-matched ai-docs HttpApi server example connects a schema-first contract, handlers, middleware, serving, and a generated client.
Invalid input fails with 400 before the handler runs and is not a server failure. A declared error uses the status declared for it; a defect or a response that cannot be encoded is a 500 reported to ErrorReporter; a disconnect interrupts the request fiber and runs the handler's finalizers.
One endpoint described as data. HttpApiEndpoint.get(identifier, path, spec) (and post, put, patch, delete, …) declares a route whose params, query, payload, success, and error are all Schemas. The identifier becomes the handler key and client method name and is exposed as .identifier; do not use .name, which is the native function name because endpoints are callable function objects. The path string carries :params.
Mental model. A typed contract: "given these validated inputs, return this success or one of these errors." The verb decides where payload lives — GET uses query string, POST/PUT/PATCH and QUERY use the request body (JSON by default). Path params are strings on the wire; their Schemas must decode from string (use Schema.FiniteFromString, or bridge with Schema.decodeTo to a branded type). Array-valued query fields accept either one value or repeated values, so ?tag=equity decodes like the singleton array form of ?tag=equity&tag=salary.
Fragment · Type-checked with fixture
ts
import { Schema } from "effect"import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api"import { CompRecord, EmployeeId, RaiseInput } from "./domain/Comp.ts"import { EmployeeNotFound } from "./domain/CompErrors.ts"// GET an employee's comp by id: the path param must DECODE FROM a string.const getComp = HttpApiEndpoint.get("getComp", "/employees/:id/comp", { params: { id: Schema.FiniteFromString.pipe(Schema.decodeTo(EmployeeId)) }, success: CompRecord, // Render this error as a bare 404 with no body. error: EmployeeNotFound.pipe( HttpApiSchema.asNoContent({ decode: () => new EmployeeNotFound() }) )})// POST a raise: payload is the JSON request body.const postRaise = HttpApiEndpoint.post("postRaise", "/employees/:id/raise", { params: { id: Schema.FiniteFromString.pipe(Schema.decodeTo(EmployeeId)) }, payload: RaiseInput, success: CompRecord})
HttpApiEndpoint.query declares an HTTP QUERY endpoint: a safe, idempotent read whose payload travels in the request body like a POST, for searches too large or too structured for a query string. The server, the derived client, and HttpApiTest handle it like any other verb; OpenAPI output and CORS need attention, see OpenApi and HttpMiddleware.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { HttpApiEndpoint } from "effect/http-api"// Search comp bands with a structured filter in the body: QUERY /comp-bands/searchconst searchBands = HttpApiEndpoint.query("searchBands", "/comp-bands/search", { payload: Schema.Struct({ levels: Schema.Array(Schema.String), location: Schema.String }), success: Schema.Array(Schema.Struct({ level: Schema.String, midpoint: Schema.Finite }))})
A literal suffix after a path parameter stays literal: /merit-cycles/:id:close binds id and keeps :close as literal path text. The server router, the derived client and urlBuilder, and the OpenAPI path (/merit-cycles/{id}:close) all agree on that shape.
Warning:Put the rule on the contract, not in the handler. A permissive endpoint schema (id: Schema.String) with the real pattern, range, or brand check repeated inside the handler hides the rule from the derived client, the OpenAPI document, and contract tests, and it lets invalid input reach downstream work before anything rejects it. Put checks and brands on params, query, headers, and payload; the handler then only ever sees decoded values. HttpApi answers a request that fails decoding with an empty 400 and an unmatched request Content-Type with 415, both before the handler runs — HttpApiTest shows how to prove it. Schema mechanics (checks, brands, transformations) live in Schema.
Reach for it when describing a single route's typed inputs and outputs — the atom every HttpApi is built from.
Named bundle of related endpoints sharing a path prefix, middleware, and OpenAPI metadata. HttpApiGroup.make("comp").add(...endpoints) collects endpoints; .prefix("/comp") mounts them; .middleware(Authorization) applies middleware to the group; .annotateMerge(OpenApi.annotations(...)) adds docs. Pass { topLevel: true } to flatten a group's endpoints onto the root of the derived client.
Mental model. The unit of organization and shared policy. In the derived client, a group becomes a namespace (client.comp.getComp()) unless topLevel, in which case methods sit at the root (client.health()).
Fragment · Type-checked with fixture
ts
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"import { Authorization } from "./Authorization.ts"const getComp = HttpApiEndpoint.get("getComp", "/employees/:id")const postRaise = HttpApiEndpoint.post("postRaise", "/employees/:id/raise")const postGrant = HttpApiEndpoint.post("postGrant", "/employees/:id/grants")// Our CompGroup: read comp, post a raise, record an equity grant.export class CompGroup extends HttpApiGroup.make("comp") .add(getComp, postRaise, postGrant) .middleware(Authorization) // auth for every endpoint in the group .prefix("/comp") // mount all under /comp .annotateMerge(OpenApi.annotations({ // group-level docs title: "Compensation", description: "Read comp, record raises, and grant equity" })) {}// A top-level group flattens onto the client root: client.health()export class SystemApi extends HttpApiGroup.make("system", { topLevel: true }).add( HttpApiEndpoint.get("health", "/health", { success: HttpApiSchema.NoContent })) {}
Reach for it when grouping endpoints that share a prefix or auth, or wanting a clean namespace in the generated client.
Root value tying groups into one API. HttpApi.make("my-api").add(GroupA).add(GroupB) builds it; .annotateMerge(OpenApi.annotations(...)) adds top-level docs (title, version, license). This single object is what you serve, generate clients from, and produce OpenAPI specs from.
Mental model. Table of contents and source of truth. Everything downstream — server routes, typed client, docs — is derived from it; the contract can't drift.
Fragment · Type-checked with fixture
ts
import { HttpApi, OpenApi } from "effect/http-api"import { CompGroup } from "./Comp.ts"import { SystemApi } from "./System.ts"export class Api extends HttpApi.make("comp-api") .add(CompGroup) .add(SystemApi) .annotateMerge(OpenApi.annotations({ title: "Acme Compensation API" })) {}
HttpApi.ParseOptions sets the Schema parse options (onExcessProperty, errors) that the server and the derived client use for every codec of an endpoint: path, query, headers, payload, success, errors, and SSE events. Annotate the API, a group, or an endpoint with .annotate(HttpApi.ParseOptions, options). The most specific level wins and replaces the whole object (options are not merged), and without an annotation Schema's defaults apply (onExcessProperty: "ignore"). Annotate the API before passing it to HttpApiBuilder.group or HttpApiBuilder.endpoint.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"const RaiseInput = Schema.Struct({ amount: Schema.Finite, effectiveDate: Schema.String })// Reject unknown request fields (a mistyped `efectiveDate` is a 400, not a silent drop)// and report every issue instead of the first one.export class RaisesApi extends HttpApi.make("raises").add( HttpApiGroup.make("raises").add( HttpApiEndpoint.post("propose", "/raises", { payload: RaiseInput }) )).annotate(HttpApi.ParseOptions, { onExcessProperty: "error", errors: "all" }) {}
With that annotation a POST carrying an extra property gets 400; without it the property is dropped and the handler runs.
ParseOptions is the fallback for six slot-specific annotations: ParamsParseOptions, QueryParseOptions, HeadersParseOptions, PayloadParseOptions, SuccessParseOptions, and ErrorParseOptions. Each one configures only its slot and, when unset, falls back to ParseOptions. Header codecs receive all request headers, so a blanket onExcessProperty: "error" also rejects undeclared ones such as content-type. Keep strict body parsing while leaving transport headers alone by overriding just that slot:
HttpApi.RedactedNames handles values that are only sometimes secret: query parameters and headers you do not want to model as Redacted, but that must not appear in traces. Annotate the API, a group, or an endpoint with .annotate(HttpApi.RedactedNames, { query?, headers? }). Names are wire names after encoding, matched like Headers.CurrentRedactedNames (strings case-insensitively, regular expressions by test), and a string query name also covers bracketed nested keys such as buildargs[NPM_TOKEN]. For that endpoint they extend UrlParams.CurrentRedactedNames and Headers.CurrentRedactedNames in the HttpApiClient request span and the HttpApiBuilder server span, including failures from middleware and request decoding. The API, group, and endpoint lists are combined; the values sent and decoded are unchanged.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { HttpApi, HttpApiEndpoint } from "effect/http-api"// A signed export link and a delegation header: keep both out of client and server spans.export const exportPayroll = HttpApiEndpoint.get("exportPayroll", "/payroll/export", { query: { signature: Schema.optional(Schema.String) }, headers: { "x-delegated-for": Schema.optional(Schema.String) }}).annotate(HttpApi.RedactedNames, { query: ["signature"], headers: ["x-delegated-for"]})
Two limits: HttpApi.addHttpApi copies the added API's annotations onto its groups like any other annotation, so a group that sets its own RedactedNames replaces the API's list instead of extending it — repeat the names on the group; and only URL and header span attributes use them, so user_agent.original and span error messages are recorded as is.
Reach for it when assembling groups into the one definition that drives server, client, and docs.
Toolkit for describing HTTP-specific facets of a schema: status codes, content types, empty responses, and streaming. HttpApiSchema.status(code) pins a status; NoContent/Created/Accepted are ready-made empty responses; asText({ contentType }) serves a string as text/CSV/etc.; asNoContent({ decode }) turns an error into a bodyless response; asMultipart marks a payload as multipart upload; StreamUint8Array/StreamSse describe streaming bodies (raw bytes or Server-Sent Events).
Mental model. Domain Schemas describe shape; HttpApiSchema annotations describe how that shape rides on HTTP. Pipeable wrappers — MySchema.pipe(HttpApiSchema.status(201)) — bolt HTTP semantics onto a plain Schema without changing its decoded type.
Fragment · Type-checked with fixture
ts
import { Schema } from "effect"import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api"import { CompRecord } from "./domain/Comp.ts"// Content negotiation: the same roster either as JSON OR as a CSV export.const exportComp = HttpApiEndpoint.get("exportComp", "/export", { payload: { departmentId: Schema.String }, success: [ Schema.Array(CompRecord), Schema.String.pipe(HttpApiSchema.asText({ contentType: "text/csv" })) ]})// A streamed bytes response with a pinned status and custom content type// (e.g. a generated comp-band report).const download = HttpApiEndpoint.get("download", "/report", { success: HttpApiSchema.status(206)( HttpApiSchema.StreamUint8Array({ contentType: "application/octet-stream" }) )})// Response headers are part of the contract, visible to handlers and clients.const PaginatedComp = HttpApiSchema.WithHeaders( Schema.Array(CompRecord), { "x-total-count": Schema.FiniteFromString, "x-next-page": Schema.optionalKey(Schema.String) })const page = HttpApiSchema.withHeaders({ body: [] as ReadonlyArray<typeof CompRecord.Type>, headers: { "x-total-count": 0 }})
HttpApiSchema.status takes a numeric code or a status literal name from HttpStatus: RaiseInput.pipe(HttpApiSchema.status("Created")) and HttpApiSchema.status(201) annotate the same thing, and the name survives code review better than a bare number.
WithHeaders(bodySchema, headersSchema) makes the success/client value a branded { body, headers } pair and works for streaming success bodies too. For a domain error that should remain the handler's error type while encoding selected fields into HTTP headers, pipe it through encodeToWithHeaders({ body, headers }, { decode, encode }). Nesting WithHeaders is rejected. Explicit content-type or content-length values in the returned headers override values inferred from the body; endpoint construction also rejects ambiguous response variants sharing the same status/content type.
In StreamSse({ data }) mode each event is { id?, event, data }, and data is encoded with the schema's JSON codec before it is stringified, so Schema.Date, Schema.BigInt, or Schema.Option values round-trip through SSE and the OpenAPI document describes their JSON form. The id is optional in the TypeScript type and in the OpenAPI schema, and a decoded event without an id omits the key rather than carrying id: undefined. A custom events schema should declare the id as Schema.optional(Schema.String), not Schema.UndefinedOr(Schema.String). The server writes events through Sse.encoder, which strips CR and LF from id and event values (and NUL from id), so a handler echoing caller-supplied text into them cannot inject extra fields or events; multi-line data is split into data: lines as usual. The event name "effect/http-api/stream/failure" is reserved: it's how a mid-stream handler failure is encoded to the client, and defining your own events schema with that literal fails at endpoint-construction time. StreamSse({ ..., keepAlive: "15 seconds" }) makes the server write a : keepalive comment each time the interval passes while the response is open, stopping when the event stream ends; SSE clients ignore comment lines, so idle connections survive proxies and runtimes that close silent responses.
For code generators and other tooling that inspects declared response schemas (including those from HttpApi.reflect), HttpApiSchema.getResponseEncodingSchema(schema) returns the buffered response encoding (defaulting to JSON, and for WithHeaders preferring the wrapper's encoding), and HttpApiSchema.getEncodeToWithHeadersParts(schema) returns the declared { body, headers } of an encodeToWithHeaders schema, or undefined. They read declarations, not the installed codecs: no-content schemas also report the JSON default (check isNoContent first), streaming and upgrade schemas are outside that contract, and a multipart encoding throws.
StreamUint8Array and StreamNdjson accept one content type or a list (contentType: ["application/x-ndjson", "application/jsonl"]): the first is the default response type, request streams are accepted under every entry, and OpenAPI lists each.
An endpoint can declare HttpApiSchema.StreamUint8Array({ maxBytes? }) or HttpApiSchema.StreamNdjson({ schema, maxBytes?, maxElementBytes? }) as its payload. The handler receives a lazy Stream that reads the body as it pulls (a decoded element stream for NDJSON). A malformed NDJSON line fails the stream with HttpApiSchemaError (400); exceeding maxBytes or maxElementBytes (1 MiB by default) fails it with HttpApiPayloadTooLarge (413), and a content-length over maxBytes is rejected before the handler runs. HttpApiClient sends a Stream payload without buffering it, HttpApiTest passes it through, and OpenApi.fromApi marks the body with x-effect-stream. StreamNdjson also works as a success response.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api"const Punch = Schema.Struct({ employeeId: Schema.String, at: Schema.String })// Bulk time-clock import: one JSON object per line, never buffered whole.export const importPunches = HttpApiEndpoint.post("importPunches", "/punches/import", { payload: HttpApiSchema.StreamNdjson({ schema: Punch, maxBytes: "100 MiB" }), success: Schema.Struct({ imported: Schema.Number })})
HttpApiSchema.Upgrade({ protocol, headers? }) declares a raw HTTP/1.1 upgrade (not WebSocket, which it rejects). Requests without matching Connection: Upgrade / Upgrade headers get 426 Upgrade Required before the payload is decoded. The endpoint may declare a buffered payload (not a streaming one), which is read before the 101, and may list ordinary successes next to the upgrade, for a server that declines. The handler receives an upgrade function rather than a socket: upgrade(), or upgrade({ headers }) when headers are declared, which yields the Socket; returning a success value after calling it is a defect. The client returns { headers, socket } for a 101, and HttpApiClient.isUpgraded(result) tells it apart from an ordinary success. The client closes the connection if the 101 headers fail to decode or the call is interrupted while taking it. Bun and Deno servers support only WebSocket upgrades.
Migration: handlers that read socket from the request now call upgrade(). Hand-built HttpApiClient.Upgraded values (for example in client mocks) must include [HttpApiClient.UpgradedTypeId]: HttpApiClient.UpgradedTypeId, and third-party HttpServerRequest implementations must add upgradeWith.
Reach for it when an endpoint needs a specific status, non-JSON content type, empty body, file upload, or streaming response.
Ready-made schema-typed errors for common HTTP failures: BadRequest, Unauthorized, Forbidden, NotFound, Conflict, UnprocessableEntity (422), RequestTimeout, InternalServerError, and more — each with the correct status code, plus *NoContent variants such as UnprocessableEntityNoContent for empty-body responses. Add to an endpoint's error list and fail with them like any yieldable error.
Mental model. Regular Schema.Error errors — they decode/encode across the wire, and a derived client gets them in its typed error channel automatically. For domain-specific failures, define your own Schema.TaggedError with an httpApiStatus.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { HttpApiError } from "effect/http-api"// Inside a handler: fail with a built-in error like any other.const handler = Effect.gen(function*() { const budgetApproved = false if (!budgetApproved) { return yield* new HttpApiError.Conflict() // 409 } return "ok"})
Note:Status codes on your own errors. Define the status on the class: class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", {}, { httpApiStatus: 404 }) {}. The third options argument is where HttpApi reads the code from.
Problem Details is opt-in; without it, built-in errors and decode failures produce the same responses as before.
HttpApiError.Problem<Self>()(tag, { type, status, title }, fields?) declares a typed problem as a yieldable Schema.Error class rendered, documented, and decoded as application/problem+json. Its _tag stays local (Effect.catchTag works without _tag on the wire); problems that share a status are told apart by type; extension fields are validated on both sides and cannot replace type, status, or title. Statuses below 500 are not reported to error reporters.
HttpApiSchema.asProblem({ title, type? }) renders a built-in error such as HttpApiError.NotFound as a problem (type defaults to about:blank).
HttpApiMiddleware.ProblemDetails, provided with HttpApiMiddleware.layerProblemDetails({ includeDetails? }), renders request decoding failures as a generic 400BadRequestProblem (with per-field errors only when includeDetails: true) and response encoding failures as a 500InternalServerErrorProblem, and declares both in OpenAPI and the client.
An HTTP status is a claim about what happened. Map every member of the public error union to the status that tells the truth, and let nothing else through.
Situation
Status
Produced by
A path, query, header, or payload value fails its Schema, or a JSON body does not parse
400, empty body (a 400 problem with Problem Details opted in)
HttpApi, before the handler runs
The request Content-Type matches no declared payload encoding
415, plain-text body
HttpApi, before the handler runs
No route matches
404, empty body
HttpRouter
Credential absent, malformed, expired, or revoked
401
your authentication middleware
Authenticated, but this actor may not perform this action on this tenant's resource
403
your use case or handler
The addressed resource does not exist
404
a declared error
State or idempotency conflict: duplicate key, stale version, raise already approved
409
a declared error
Well-formed input that current state rejects: salary outside the level's band
422
a declared error
A response encoding failure — the handler returned a value the declared success or error schema could not encode
500, empty body
HttpApi — reported to ErrorReporter
A defect — anything the endpoint did not declare
500, empty body
HttpApi — reported to ErrorReporter
The request fiber was interrupted: by a client disconnect / by the server itself
499 / 503
HttpServerError.causeResponse
Only a query that succeeded and returned nothing is "not found". A timeout, an exhausted pool, a permission error, or a malformed row is an infrastructure fault; rendering it as 404 or 409 makes clients act on a lie. Translate storage failures at the repository (SqlError) and let the rest become 500.
Do not Effect.die an expected failure to shrink a union. Convert to a defect only what no caller could act on at this edge — as the handler example does for a BandViolation that a read cannot produce. A BandViolation the UI must display belongs in the endpoint's error list.
Request decoding failures are unreported; response encoding failures are not. An invalid path param, query value, header, or payload body fails with 400 and the cause is not reported to ErrorReporter (it's a client mistake, not a server problem). A handler that returns a value the declared success or error schema cannot encode fails with 500 and is reported — it is a schema contract violation on the server side. The underlying HttpApiSchemaError is preserved as a defect so schema-error middleware (HttpApiMiddleware.layerSchemaErrorTransform) can still inspect it.
Defects are sanitized for you. A defect is answered with a content-free 500; the Cause goes to the server log and any configured ErrorReporter, never to the client. Do not add a catch-all that serializes error.message into the body.
Interruption is not a failure response. A disconnect interrupts the request fiber (499 is for your access log only — nobody receives it); do not catch it, retry it, or count it as an error rate.
The implicit 400 is not in the contract until you declare it.OpenApi.fromApi lists only declared statuses, and a derived client sees an undeclared 400 as an HttpClientError. Add HttpApiError.BadRequestNoContent to error wherever inputs are validated; the client then fails with a typed BadRequest and the document lists 400. To answer decode failures with your own body instead, implement a middleware with HttpApiMiddleware.layerSchemaErrorTransform(service, (schemaError, { endpoint, group }) => ...).
A public error value is an output surface. Every field of a declared error is serialized to clients and copied into telemetry. Give public errors a stable tag plus safe identifiers; keep cause, driver messages, SQL text, stack traces, and anything Redacted on internal errors only.
When a use case fails with a union wider than the endpoint declares, translate it with an exhaustive matcher so that a new member is a compile error rather than a silent 500:
Fragment · Type-checked
ts
import { Data, Effect, Match, Schema } from "effect"class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()( "EmployeeNotFound", { employeeId: Schema.String }, { httpApiStatus: 404 }) {}class RaiseAlreadyApproved extends Schema.TaggedError<RaiseAlreadyApproved>()( "RaiseAlreadyApproved", { raiseId: Schema.String }, { httpApiStatus: 409 }) {}// Internal: carries a driver cause, so it is never declared on an endpoint.class RepositoryError extends Data.TaggedError("RepositoryError")<{ readonly operation: string readonly cause: unknown}> {}type ApproveFailure = EmployeeNotFound | RaiseAlreadyApproved | RepositoryError// No wildcard branch: adding a member to ApproveFailure stops this from compiling.const toPublicError = Match.type<ApproveFailure>().pipe( Match.tagsExhaustive({ EmployeeNotFound: (error) => Effect.fail(error), RaiseAlreadyApproved: (error) => Effect.fail(error), // The HTTP edge is the last owner of an infrastructure fault: a sanitized 500, // with the full Cause in the server log. RepositoryError: (error) => Effect.die(error) }))declare const approveRaise: (raiseId: string) => Effect.Effect<void, ApproveFailure>// Effect<void, EmployeeNotFound | RaiseAlreadyApproved>export const approveRaiseHandler = (raiseId: string) => approveRaise(raiseId).pipe(Effect.catch(toPublicError))
Reach for it when an endpoint needs a standard HTTP error without hand-rolling the status mapping.
The RFC 9457 value layer underneath HttpApi's problem support, usable from a plain HttpRouter too. ProblemDetails.contentType is application/problem+json, blankType is about:blank, ProblemDetails.Schema is a lenient codec for a problem object (type, status, title, detail, instance, plus extension members) that follows RFC 9457 when decoding (a missing type becomes about:blank, wrong-typed standard members are dropped, unknown members are kept as extensions), and ProblemDetails.toResponse(problem) builds the application/problem+json response with the problem's status (or 500 when absent).
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { HttpRouter, ProblemDetails } from "effect/http"export const MaintenanceRoute = HttpRouter.add("POST", "/payroll/run", () => Effect.succeed(ProblemDetails.toResponse({ type: "https://comp.acme.internal/problems/maintenance", status: 503, title: "Payroll runs are paused for maintenance." })))
Declarative security schemes: HttpApiSecurity.bearer (Authorization: Bearer), apiKey({ key, in }) (header/query/cookie), basic (HTTP Basic). Attach to a middleware definition; HttpApi extracts and decodes the credential from each request (handing it to middleware as a Redacted value) and emits the matching securityScheme into the OpenAPI doc so the "Authorize" button works in Swagger/Scalar.
Warning:A security scheme extracts and documents; it verifies nothing. When the header, cookie, or query key is absent or malformed, the middleware still runs and receives an empty credential (Redacted.make(""), or an empty username/password for basic). Rejecting it — and checking signature, expiry, issuer, audience, and revocation — is the middleware's job.
Reach for it when protecting endpoints and wanting both runtime credential extraction and accurate security docs from one declaration.
Middleware for the declarative world, defined as a typed service. HttpApiMiddleware.Service declares what the middleware provides to downstream handlers (e.g. a CurrentUser service), what it requires, the error it can raise, and an optional security scheme. The definition lives next to the API (no implementation); the server supplies a Layer that implements it; clients supply a layerClient to inject credentials.
Mental model. Auth-as-a-service. Because middleware can provide a service, an auth middleware can decode a bearer token and inject the authenticated user into context — downstream handlers just yield* CurrentUser. The provides/requires types are tracked: forgetting to wire a middleware is a compile error, not a runtime failure.
Fragment · Type-checked with fixture
ts
import { Context, Schema } from "effect"import { HttpApiMiddleware, HttpApiSecurity } from "effect/http-api"import type { Employee } from "../domain/Comp.ts"// The service the middleware injects for downstream endpoints — the// authenticated HRBP/manager driving the comp change.export class CurrentUser extends Context.Service<CurrentUser, Employee>()( "comp/Authorization/CurrentUser") {}export class Unauthorized extends Schema.TaggedError<Unauthorized>()( "Unauthorized", { message: Schema.String }, { httpApiStatus: 401 }) {}// Definition only — no implementation here.export class Authorization extends HttpApiMiddleware.Service<Authorization, { provides: CurrentUser // downstream handlers can read CurrentUser requires: never}>()("comp/Authorization", { requiredForClient: true, // clients must inject credentials too security: { bearer: HttpApiSecurity.bearer }, error: Unauthorized}) {}
The server implements it as a Layer — validates the credential and provideServices the context:
Fragment · Type-checked with fixture
ts
import { Effect, Layer, Redacted } from "effect"import { Authorization, CurrentUser, Unauthorized } from "./Authorization.ts"import { Employee, EmployeeId } from "../domain/Comp.ts"export const AuthorizationLayer = Layer.effect( Authorization, Effect.gen(function*() { return Authorization.of({ bearer: Effect.fn(function*(httpEffect, { credential }) { if (Redacted.value(credential) !== "hrbp-token") { return yield* new Unauthorized({ message: "Invalid bearer token" }) } // Inject the user for every endpoint that runs after this middleware. return yield* Effect.provideService( httpEffect, CurrentUser, new Employee({ id: EmployeeId.make(1), name: "Dana HRBP", level: 6, baseSalary: 0 }) ) }) }) }))
The AuthorizationLayer above compares the token with a literal to keep the wiring visible. A real one answers two questions, with two owners and two statuses. Authentication ("who is calling?") belongs to the middleware and fails with 401. Authorization ("may this actor do this, to this resource, in this tenant?") belongs to the use case and fails with 403. Holding a valid token, reaching a route, or appearing in the OpenAPI document authorizes nothing.
Step
Owner
Rule
Extract the credential
HttpApiSecurity scheme
Keep it Redacted; call Redacted.value only inside the verifier.
Verify it
middleware, through a verifier service
Signature or opaque-token lookup, expiry, issuer/audience, revocation. An empty or invalid credential is one non-revealing 401.
Provide a principal
middleware (provides)
A narrow, decoded value — actor id, tenant, permissions — never the raw token or unverified claims.
Authorize the operation
use case or handler
Check the concrete actor · action · tenant · resource on every call; fail with a declared 403.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, type Redacted, Schema } from "effect"import { HttpApiMiddleware, HttpApiSecurity } from "effect/http-api"// What handlers may know about the caller: verified facts only.export class CurrentPrincipal extends Context.Service<CurrentPrincipal, { readonly actorId: string readonly tenantId: string readonly permissions: ReadonlySet<string>}>()("comp/CurrentPrincipal") {}export class Unauthenticated extends Schema.TaggedError<Unauthenticated>()( "Unauthenticated", {}, { httpApiStatus: 401 }) {}export class Forbidden extends Schema.TaggedError<Forbidden>()( "Forbidden", {}, { httpApiStatus: 403 }) {}export class Authentication extends HttpApiMiddleware.Service<Authentication, { provides: CurrentPrincipal}>()("comp/Authentication", { security: { bearer: HttpApiSecurity.bearer }, error: Unauthenticated}) {}// The verifier is a capability: a JWKS check, a session lookup, or a test fake.export class TokenVerifier extends Context.Service<TokenVerifier, { readonly verify: ( token: Redacted.Redacted<string> ) => Effect.Effect<CurrentPrincipal["Service"], Unauthenticated>}>()("comp/TokenVerifier") {}export const AuthenticationLive = Layer.effect( Authentication, Effect.gen(function*() { const verifier = yield* TokenVerifier return Authentication.of({ // A missing header arrives here as an empty credential; the verifier must reject it. bearer: Effect.fn(function*(httpEffect, { credential }) { const principal = yield* verifier.verify(credential) return yield* Effect.provideService(httpEffect, CurrentPrincipal, principal) }) }) }))// Authorization runs per operation, against the resource the request names.export const authorize = Effect.fn("authorize")(function*(action: string, tenantId: string) { const principal = yield* CurrentPrincipal if (principal.tenantId !== tenantId || !principal.permissions.has(action)) { return yield* new Forbidden() } return principal})
A handler for POST /tenants/:tenantId/raises/:id/approve starts with yield* authorize("raise:approve", params.tenantId) and declares Forbidden in the endpoint's error. A request with no Authorization header and an invalid :id gets 401, not 400, because middleware wraps request decoding — an unauthenticated caller learns nothing about your validation rules; a valid token with the wrong tenant or a missing permission gets 403, and the handler body never runs.
Declare a middleware's error once, on the middleware. It reaches the derived client's error channel and the OpenAPI responses of every endpoint it covers; repeating it on each endpoint is noise.
Never infer authorization from route possession, a documented security scheme, an unverified claim, a phantom type, or a cast. Audit system actors and "internal" bypass paths the same way as user calls.
Test every denial independently: no credential, bad credential, wrong tenant, missing permission, and the success path each get their own assertion, plus one that a secret canary appears in neither the response body nor the captured log output.
If the 401 needs a WWW-Authenticate challenge, fold the header into the error with HttpApiSchema.encodeToWithHeaders (see HttpApiSchema).
Reach for it when you need auth (or any cross-cutting concern) that both decodes credentials and provides typed context to handlers, with wiring checked at compile time.
The server side — where handlers are implemented. HttpApiBuilder.group(api, "comp", build) gives a typed handlers object whose .handle("name", impl) only accepts endpoints in that group, with inputs (params, query, payload) already decoded and return type constrained to the endpoint's success/error. HttpApiBuilder.layer(api, { openapiPath }) turns the implemented API into router routes (and optionally publishes the OpenAPI JSON).
Mental model. The contract enforcer. You can't implement a nonexistent endpoint, return the wrong type, or omit one — the types prevent it. Inputs arrive validated; focus purely on business logic.
For a larger group, handlers.handleAll({ endpointId: handler, ... }) registers an exhaustively typed identifier-keyed object in one call. It avoids a long fluent chain while preserving the same duplicate/missing-handler checks.
Fragment · Type-checked with fixture
ts
import { Effect, Layer } from "effect"import { HttpApiBuilder } from "effect/http-api"import { Api } from "../../api/Api.ts"import { CurrentUser } from "../../api/Authorization.ts"import { CompService } from "../CompService.ts"export const CompApiHandlers = HttpApiBuilder.group( Api, "comp", Effect.fn(function*(handlers) { const comp = yield* CompService // your comp/HRIS service return handlers // Inputs are already decoded: `params`, `payload` are typed. .handle("getComp", ({ params }) => // EmployeeNotFound is declared on the endpoint, so let it through; // anything unexpected becomes a 500. comp.getComp(params.id).pipe( Effect.catchTag("BandViolation", Effect.die) )) .handle("postRaise", Effect.fn(function*({ params, payload }) { // BandViolation (salary outside the level's band) is a declared error. return yield* comp.recordRaise(params.id, payload) })) .handle("postGrant", ({ payload }) => comp.recordGrant(payload).pipe(Effect.orDie)) // The Authorization middleware provided CurrentUser — just read it. .handle("me", () => CurrentUser) })).pipe( Layer.provide([CompService.layer, AuthorizationLayer]))
HttpApiBuilder.handler(api, groupId, endpointId, f) defines one endpoint callback outside the group builder. It returns f unchanged, but infers the request shape, the allowed success and error types, and the callback's service requirements from the endpoint — so large groups can keep one handler per module and still register them with handlers.handle.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"class CompRecord extends Schema.Class<CompRecord>("CompRecord")({ employeeId: Schema.String, baseSalary: Schema.Finite}) {}class Api extends HttpApi.make("comp-api").add( HttpApiGroup.make("comp").add( HttpApiEndpoint.get("getComp", "/employees/:id/comp", { params: { id: Schema.String }, success: CompRecord }) )) {}declare const loadComp: (employeeId: string) => Effect.Effect<CompRecord>// `params.id` is a string and the result must be a CompRecord — no annotations needed.export const getComp = HttpApiBuilder.handler(Api, "comp", "getComp", ({ params }) => loadComp(params.id))export const CompHandlers = HttpApiBuilder.group(Api, "comp", (handlers) => handlers.handle("getComp", getComp))
Assemble the server: provide each group's handler Layer to HttpApiBuilder.layer, mount docs, and serve.
HttpApiBuilder.layer rejects two endpoints with the same method and path, naming both; declare request variants of one operation as a single endpoint with a payload union. An undeclared error that implements HttpServerRespondable renders its own response when error-schema encoding fails (oversized multipart streaming uploads answer 413), while declared error schemas keep precedence.
A handler translates one decoded request into one use-case call and returns the Effect. Keep everything else out.
Return an Effect; never run one. No Effect.runPromise, no ManagedRuntime, no nested runtime inside a handler — the request fiber must own the work so that a disconnect or shutdown interrupts it (HTTP Server shows the proof).
Depend on use-case services, not infrastructure. A handler that yields SqlClient or builds an HttpClient has absorbed persistence and tenancy policy that no other entry point (RPC, CLI, workflow) will share.
Keep public DTOs separate from persistence models. The endpoint's success schema is a published contract; a table row is not. Map between them in the use case or repository.
Fully typed client derived from your API definition — no codegen. HttpApiClient.make(Api, { transformClient }) produces an object mirroring your groups and endpoints: client.comp.getComp({ params: { id } }) returns Effect<CompRecord, EmployeeNotFound | ...> with request encoding, middleware, and response decoding handled. Path params, query, and payload go under named keys: { params: { id }, payload: { ... } }. transformClient sets the base URL and adds retries by composing the underlying HttpClient.
Mental model. A live, type-level reflection of the server contract. Both sides share the one HttpApi value — renaming an endpoint or tweaking a field breaks client types immediately. If a middleware is requiredForClient, its layerClient must be provided to inject credentials.
Fragment · Type-checked with fixture
ts
import { Context, Effect, flow, Layer, Schedule } from "effect"import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"import { HttpApiClient, HttpApiMiddleware } from "effect/http-api"import { Api } from "./api/Api.ts"import { Authorization } from "./api/Authorization.ts"// Client-side implementation of the required Authorization middleware: inject a token.const AuthorizationClient = HttpApiMiddleware.layerClient( Authorization, Effect.fn(function*({ next, request }) { return yield* next(HttpClientRequest.bearerToken(request, "hrbp-token")) }))export class ApiClient extends Context.Service<ApiClient, HttpApiClient.ForApi<typeof Api>>()( "comp/ApiClient") { static readonly layer = Layer.effect( ApiClient, HttpApiClient.make(Api, { transformClient: (client) => client.pipe( HttpClient.mapRequest(flow(HttpClientRequest.prependUrl("http://localhost:3000"))), HttpClient.retryTransient({ schedule: Schedule.exponential(100), times: 3 }) ) }) ).pipe( Layer.provide(AuthorizationClient), // required because requiredForClient: true Layer.provide(FetchHttpClient.layer) // the underlying HttpClient implementation )}// Calling it is just Effect. Types mirror the API end-to-end.export const callApi = Effect.gen(function*() { const client = yield* ApiClient // Path params live under `params`; the result is typed CompRecord. const comp = yield* client.comp.getComp({ params: { id: 42 } }) yield* client.health() // SystemApi was topLevel -> method sits at the root return comp}).pipe(Effect.provide(ApiClient.layer))
Options and per-call controls worth knowing:
Need
Use
Point the client at a host or base path
HttpApiClient.make(Api, { baseUrl: "https://hr.acme.internal/api/v2" }) — shorter than a prependUrl transform
The status or headers as well as the decoded value
pass responseMode: "decoded-and-response" (a [value, response] tuple) or "response-only" in the call's request object; the default is "decoded-only"
A link or redirect target without executing a request
HttpApiClient.urlBuilder(Api, { baseUrl }) mirrors the client's shape and returns strings: urls.comp.getComp({ params, query }). Params and query are encoded through the endpoint schemas, and a base URL's pathname is kept
Stricter or exhaustive decoding of responses
the same HttpApi.ParseOptions annotation (or its per-slot variants) the server reads also configures the client's request encoders and response decoders
Decode a raw response later, for example after responseMode: "response-only"
HttpApiClient.decodeResponse(Api, { group, endpoint }) builds a reusable decoder that applies the endpoint's declared success and error schemas (undeclared statuses fail with a DecodeError described as undeclared status code); build it once and run it inside the scope that owns the response
A larger SSE event budget for one StreamSse endpoint
sseOptions: { maxEventSize } in that call's request object; the default cap is 10 MiB per pending event
The client decodes JSON, text, bytes, and form-urlencoded responses according to the endpoint's declared encoding. Request values are encoded through the endpoint schemas before anything is sent, so a value that violates a check fails locally with SchemaError: a typed client cannot produce malformed wire input, which is why boundary tests need a raw request (HttpApiTest).
Path parameters equal to . or .. are rejected so they cannot rewrite the request path through URL normalization, and path-parameter regex constraints are not emitted into client URLs or OpenAPI paths.
Reach for it when consuming an HttpApi from another service or frontend and wanting a typed client that can never silently drift from the server.
OpenAPI 3.1 generator and annotation toolkit. OpenApi.fromApi(api) returns a complete spec object derived from endpoints, schemas, errors, and security. OpenApi.annotations({ title, version, description, license, ... }) attaches metadata; services (OpenApi.Title, Version, Servers, Summary, Deprecated, Exclude, Transform) override anything down to a single parameter. When several security middlewares are stacked on an endpoint, the document requires all of them (one combined security requirement), matching the server; optional parameters and headers are not marked nullable, and includeAnnotationKey copies selected custom schema annotations (such as x-* vendor extensions) into the output.
Mental model. Docs are a projection of the same definition — not a parallel artifact kept in sync by hand. Because the spec comes from live Schemas, request/response shapes in the docs are always correct. Results are fresh clones even when the compiler cache is hit, so mutating one returned spec does not contaminate a later fromApi call.
Fragment · Type-checked with fixture
ts
import { OpenApi } from "effect/http-api"import { Api } from "./api/Api.ts"// The raw spec object — serve it, write it to a file, feed it to codegen tools.const spec = OpenApi.fromApi(Api)
Typically you don't call fromApi yourself — passing openapiPath to HttpApiBuilder.layer publishes it, and Swagger/Scalar layers consume it. Annotate at any level: HttpApi.make(...).annotateMerge(OpenApi.annotations({ title, version })) for the whole API, or equivalently on a group or endpoint.
Facts that decide how you use the document:
Each model owns its own artifact. A value Schema knows a shape, so Schema.toJsonSchemaDocument yields a JSON Schema for config validation, structured-output prompts, or cross-language payload codegen. Methods, paths, parameter locations, statuses, per-endpoint errors, security, and media types live only on the assembled HttpApi, so the OpenAPI document must come from OpenApi.fromApi. Feeding either generator the other model produces a document missing exactly the facts the other owns — and a JSON Schema is not "the OpenAPI".
Objects are closed here, open there.fromApi generates object schemas with onExcessProperty: "error", so struct bodies carry additionalProperties: false. A bare Schema.toJsonSchemaDocument call leaves objects open (additionalProperties: true) unless you pass the same option. Decoding is a separate matter: by default the server decodes with Schema's default parse options, so an unknown request property is dropped before the handler sees the payload, not rejected. To make the server enforce what the document advertises, annotate the API with HttpApi.ParseOptions{ onExcessProperty: "error" }.
QUERY operations sit under an extension. OpenAPI 3.1 has no query field, so fromApi emits an HttpApiEndpoint.query operation under paths[path]["x-oai-additionalOperations"].QUERY. Swagger UI, Scalar, and generators that do not read that extension will not show it; @effect/openapi-generator reads both the extension and OpenAPI 3.2's native query field.
Only identified schemas become components. A schema with an identifier annotation is emitted once under components.schemas and referenced by $ref; anonymous structs are inlined at each use. A Schema.Class named CompRecord appears as CompRecordEncoded, because the document describes the encoded side. Name the DTOs you want codegen tools to reuse.
Optionality mirrors the encoded schema. A path parameter, query parameter, or response header is marked optional in the document precisely when the corresponding field is optional on the schema's encoded side (Schema.optional, etc.) — the same flag that decoding uses, so the document never drifts from runtime behavior.
Generation is deferred. The openapiPath, Swagger, and Scalar routes build the document on the first request and memoize it, so startup stays cheap — and a generation defect (duplicate operationId, conflicting security scheme, invalid component key) surfaces on that first request, not at boot. Call OpenApi.fromApi(Api) in a test to move the failure into CI.
Overrides apply last. Endpoint-level OpenApi.Override and OpenApi.Transform annotations run after schema generation, so a transform sees — and may rewrite — the finished operation, including its generated request and response schemas.
Assert semantics, not snapshots. Check the facts a consumer depends on — path, method, parameter locations, security requirement, media types, each declared status — instead of snapshotting the whole document, whose key order and component layout are not a contract.
Official guide: Schema to JSON Schema — how identifier annotations become shared definitions (its "Generation Options" section describes an additionalProperties option; HttpApi uses onExcessProperty instead).
Reach for it when you need an OpenAPI document for external consumers, codegen, or API gateways — guaranteed to match what you actually serve.
Mounts Swagger UI for your API. HttpApiSwagger.layer(Api, { path: "/docs" }) serves the interactive Swagger explorer (with a working "Authorize" button if security is declared) at the chosen path, backed by the generated OpenAPI spec. Merge the Layer alongside your API routes.
Fragment · Type-checked with fixture
ts
import { HttpApiSwagger } from "effect/http-api"import { Api } from "./api/Api.ts"const SwaggerRoute = HttpApiSwagger.layer(Api, { path: "/docs" })
Reach for it when you want the familiar Swagger UI with zero extra wiring.
Same idea as Swagger, rendered with Scalar's modern API reference UI. HttpApiScalar.layer(Api, { path: "/docs" }) bundles the Scalar script inline; HttpApiScalar.layerCdn(Api, { path, version }) loads it from a CDN. Both serve the generated OpenAPI spec.
Scalar configuration supports authentication.preferredSecurityScheme (a scheme name, alternatives, nested combinations, or null) to choose the initially selected authentication UI. It changes the explorer's preference, not the API's security requirements or the server's credential verification.
Fragment · Type-checked with fixture
ts
import { HttpApiScalar } from "effect/http-api"import { Api } from "./api/Api.ts"const DocsRoute = HttpApiScalar.layer(Api, { path: "/docs" })
Reach for it when you want a modern docs page instead of Swagger UI — same effort, nicer result.
In-memory testing — no socket, no port. HttpApiTest.groups(Api, ["comp"]) wires selected groups' handlers to a generated client through the real request encoding, routing, response encoding, and client decoding pipeline, then returns the typed client. Call endpoints exactly as in production and assert on results. Unselected groups get placeholder handlers that fail if called, keeping tests scoped.
Mental model. Full HttpApi round-trip with the network removed — exercises schema validation, status mapping, and middleware for real, while staying fast and deterministic.
Fragment · Type-checked with fixture
ts
import { assert, it } from "@effect/vitest"import { Effect, FileSystem, Layer, Path } from "effect"import { Etag, HttpPlatform } from "effect/http"import { HttpApiTest } from "effect/http-api"import { Api } from "./api/Api.ts"import { CompApiHandlers } from "./server/Comp/http.ts"// HttpApiBuilder needs these platform services; FileSystem can be a noop in tests.const TestServices = Layer.mergeAll(Path.layer, Etag.layerWeak, HttpPlatform.layer).pipe( Layer.provideMerge(FileSystem.layerNoop({})))it.layer(TestServices)("Comp API", (it) => { it.effect("reads an employee's comp", () => Effect.gen(function*() { const client = yield* HttpApiTest.groups(Api, ["comp"]).pipe( Effect.provide(CompApiHandlers) ) const comp = yield* client.comp.getComp({ params: { id: 1 } }) assert.strictEqual(comp.employeeId, 1) }))})
HttpServer.layerServices is the ready-made equivalent of the TestServices Layer above (Path, a weak Etag generator, HttpPlatform, and a no-op FileSystem). The harness also runs registered pre-response handlers, so headers and cookies added with HttpEffect.appendPreResponseHandler or HttpApiBuilder.securitySetCookie are visible on the test response.
the built bundle or container, launched as in production
packaging, config, and startup
—
A direct call to a service method is evidence about that service, not about HTTP. To show where validation lives, send an invalid value over the raw wire and assert both the 400 and that the dependency behind the handler was never touched:
For a secured mutation, cover every declared status, and the tenant and permission denials independently; assert over the raw wire that a defect yields a content-free 500 (inside HttpApiTest a handler defect surfaces as a defect of the client call, so the rendered response is not visible there); and plant a canary secret to confirm it reaches neither the response body nor the captured log output.
Reach for it when testing handlers, schema round-trips, error mapping, or middleware — fast, faithful, without standing up a server.
Tip: Full arc: define endpoints with HttpApiEndpoint, bundle with HttpApiGroup, assemble with HttpApi; annotate HTTP facets with HttpApiSchema and errors with HttpApiError/HttpApiSecurity/HttpApiMiddleware; implement on the server with HttpApiBuilder and serve via HttpRouter; consume with the derived HttpApiClient; publish docs with OpenApi + HttpApiSwagger/HttpApiScalar; test in memory with HttpApiTest. One definition — every consumer in lockstep.
Typed operations for consuming a GraphQL API, not a GraphQL server framework. All seven effect/graphql modules are experimental: pin matching packages and re-audit on every upgrade. Prefer HttpApi for an Effect-owned HTTP contract, and RPC for an Effect-to-Effect procedure protocol.
query, mutation, and subscription describe a named document, variables, and a result Schema. Variables are encoded before sending; results are decoded before returning, so transformed scalars retain distinct decoded and wire types. The constructors do not validate a handwritten GraphQL document against a server schema: use the generator for that check. Variables, Result, Error, and Services project an operation's types. enumLiterals and otherTypename support generated enum and abstract-type schemas.
make(...operations) collects operations; merge(...groups) assembles a client surface. Method names come from operation names. Attach .middleware(Service) to an operation or a group. Group middleware run outside operation middleware, in attachment order within each level. Keep names unique when combining documents.
Reach for it when exposing only the operations an application capability needs.
make(group) acquires the protocol and middleware implementations and produces one typed method per operation. Queries and mutations return Effects; subscriptions return Streams. Per-call headers and context let callers supply request-local data without capturing it at client construction.
By default, a response carrying GraphQL errors fails even when it also carries data. { partial: true } returns a PartialResult with decoded data when available and the errors alongside it; it does not make malformed data valid, and it never applies to a non-2xx HTTP response, which always fails (see GraphQLClientError). GraphQL non-null propagation still applies: a failed non-null field can null its nearest nullable ancestor, or all of data.
pages(method, { variables, connection }) lazily fetches forward cursor pages; items flattens their nodes. The method must declare a nullable string after variable, omitted from the supplied initial variables, and the selected connection must include pageInfo. items additionally needs nodes. A cap on pages limits requests, while a cap on items may fetch a whole last page. Retrying the entire Stream starts again from the beginning, not the last failed page.
Subscriptions reconnect after retryable failures using defaultSubscriptionRetry (or subscriptionRetry); the default respects retryAfter. Reconnection does not replay missed events. Ordinary queries and mutations do not acquire safe retry semantics just because their errors expose isRetryable: a mutation may already have committed.
makeTest and layerTest accept typed operation handlers for application tests without a transport. They bypass encoding, decoding, and middleware; they do not prove server validation, HTTP behavior, authentication, or subscription reconnection. Test those boundaries with a real protocol and controlled HTTP/socket responses instead.
Reach for it when executing operations, paging connections, or replacing a GraphQL dependency in a use-case test.
Catch the outer GraphQLClientError, then inspect reason._tag:
Reason
Boundary that failed
EncodeError
Variables could not be encoded; nothing sent.
DecodeError
A result did not match its Schema.
ResponseError
GraphQL errors, retaining raw data and error paths — including on a non-2xx response, even with data and { partial: true }.
TransportError
HTTP/socket/protocol failure, including responses that are not GraphQL envelopes and non-2xx GraphQL responses without errors (such as { data: null }).
PaginationError
Invalid or non-progressing cursor pagination.
The wrapper exposes isRetryable, retryAfter, response headers, and status when available. GraphQLError preserves extra JSON fields, including provider-specific error types. A call never succeeds on a non-2xx HTTP status. A GraphQL body with errors on such a status is a ResponseError; a GraphQL body without errors, or a non-GraphQL body, is a TransportError carrying the status, headers, and parsed Retry-After, so a retry policy built on isRetryable treats a 503 { "data": null } as retryable rather than as data. A data: null result without errors on a 2xx (or over WebSocket, which has no status) remains a DecodeError. Read provider rate-limit headers as well as isRetryable: a provider can report an exhausted budget in a GraphQL error with HTTP 200. Never retry mutations solely on this flag.
Reach for it when distinguishing schema defects, transport failures, provider errors, and rate limits.
Define a Service and provide its implementation as a Layer. Implementations have execute and subscribe; mapRequest transforms requests for both. Middleware can require request-local services and add its own typed errors to calls. It sees raw execution results from next, including GraphQL errors, before client result decoding; transport failures fail next instead. This is client middleware: adding a bearer token is not verifying it on the server.
Reach for it when attaching credentials, recording rate-limit headers, or applying replay-safe per-operation policy.
layerHttp({ url }) uses an HttpClient for queries/mutations and HTTP SSE subscriptions; layerWebSocket supplies the WebSocket transport. Supply a Socket constructor/host layer appropriate to the runtime. The WebSocket protocol is graphql-transport-ws, not the older subscriptions-transport-ws protocol.
The HTTP url may also be a function evaluated per request with the call's services, or an Effect<string>. This supports per-tenant endpoints without constructing one global client per tenant. That overload uses HTTP/SSE only: combining HTTP with subscriptions.webSocket requires a static string URL. Resolver batching partitions by the resolved URL; it must not combine calls to different endpoints. A URL partition is not an authorization partition: still key batching by every request-local identity the middleware reads.
Reach for it when choosing HTTP/SSE versus WebSocket or routing calls to request-dependent endpoints.
ordered maps a list result to input keys by position; findById matches returned objects by a key. request(resolver) turns either into a lookup function participating in Effect request batching. path selects the result list and typename narrows abstract results. Missing/null/wrong-type entries fail their own lookup with NoSuchElementError; errors with an entry-specific GraphQL path can fail just that entry, while transport, decoding, or unscoped GraphQL errors fail the batch. Bound batch size to the server's actual list/page limit; a truncated result must not silently become “not found.” Batch limits apply independently per resolved protocol URL and batchKey, so interleaved lookups for different tenants do not fragment each other's batches, and each lookup's URL is resolved in its calling fiber.
aliased combines generated document templates into one request, renaming variables and root fields, then decodes each slice with its operation Schema. Equal encoded variables share a slice; the default cap is ten slices. Handwritten document strings lack the generator's rename metadata. Pathless errors fail all slices; non-null propagation can also destroy shared data. Middleware sees the batched request.query, so persisted-document allowlists or signatures must account for the rewritten document.
When middleware requires a per-call service, supply the required batchKey derived from that service so different users or tenants cannot share a call. Context References with defaults do not appear in the requirement channel: do not assume this type check discovers every hidden identity dependency.
Reach for it when replacing N+1 GraphQL calls with bounded, identity-aware request batches.
pkg @effect/graphql-generator — provides the graphqlgen CLI and public tool modules through subpath exports; there is no package-root entry point. bin, main, and internal/* are not public imports. Pin it with effect and its @effect/platform-node peer to the same release.
Self-contained source · Type-checked
ts
// The generator configuration API is intentionally experimental too.// @effect-diagnostics experimentalApiUsage:offimport { defineConfig } from "@effect/graphql-generator/Config"export default defineConfig({ schema: "./schema.graphql", documents: ["src/**/*.graphql"], scalars: { DateTime: "effect/Schema#DateTimeUtcFromString" }, importExtension: ".ts"})
Run graphqlgen, graphqlgen --watch, or graphqlgen --check (CI, no writes); --config selects a different config. One config targets one SDL or introspection schema. The CLI imports TypeScript configuration directly, so on Node (22.19+, the @effect/platform-node peer's minimum) keep the config to erasable syntax, or use Bun/Deno. Document globs are relative to the config and reject absolute patterns.
For programmatic tooling, @effect/graphql-generator/Generator.generate(config, { cwd }) returns generated files, stale-file deletions, and diagnostics in memory, requiring FileSystem and Path; it does not write files itself. Error diagnostics leave the returned file/deletion lists empty. This is the public generator entry point; do not import its parser/emitter internals.
The generator validates documents and writes sibling .graphql.ts / .gql.ts modules plus a shared schema module. Generated exports include operations, a group, fragment schemas, and named decoded interfaces. Object selections, ordinary input objects, and object fragments use a Schema.Struct const with a same-named interface, rather than the earlier Opaque class shape; abstract unions and one-of inputs retain their specialized forms. Recursive input objects (filters with and / or) are generated rather than reported as unsupported. Use exported interfaces in explicit annotations when structural editor hovers become large.
Built-in Int is 32-bit, Float finite, and ID string. DateTime defaults to a UTC DateTime codec and URI to string; unmapped custom scalars fall back to Schema.Json with a warning. Scalar mappings name an exported Schema codec (module#export): generation does not prove that module exists, so compile the output too.
Commit generated files, exclude them from formatting, and gate drift with --check. Successful generation removes only orphan document outputs carrying the matching generated header, not arbitrary files or the shared module. Watch mode installs watchers before its initial generation, preserves last-good output on errors, and does not reload modules imported by the config: restart after changing those modules.
Reach for it when consuming an existing schema with many operations, fragments, custom scalars, subscriptions, or aliased batching.
Effect 4's RPC is schema-first and transport-agnostic. One contract — a group of procedures, each with payload/success/error Schema — derives a server, a typed client, and a test harness. Wire format and transport are pluggable layers. The contract never changes.
Note: Thirteen modules; three core nouns and adapters. Rpc + RpcGroup define the contract. RpcServer runs handlers; RpcClient derives the caller. RpcSerialization picks the wire encoding; the layerProtocol* functions pick the pipe. OpenRpc publishes the contract as a document. RpcMiddleware, RpcSchema, RpcMessage, RpcClientError, RpcWorker, RpcTest, and Utils are supporting modules.
One procedure. Rpc.make(tag, options) records a tag plus four Schemas: payload (request), success (happy result), error (typed recoverable failures), and optional defect for unexpected deaths.
Mental model. An Rpc is a typed envelope spec both ends agree on. The client reads it to know what to send and what comes back; the server reads it to know what to decode and must return. The declaration is pure data — no shared implementation, only this definition.
payload accepts a Schema or bare struct fields (auto-wrapped in Schema.Struct). Pass stream: true to make success a stream of values. Subclass to get a nominal type for yield* and annotation.
Type helpers project a group's union of RPCs: Rpc.ExtractTag<Rpcs, "GetComp"> selects one procedure, Rpc.ByTag<Rpcs> is the same union as an object keyed by tag (indexing it with a literal tag avoids testing every member, which keeps type-checking of large groups fast), and Rpc.SuccessChunk<Rpcs> is the element type of the streaming members, distributing over a union.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Rpc } from "effect/rpc"// Your typed, recoverable error — a normal Schema tagged error.class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { employeeId: Schema.String}) {}class Compensation extends Schema.Class<Compensation>("Compensation")({ employeeId: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), baseSalary: Schema.BigDecimal}) {}// A single procedure: payload in, Compensation out, EmployeeNotFound as the typed failure.const GetComp = Rpc.make("GetComp", { payload: { employeeId: Schema.String }, // struct fields are auto-wrapped in Schema.Struct success: Compensation, error: EmployeeNotFound})// Subclass form — gives you a nameable type and a place to hang annotations.class ProposeRaise extends Rpc.make("ProposeRaise", { payload: { employeeId: Schema.String, amount: Schema.BigDecimal }, success: Compensation}) {}
Tip:Rpc.fork(effect) forces a response to run concurrently regardless of the server's concurrency setting; Rpc.uninterruptible(effect) runs it in an uninterruptible region. Both work on Effects and Streams. primaryKey: (payload) => string turns the payload into a keyed request (required by the cluster layer, useful for dedup/caching).
Warning:Defects cross the wire. Unlike HttpApi, which answers a defect with an empty 500, an RPC server serializes it: an Error's name, message, and cause travel to the peer (stacks are omitted unless a schema opts in). For example, Effect.die(new Error("connect postgres://comp:hunter2@db")) in a handler arrives at the client verbatim. By default the server treats a handler defect as fatal to the connection and encodes it with the generic Schema.Defect(); the per-procedure defect schema passed to Rpc.make is used only when the server runs with disableFatalDefects: true (see operational defaults). Keep secrets out of error messages, translate infrastructure failures before they can become defects, and for untrusted peers either catch defects in a group-wide middleware (Effect.catchDefect, log the original, die with a fixed value) or combine disableFatalDefects: true with a defect schema that encodes to a content-free value.
Reach for it when describing exactly one remote call with inputs, outputs, and failures captured as Schema.
A collection of Rpc definitions keyed by tag, forming the service contract. RpcGroup.make(...rpcs) builds it; .add, .merge, .omit, .prefix, .middleware, and .annotateRpcs shape it. Hand this single value to both server and client.
Mental model. The group is the interface; group.toLayer(handlers) is the implementation. The handlers object is exhaustively type-checked: every tag needs a handler receiving the decoded payload and returning an Effect (or Stream) whose success/error matches that procedure's Schemas. Missing tag or wrong return type fails to compile.
Every handler's second argument carries { client, requestId, headers, rpc } — connected client metadata, request id, inbound headers, and the RPC definition itself.
A handler may also fail with the declared error of the server middleware attached to its procedure, without repeating it in the procedure's own error schema; the error travels to the client like any middleware failure. A Deferred the handler returns can still fail only with the procedure's own error.
Migration: handlers obtained with RpcGroup.accessHandler now carry those middleware errors in their error type. Handle them, or widen an annotation that previously allowed only the procedure's own errors.
Note:group.merge(other) combines contracts; group.prefix("admin.") namespaces every tag; group.middleware(MyMiddleware) attaches a cross-cutting service to every procedure added so far. For one-off handler wiring: group.toLayerHandler("GetComp", fn).
The group is the wire protocol. Everything a peer can observe — the final tag (after prefix), the payload/success/error schemas, middleware errors, the defect policy, the serializer, and the framing — is versioned by deployment, not by the compiler, because client and server are rarely redeployed in the same instant.
Change
Compatible?
Do this
Add a procedure
yes, if old servers never receive it
deploy servers first; an unknown tag is answered with a defect (Unknown request tag: ...), not a typed error (probed)
Add an optional payload field with explicit decode semantics (Schema.optionalKey, a decoding default)
yes
deploy tolerant servers before clients that send it
Add a required payload field, tighten a check, rename or remove a field
no
a payload that fails to decode is answered with a defect carrying the formatted schema issue, and the handler never runs (probed) — add a new procedure instead
Add a member to error or to a success union
no for old clients
an old client cannot decode the new member; ship clients that know it first, then let servers produce it
Change a tag, a prefix, or what a stable tag means
no
introduce ApproveRaiseV2, keep the old tag through the rollback window, then remove it
Swap RpcSerialization, framing, or fingerprintPayloads
no
both peers must change together; bridge with a second endpoint
Give every final tag one stable identity.RpcGroup.add and merge keep a map keyed by tag, so a duplicate tag silently replaces the earlier definition (probed: merging two groups that both define GetComp leaves one, the later). Do not let merge order decide which procedure wins — prefix groups (group.prefix("comp.")) or assert uniqueness in a test.
Test the skew, not just the head. Keep a frozen copy of the previous release's group and exercise both mixed pairings (the previous client against the new server, and the new client against the previous server) through a real serializer; RpcTest cannot see these failures.
Schema-level techniques for tolerant evolution (optional keys, decoding defaults, unions of versions) are in Schema.
Reach for it when you want a single typed surface the server implements and the client mirrors.
The runtime that takes a group, its handler layer, a serialization layer, and a transport, and serves requests. Decodes incoming payloads with the procedure's Schema, runs the matching handler (and any middleware), tracks in-flight requests, honours acks and interrupts, encodes the result back to the client.
Mental model.RpcServer.layer(group) is the engine; it needs a Protocol (transport boundary) plus handlers in context. For the common case, RpcServer.layerHttp({ group, path, protocol }) bundles the engine and transport and registers a route on an HttpRouter. Pick wire format separately with a serialization layer — swapping JSON for SchemaBinary is one line.
Fragment · Type-checked with fixture
ts
import { Layer } from "effect"import { RpcSerialization, RpcServer } from "effect/rpc"import { HttpRouter } from "effect/http"import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"import { createServer } from "node:http"// Mount the CompRpc group at POST /rpc, over HTTP, framed as ndjson.const RpcRoute = RpcServer.layerHttp({ group: CompRpc, path: "/rpc", protocol: "http" // or "websocket" (the default)}).pipe( Layer.provide(CompLive), // your handlers Layer.provide(RpcSerialization.layerNdjson) // the wire format)// Serve it like any other HTTP app.const HttpLive = HttpRouter.serve(RpcRoute).pipe( Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })))NodeRuntime.runMain(Layer.launch(HttpLive))
Additional protocol layers: layerProtocolWebsocket, layerProtocolSocketServer (raw TCP), layerProtocolStdio (CLIs; for a Model Context Protocol server use McpServer.layerStdio from effect/ai, which builds on this RPC machinery — see Exposing an Effect Application over MCP), layerProtocolWorkerRunner (server half of a Worker). Compose RpcServer.layer(group) with any of them to use the engine without the HTTP router.
layerProtocolStdio is a module-level Layer, and Layers are memoized by reference within one graph: two stdio servers in the same graph share one Protocol bound to the first Stdio built. Wrap it in Layer.fresh, or build Layer.effect(RpcServer.Protocol, RpcServer.makeProtocolStdio) per server. When stdin closes and pending responses have drained, a stdio server exits with code 0, not as an interrupted (130) process.
Warning:layerHttp and layerProtocolHttp register their route on whichever HttpRouter is in context when their Layer is built — they don't bring their own router. HttpRouter.serve builds a fresh router in a forked layer memo map for each entrypoint, so that route is only reachable when RpcRoute (or the layer wrapping it) is passed directly into serve's own argument, as above. Pulling RpcRoute out from under serve and providing it to a router built elsewhere — for example via a separate Layer.provide(HttpRouter.layer) — builds against a private router that serve never mounts, so the route silently goes unserved.
Choosing a transport is choosing what you must prove before shipping it:
Transport
You own
Prove with a real peer
HTTP (protocol: "http")
body and frame limits, proxy buffering of streamed responses, cookies/CORS/CSRF
an aborted request interrupts the handler; an oversized body is refused; a streamed reply is not buffered whole by the proxy
WebSocket / socket
authentication and Origin check at upgrade, heartbeat (the client pings and treats a missed pong as a connection failure), idle and maximum connection lifetime, reconnect and re-subscribe, ack-based flow control
disconnect cleans up every in-flight handler; a reconnect does not double-apply a mutation
Worker
the initial-message handshake, ownership of transferred buffers, pool bounds, worker death
a crashed worker fails its own calls instead of hanging them, and calls on healthy workers in the pool keep running
stdio
strict framing, stdout reserved for the protocol (log to stderr), draining stderr, child-process ownership
a stray console.log in the server does not corrupt the stream
RpcServer.layer, layerHttp, and make share these options. Several defaults favor throughput over protection; choose each deliberately.
Option
Default
What it means
concurrency
"unbounded"
Every request starts its handler immediately. A number creates one server-wide Semaphore, so at most that many handlers run and the rest wait for a permit.
Rpc.fork(effect) in a handler
—
Skips that semaphore entirely (probed: with concurrency: 1, four plain calls ran one at a time and four forked calls ran all at once). Audit every use; reserve it for cheap control-plane calls (health, cancel) that must not queue behind slow work.
streamBufferSize (layerHttp, layerProtocolHttp)
16
A framed HTTP response stream buffers at most 16 encoded messages ahead of the socket and then backpressures the handler. "unbounded" disables the limit. Unframed layerJson responses are collected whole. A batch is dispatched while the response drains, so a batch whose rejected requests alone produce more replies than the buffer holds still completes.
disableFatalDefects
false
A handler defect is sent as a connection-level Defect: every in-flight call multiplexed on that client fails with it (probed with RpcTest). true confines it to the failing request and encodes it with the procedure's defect schema; a handler that throws synchronously is treated as a defect of that request too. Over the HTTP protocol each POST is its own client, so the blast radius is that request batch; over a WebSocket, socket, or worker it is the connection.
onRequest (make)
none
(effect, request) => effect, wrapping the effect that runs one decoded request: its middleware, its handler, and — when the handler returns its result directly — the response write. It runs inside the request's span (unless tracing is off) and is interrupted with the request. Use it for per-request context such as log annotations or metrics; a handler that succeeds with a Deferred leaves the wrapped effect before its reply is sent.
onDisconnect
none
(clientId) => Effect<void>, called per disconnect the Protocol reports, after the server has requested interruption of that client's in-flight requests (it does not wait for them). Each call runs in its own fiber; failures are logged, not propagated. Use it instead of taking from Protocol.disconnects, which would stop the server from interrupting the disconnected client's work. Not called for a clean end of input or for clients still connected at shutdown.
disableTracing, spanPrefix, spanAttributes
tracing on, no prefix
One span per call named by the RPC method tag (e.g. GetComp); pass spanPrefix: "RpcServer" to restore the old RpcServer.GetComp form. Spans record rpc.system.name: "effect_rpc" and rpc.method. The socket, WebSocket, stdio, and worker protocols carry the caller's trace context in the RPC envelope.
Five mechanisms are easy to conflate and do not substitute for each other: handler concurrency (concurrency), stream acks (the client acknowledges each chunk, pacing a streaming handler — on the socket, WebSocket, stdio, and worker protocols, not HTTP), transport backpressure (streamBufferSize, the socket), JSON-RPC batching (several messages in one frame), and RequestResolver batching inside a handler (Caching and batching). A capacity plan names a finite value for each of: body and frame bytes (maxFrameSize, maxBufferSize, and MaxBodySize for HTTP), connections and their maximum lifetime, in-flight calls, per-principal rate, stream queue depth, a server-side deadline for every call and stream (Effect.timeout in the handler or a middleware — a browser tab that closes cannot be relied on to send Interrupt), and the shutdown drain. It also states the overload behavior in one word: reject, queue, shed, or close.
Request lifetime is request-owned: when the client interrupts a call, or an HTTP client disconnects, the server interrupts the matching handler fiber and its finalizers run. Rpc.uninterruptible(effect) opts a handler out — use it only for a short critical section, because cancellation is not rollback: a mutation interrupted halfway needs a transaction (SQL transactions), not a hopeful client.
A request whose envelope headers are malformed is answered with a defect Exit for that request (a malformed notification is dropped) instead of failing the HTTP response or the connection.
Response-encoding failures are server failures too: the server records them on the RPC method span rather than silently losing observability after a successful handler. Keep the declared success Schema aligned with the actual value, and distinguish an encoding failure from a domain error or a client disconnect.
Reach for it when you are the callee and need to expose handlers over a real transport.
The mirror of the server, derived from the same group. RpcClient.make(group) returns an object with one method per procedure; calling client.GetComp({ employeeId }) returns an Effect with exactly the success and error types the group declared. No codegen, no duplicated types.
Mental model. The client encodes the payload, ships it through the current Protocol, decodes the response, and reconstructs typed errors so Effect.catchTag("EmployeeNotFound", ...) works on the calling side. Failures below the contract (connection dropped, malformed frame) surface as RpcClientError.
Fragment · Type-checked with fixture
ts
import { BigDecimal, Effect, Layer } from "effect"import { RpcClient, RpcSerialization } from "effect/rpc"import { FetchHttpClient } from "effect/http"// Transport: HTTP to the server's /rpc endpoint, ndjson on the wire.const ProtocolLive = RpcClient.layerProtocolHttp({ url: "http://localhost:3000/rpc"}).pipe( Layer.provide(RpcSerialization.layerNdjson), Layer.provide(FetchHttpClient.layer))const program = Effect.gen(function*() { // Derived from CompRpc — fully typed, same contract as the server. const client = yield* RpcClient.make(CompRpc) const comp = yield* client.GetComp({ employeeId: "E-1" }) // Compensation // Propose a raise; the typed errors from the contract are catchable here: const raised = yield* client.ProposeRaise({ employeeId: "E-1", amount: BigDecimal.fromBigInt(12000n) }).pipe( Effect.catchTag("BudgetExceeded", () => Effect.succeed(comp)), // keep current comp if over budget Effect.catchTag("EmployeeNotFound", ({ employeeId }) => Effect.die(`unknown employee ${employeeId}`) ) ) yield* Effect.log(`base now ${BigDecimal.format(raised.baseSalary)}`)}).pipe(Effect.scoped, Effect.provide(ProtocolLive))
Tip: Attach per-call headers with RpcClient.withHeaders(effect, { authorization: token }) — they merge with CurrentHeaders and ride on outgoing requests, readable by the handler via headers. Pass { flatten: true } to RpcClient.make to get a single client(tag, payload) function instead of a method-per-procedure object — useful for generic wrappers. Matching client transports: layerProtocolHttp, layerProtocolSocket, layerProtocolWorker. Socket clients accept pingInterval and pingTimeout options (both default to 5 seconds); any decoded server frame counts as liveness, so only a genuinely quiet connection triggers a ping.
discard: true waits for an acknowledgement. A non-streaming call made with { discard: true } completes once the server acknowledges it as its handler starts (after middleware has run), not when the request is written; the result and the handler's error are not returned, but transport errors, middleware errors, and failures before the handler starts still fail the call — at once, interrupting the pending send, so a discarded call over a disconnected socket fails instead of waiting to be sent (and run) after a reconnect. Over HTTP and workers it completes after the handler finishes. A discarded call is a Request message with discard: true; makeNoSerialization's onFromClient no longer receives a separate discard flag. layerProtocolHttp / makeProtocolHttp also accept an opt-in batch: { window, maxSize? } that sends concurrent requests from one client in a single HTTP request.
A custom RpcClient.Protocol owes every accepted request a reply. A Request that send accepts stays pending — holding the request and the caller's context — until a reply names its id: an Exit, or a ClientProtocolError whose requestIds lists it (one without requestIds fails every pending request). Only caller interruption, the client closing, or a connection failure releases it otherwise. A delivery-only transport, such as a message queue, writes a void Exit for a discard request once delivered and fails send with an RpcClientError for every other request.
With { flatten: true }, RpcClient.RpcClient.Options and RpcClient.RpcClient.Result name a call's options and result type for wrappers, and a streaming call made with asQueue: true dequeues with Cause.Done in its error type, as on the object-shaped client.
Socket heartbeat liveness is time since the last decoded server frame, not only the last pong. pingInterval defaults to five seconds and pingTimeout to that interval. A late scheduler tick sends a ping before declaring silence, avoiding premature timeouts after event-loop stalls. layerProtocolSocket({ onPingTimeout }) runs that no-error/no-services Effect on an open connection's timeout, before disconnect hooks and in-flight SocketReadError failures; hook defects are logged and ignored. This hook is distinct from onTransientError, which reports retried connection-open errors.
A call that fails with RpcClientError has an unknown outcome: the request may never have left, or the handler may have committed just before the connection dropped. Anything that sends it again — Effect.retry around the call, HttpClient.retryTransient inside layerProtocolHttp({ transformClient }), a user clicking twice, a socket client reconnecting with retryTransientErrors and the caller retrying — can apply the mutation twice. A missed heartbeat pong always fails every in-flight call on that connection, even with retryTransientErrors enabled and a reconnect under way — onTransientError is not invoked for it, only for a retried connection-open failure — so a pong timeout is exactly the kind of unknown-outcome failure this section is about. Reads are replay-safe; mutations need a protocol:
The caller mints one idempotency key per intent and reuses it on every retry. A payload id the server generates, or a fresh key per attempt, deduplicates nothing.
The server records the key and the outcome in the same transaction as the mutation, and on a repeat returns the recorded outcome instead of running again. An in-memory Set loses the ledger on restart and is wrong across replicas.
Decide what a key conflict means: the same key with a different payload is a caller bug — fail with a declared conflict error rather than returning the old result.
Or state the trade-off: "at most once, no retry" is a legitimate contract for a mutation, as long as the caller surfaces "outcome unknown" instead of guessing.
Fragment · Type-checked
ts
import { Context, Effect, Option, Schema } from "effect"import { Rpc, RpcGroup } from "effect/rpc"class RaiseApproval extends Schema.Class<RaiseApproval>("RaiseApproval")({ raiseId: Schema.String, approvedBy: Schema.String}) {}class IdempotencyConflict extends Schema.TaggedError<IdempotencyConflict>()("IdempotencyConflict", { requestKey: Schema.String}) {}export class ApprovalsRpc extends RpcGroup.make( Rpc.make("ApproveRaise", { // Minted once by the caller for this intent; identical on every retry. payload: { requestKey: Schema.String, raiseId: Schema.String }, success: RaiseApproval, error: IdempotencyConflict })) {}// A durable ledger: both methods run inside the use case's transaction.class MutationLedger extends Context.Service<MutationLedger, { readonly find: ( requestKey: string ) => Effect.Effect<Option.Option<{ readonly raiseId: string; readonly outcome: RaiseApproval }>> readonly record: (requestKey: string, raiseId: string, outcome: RaiseApproval) => Effect.Effect<void>}>()("app/MutationLedger") {}declare const approveRaise: (raiseId: string) => Effect.Effect<RaiseApproval>declare const inTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>export const ApprovalsLive = ApprovalsRpc.toLayer( Effect.gen(function*() { const ledger = yield* MutationLedger return { ApproveRaise: ({ raiseId, requestKey }) => inTransaction(Effect.gen(function*() { const previous = yield* ledger.find(requestKey) if (Option.isSome(previous)) { return previous.value.raiseId === raiseId ? previous.value.outcome // a retry: replay the recorded answer : yield* new IdempotencyConflict({ requestKey }) } const outcome = yield* approveRaise(raiseId) yield* ledger.record(requestKey, raiseId, outcome) // commits with the mutation, or not at all return outcome })) } }))
The error a derived client raises for a transport or protocol failure rather than a declared remote error. Its reason is a union of transport failures — HTTP client errors, socket errors, worker errors — plus RpcClientDefect for protocol violations and decode failures (e.g. empty or malformed response).
Mental model. Two error channels: contract typed errors (e.g. EmployeeNotFound) are application failures, catchable by tag. RpcClientError is infrastructure failure — it does not prove that the request was never sent or executed. A handler may commit before the connection drops or its response fails to decode, leaving the caller with an unknown outcome. Match on error.reason._tag to distinguish a dropped socket from a garbled frame, and use the mutation retry ledger before replaying a write. An HTTP transport failure arrives as an HttpError reason whose kind names the HttpClientError reason and whose message is taken from it, so the error reads as the underlying failure rather than a bare HttpError:.
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import { RpcClientError } from "effect/rpc/RpcClientError"const robust = client.GetComp({ employeeId: "E-1" }).pipe( Effect.catchTag("EmployeeNotFound", () => Effect.succeed(null)), // contract error // catchIf recovers only the matching failures; everything else stays in the error channel. Effect.catchIf( (e) => e instanceof RpcClientError && e.reason._tag === "RpcClientDefect", (e) => Effect.logError(`protocol problem: ${e.reason.message}`) ))
an invariant breach or a cancellation; not retryable, not a user-facing message
Collapsing these — mapping every failure to one "RPC failed" error, or retrying all of them — throws away the only information that says whether a retry is safe and whose bug it is.
Reach for it when you need to react to transport-level failures distinctly from contract business errors.
Cross-cutting concerns — auth, logging, rate limiting — modeled as a typed service attached to procedures. RpcMiddleware.Service<Self, { provides, requires }>()(name, { error }) declares middleware that can fail with a typed error and provides a service to the handlers behind it.
Mental model. Middleware wraps the handler and rewires type-level requirements. If auth middleware provides: CurrentManager, any handler under it may yield* CurrentManager and the compiler knows that dependency is satisfied. Attach with .middleware(M) on an individual Rpc or on an RpcGroup.
Self-contained source · Type-checked
ts
import { Context, Effect, Schema } from "effect"import { Rpc, RpcGroup, RpcMiddleware } from "effect/rpc"class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {}// The approving manager for this call. No default impl — the middleware supplies it.class CurrentManager extends Context.Service<CurrentManager, { readonly id: string}>()("app/CurrentManager") {}// Middleware that authenticates and PROVIDES CurrentManager to downstream handlers.class Authenticated extends RpcMiddleware.Service<Authenticated, { provides: CurrentManager}>()("app/Authenticated", { error: Unauthorized}) {}// A protected procedure; CurrentManager is satisfied by the middleware, not the handler.class WhoApproves extends Rpc.make("WhoApproves", { success: Schema.String}).middleware(Authenticated) {}const AuthedRpc = RpcGroup.make(WhoApproves)const AuthedLive = AuthedRpc.toLayer({ WhoApproves: () => Effect.map(CurrentManager, (m) => m.id) // CurrentManager is in scope})
Provide the server-side behaviour with a Layer.succeed(Authenticated)(...) whose value is a middleware function: receives the handler effect plus options (including request headers), reads the caller from headers, uses Effect.provideService to inject the provided service into the handler. RpcMiddleware.layerClient handles middleware that also needs to run on the client (e.g. signing a request) — declare with requiredForClient: true.
Fragment · Type-checked with fixture
ts
import { Effect, Layer } from "effect"// Server-side implementation: a function that wraps the handler and provides the service.const AuthedServer = Layer.succeed(Authenticated)( Authenticated.of((effect, options) => Effect.provideService(effect, CurrentManager, { id: options.headers["x-manager-id"] ?? "unknown" }) ))
Warning: The layer above shows only the wiring. It trusts a caller-supplied x-manager-id header and falls back to "unknown", which is acceptable behind a test harness and nowhere else: any client can type any manager id.
Client middleware attaches; only the server edge enforces
A client middleware (RpcMiddleware.layerClient) can attach a credential. It cannot enforce anything, because the peer may not be your client at all. Enforcement happens where the procedure is reachable:
Extract the credential from an allowed location — and still treat it as untrusted. Headers, connection ids, remote addresses, and forwarded fields are claims, not facts. Trust proxy-supplied identity only when the backend is unreachable except through that proxy.
Verify it cryptographically or resolve it against a session store; keep it Redacted until the verifier needs the bytes. Absent, malformed, expired, or revoked all fail with the same declared, non-revealing error.
Provide a decoded principal through provides — never the raw token.
Authorize per procedure against the concrete actor · action · tenant · resource, with a second declared error. A middleware annotation or a "this group is internal" comment is not an authorization check.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Redacted, Schema } from "effect"import { Headers } from "effect/http"import { Rpc, RpcGroup, RpcMiddleware } from "effect/rpc"class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {}class Forbidden extends Schema.TaggedError<Forbidden>()("Forbidden", {}) {}class CurrentManager extends Context.Service<CurrentManager, { readonly id: string readonly canApprove: boolean}>()("app/CurrentManager") {}class SessionVerifier extends Context.Service<SessionVerifier, { readonly verify: ( token: Redacted.Redacted<string> ) => Effect.Effect<CurrentManager["Service"], Unauthorized>}>()("app/SessionVerifier") {}class Authenticated extends RpcMiddleware.Service<Authenticated, { provides: CurrentManager}>()("app/Authenticated", { error: Unauthorized, requiredForClient: true // the derived client will not build without a client layer}) {}// Server edge: verify, then provide. No credential, no handler.export const AuthenticatedLive = Layer.effect( Authenticated, Effect.gen(function*() { const verifier = yield* SessionVerifier return Authenticated.of((effect, { headers }) => Effect.gen(function*() { const header = headers["authorization"] if (header === undefined || !header.startsWith("Bearer ")) { return yield* new Unauthorized() } const manager = yield* verifier.verify(Redacted.make(header.slice("Bearer ".length))) return yield* Effect.provideService(effect, CurrentManager, manager) }) ) }))// Client side: attach only. The token comes from a service, not a mutable global.class SessionToken extends Context.Service<SessionToken, Redacted.Redacted<string>>()( "app/SessionToken") {}export const AuthenticatedClient = RpcMiddleware.layerClient(Authenticated, ({ next, request }) => Effect.flatMap(SessionToken, (token) => next({ ...request, headers: Headers.set(request.headers, "authorization", `Bearer ${Redacted.value(token)}`) })))export const Approvals = RpcGroup.make( Rpc.make("ApproveRaise", { payload: { raiseId: Schema.String }, success: Schema.String, error: Forbidden })).middleware(Authenticated)export const ApprovalsLive = Approvals.toLayer({ ApproveRaise: Effect.fn(function*({ raiseId }) { const manager = yield* CurrentManager if (!manager.canApprove) return yield* new Forbidden() // authorization, per procedure return `${manager.id} approved ${raiseId}` })})
Probed through RpcTest: a valid manager token succeeds, a valid token without the permission fails with Forbidden, and an unknown token fails with Unauthorized before the handler runs. For per-call credentials on a shared client, prefer RpcClient.withHeaders(effect, headers) — it is fiber-scoped, so concurrent calls for different users cannot see each other's headers.
For browsers, the HTTP edge in front of the RPC route still needs a CORS allow-list and, with cookie authentication, a CSRF defense (edge policy checklist). CORS does not apply to WebSocket upgrades: validate Origin and authenticate during the upgrade, before any RPC message is accepted.
Reach for it when a concern spans many procedures and should both gate the call and hand the handler a derived service.
Schema helpers specific to RPC — chiefly RpcSchema.Stream(success, error), the success type that turns a procedure into a streaming response. A handler for a streaming RPC returns a Stream (or Queue.Dequeue); the client receives a Stream of decoded values.
Mental model. Most procedures are request/response. RpcSchema.Stream is the escape hatch for many responses over time — server push, streaming results. Pass stream: true to Rpc.make and it wraps the schemas automatically.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Rpc, RpcSchema } from "effect/rpc"class Compensation extends Schema.Class<Compensation>("Compensation")({ employeeId: Schema.String, level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), baseSalary: Schema.BigDecimal}) {}// Explicit stream schema: stream every employee's comp in a department...const StreamComp = Rpc.make("StreamComp", { payload: { departmentId: Schema.String }, success: RpcSchema.Stream(Compensation, Schema.Never)})// ...or the shorthand, which produces the same thing.const StreamComp2 = Rpc.make("StreamComp", { payload: { departmentId: Schema.String }, success: Compensation, stream: true})
Also exposes RpcSchema.ClientAbort, a marker the server can use to detect a streaming client disconnect, and getStreamSchemas for introspecting whether a success schema is a stream.
A stream is request-owned and ephemeral. Decide, per streaming procedure: what an element failure and a terminal failure mean, the ordering guarantee, how it completes, the finite buffers on both sides, what happens to a slow consumer, and which finalizers release the subscription or cursor. When the client stops consuming or disconnects, the server interrupts the handler and the stream's finalizers run — but a browser tab that closes may never send the interrupt, so put a server-side deadline or idle timeout on every long stream. When a consumer is interrupted, the client stops acknowledging the chunks it drops, so on ack-paced transports the server stops producing instead of draining the whole stream before the interrupt arrives. On the client side, if the fiber writing a streaming request to the transport is interrupted, the local stream (or the queue returned with { asQueue: true }) ends with that interruption instead of waiting forever for chunks that will never arrive. A stream is not a durable job, a replay log, or an exactly-once channel: work that must outlive the call belongs in a workflow, and "reconnect and resume" is a feature you build with cursors, retention, re-authorization, and duplicate handling.
Reach for it when a procedure produces a sequence of values rather than a single result.
The pluggable wire format. RpcSerialization is a service describing how messages are framed and parsed; provide one of its layers and both client and server use it. Swapping formats is a single layer change with zero impact on contract or handlers.
Mental model. The contract decides what travels; serialization decides how it's encoded. Framed formats (NDJSON, SchemaBinary) can stream multiple messages over a long-lived connection; unframed JSON suits one-shot HTTP request/response.
Serialization is schema-aware: each RpcSerialization carries a codecFor(schema) that builds the codec for the payload, chunk, exit, and defect holes inside the protocol envelope. JSON formats return Schema.toCodecJson; layerSchemaBinary encodes those holes as bytes compiled from the RPC's own schemas. A custom serialization must therefore supply codecFor as well as framing.
layerJson — Plain JSON. Unframed — best for one-request-per-HTTP-call.
layerNdjson — Newline-delimited JSON. Framed; ideal for streaming and sockets. Its content type is application/x-ndjson; empty LF/CRLF lines are skipped and a malformed non-empty line fails with NdjsonDecodeError instead of being dropped.
layerNdjsonWith({ maxBufferSize }) — NDJSON with an explicit bound on a retained incomplete frame. The default is 16 MiB; "unbounded" disables it. Exceeding it fails with MaxBufferSizeExceeded.
layerSchemaBinary({ maxFrameSize?, fingerprintPayloads? }) — Compact binary frames derived from the RPC schemas (see SchemaBinary). Framed; great for workers, TCP, and high-throughput links. Envelopes are fingerprinted; payload fingerprints are off by default so peers can evolve payload schemas compatibly. Frames default to a 16 MiB maximum. It is also what the platform cluster layers (NodeClusterSocket, NodeClusterHttp, and their Bun/Deno equivalents) select by default — serialization: "binary" — with serialization: "ndjson" as the explicit alternative.
layerJsonRpc / layerNdJsonRpc — JSON-RPC 2.0 framing for interop with non-Effect peers (e.g. LSP/MCP tooling). Request ids are echoed exactly as sent, including 0 and "", and stream chunks of a request sent inside a JSON-RPC batch keep their order. Pass controlMessages: false when the peer is a plain JSON-RPC implementation, so its @effect/rpc/* method names are not decoded as Effect control messages (MCP servers do this).
Self-contained source · Type-checked
ts
import { RpcSerialization } from "effect/rpc"// JSON for a simple HTTP comp endpoint:const wireJson = RpcSerialization.layerJson// Binary for a worker or a chatty socket (e.g. streaming a payroll batch):const wireBinary = RpcSerialization.layerSchemaBinary()// Tighter frames when both peers always deploy the same schema definition:const wireBinaryStrict = RpcSerialization.layerSchemaBinary({ fingerprintPayloads: true, maxFrameSize: 4 * 1024 * 1024})// JSON-RPC 2.0 for cross-language interop:const wireJsonRpc = RpcSerialization.layerJsonRpc()
Warning:layerSchemaBinary() is the binary wire format; it compiles the codec for every payload, chunk, exit, and defect hole directly from the RPC group's own schemas, so it needs no runtime schema registry or format-specific dependency. Nothing negotiates the format, though: changing it is a two-sided deploy, and two binary formats (or a binary and a text format) are not wire-compatible with each other. A rolling upgrade across that boundary needs a format both versions speak — NDJSON, or a second endpoint — as the bridge. Rehearse it in staging: this handbook has not verified mixed-version NDJSON interoperability.
Migration: the request envelope gained a discard field, which changes the SchemaBinary envelope fingerprint. Upgrade every SchemaBinary peer (including cluster runners using serialization: "binary") together; mixed versions do not share an envelope fingerprint. JSON-based serializations carry no fingerprint.
Serialization is chosen independently of the transport, and both peers must provide the same one — nothing negotiates it. Every framed format needs a finite bound on an unterminated frame (maxBufferSize, maxFrameSize); leave "unbounded" to trusted, in-process peers.
Reach for it when you need to choose or change the on-the-wire encoding — for size, streaming framing, or interop.
Publishes an RPC group as an OpenRPC 1.3.2 document, the JSON-RPC counterpart of OpenApi.fromApi. OpenRpc.fromRpcGroup(group, { info, servers? }) reads only the contract: it needs no handlers, no server, and no transport, and it installs no rpc.discover method — serve or commit the returned value yourself. It describes the canonical JSON encoding, which is what RpcSerialization.layerJsonRpc / layerNdJsonRpc put on the wire.
Key API shape.
Methods come from the final composed group: one per tag (after prefix), including the errors contributed by middleware. An object payload becomes paramStructure: "by-name" with one descriptor per field (required first); a tuple payload becomes "by-position"; a payload-less procedure has no params. A scalar payload, or a schema that cannot be lowered to Draft 7 JSON Schema, throws with the method name in the message — call it in a test so the failure lands in CI.
Schemas are Draft 7, with identified schemas shared under components.schemas. Structured payloads also get x-effect-params-schema, the complete encoded payload schema for shapes descriptors cannot express. A void result or a stream's terminal completion is { type: "null" }.
Errors: a JSON-RPC error entry is derived only from error members with a literal code and message (the fields the JSON-RPC serializer sends); other errors are left out unless an OpenRpc.Errors annotation lists them, which replaces derivation.
Streams carry x-effect-stream (item, chunk, error, and cause schemas plus the @effect/rpc/Ack and @effect/rpc/Interrupt control methods). It documents Effect's protocol; a generic OpenRPC client does not speak it.
Annotations: Summary, Description, Tags, Examples, Deprecated, ExternalDocs, and Errors are Context.Service keys for .annotate on an Rpc or an RpcGroup; OpenRpc.annotations({ ... }) builds a context of several for annotateMerge. Group values are defaults, a method's value replaces them (lists are not merged), and false or [] on a method deliberately overrides a group default. Field-level title, description, and deprecated schema annotations become descriptor metadata.
Types: OpenRPCSpec, OpenRPCMethod, OpenRPCContentDescriptor, OpenRPCError, and the other OpenRPC* interfaces model the document, so post-processing stays typed.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { OpenRpc, Rpc, RpcGroup } from "effect/rpc"export const CompContract = RpcGroup.make( Rpc.make("GetComp", { payload: { employeeId: Schema.String }, success: Schema.Struct({ employeeId: Schema.String, baseSalary: Schema.Finite }), // A literal code and message become the method's documented JSON-RPC error. error: Schema.Struct({ code: Schema.Literal(-32004), message: Schema.Literal("Employee not found") }) }).annotate(OpenRpc.Summary, "Read one employee's compensation"), Rpc.make("StreamDepartment", { payload: { departmentId: Schema.String }, success: Schema.Struct({ employeeId: Schema.String }), stream: true // documented with x-effect-stream; the result descriptor is null })).annotate(OpenRpc.Tags, [{ name: "comp" }]) // a group default every method inheritsexport const document = OpenRpc.fromRpcGroup(CompContract, { info: { title: "Comp RPC", version: "1.0.0" }, servers: [{ name: "production", url: "https://comp.acme.internal/rpc" }]})// document.methods[0].errors => [{ code: -32004, message: "Employee not found" }]
Generation is best-effort in the same way as OpenAPI: custom predicates and approximated constraints are documented loosely, and Effect decoding stays the authority. Assert the facts a consumer relies on — method names, parameter structure, required params, error codes — rather than snapshotting the document.
Reach for it when non-Effect peers call the group over JSON-RPC and need a machine-readable contract for discovery, client generation, or review.
The protocol envelope types — messages that flow between client and server once payloads are wrapped for transport. Client-to-server: Request, Ack, Interrupt, Eof, Ping. Server-to-client: response exits, stream chunks, defects, Pong. Also defines branded RequestId.
Mental model. This is the language transports speak. RpcClient/RpcServer produce and consume these — but backpressure (Ack), cancellation (Interrupt), and end-of-stream (Eof) live here. Consult when writing a custom transport or debugging framing.
The Request envelope flows in both directions: a server protocol can originate requests to a connected client, and a request marked isNotification expects no reply — server-originated notifications are a first-class capability, not a transport hack. A protocol advertises the capability as supportsNotifications; the buffered (unframed layerJson/layerJsonRpc) HTTP protocol cannot deliver them and drops server notifications, because a single buffered response has nowhere to put them — use a framed serialization or a socket when the server must push.
A response Exit's encoded Interrupt cause carries fiberId: number | null | undefined — a serializer or custom protocol that round-trips an interrupted exit must accept a null fiber id, not just a number.
Glue for running an RPC group over a Worker. Pair RpcClient.layerProtocolWorker on the main thread with RpcServer.layerProtocolWorkerRunner inside the worker to make a typed group drive a typed worker pool — same contract as HTTP, different pipe.
Mental model. Instead of HTTP, messages travel via postMessage (with transferables for zero-copy buffers). RpcWorker adds the InitialMessage service — one schema-encoded value the client hands the worker on startup (config, connection string) before normal requests flow.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { RpcWorker } from "effect/rpc"// Client side: provide a one-shot initial message to every spawned worker.const initLayer = RpcWorker.layerInitialMessage( Schema.Struct({ hrisUrl: Schema.String }), Effect.succeed({ hrisUrl: "postgres://localhost/hris" }))// Worker side: read and decode that initial message before serving requests.const readInit = RpcWorker.initialMessage( Schema.Struct({ hrisUrl: Schema.String }))
Combine with RpcSerialization.layerSchemaBinary() — binary framing plus transferables is the sweet spot for worker traffic.
Reach for it when you want a typed RPC contract to drive a Worker pool, not a network service.
In-memory harness that wires a derived client straight to handlers — no transport, no serializer, no HTTP server. RpcTest.makeClient(group) connects client and server through the no-serialization path; requests, responses, stream chunks, acks, interrupts, headers, and middleware all flow through the real machinery without bytes on a wire.
Mental model. Fastest way to test a group end-to-end. Provide the same handler layer you'd ship in production; the harness gives a typed client that calls it directly. Failures, streams, and middleware behave exactly as over a socket — faster and deterministic.
Fragment · Type-checked with fixture
ts
import { BigDecimal, Effect } from "effect"import { RpcTest } from "effect/rpc"const test = Effect.gen(function*() { // Client talks straight to CompLive handlers — no network involved. const client = yield* RpcTest.makeClient(CompRpc) const raised = yield* client.ProposeRaise({ employeeId: "E-1", amount: BigDecimal.fromBigInt(12000n) }) // assert BigDecimal.equals(raised.baseSalary, BigDecimal.fromBigInt(192000n)) const missing = yield* client.GetComp({ employeeId: "E-999" }).pipe(Effect.flip) // missing is a typed EmployeeNotFound, exactly as a real client would see}).pipe(Effect.scoped, Effect.provide(CompLive))
RpcTest.makeClient(group, { disableFatalDefects: true }) mirrors the server option, so a handler defect fails only its own request instead of every pending call on the test client.
What it proves, and what it does not.RpcTest.makeClient runs the real request machinery — handlers, middleware, typed exits, stream chunks, acks, interruption — and the client still validates each payload against the procedure's schema when it builds the request. It skips serialization and transport entirely, so it proves nothing about the encoded form, framing, a serializer mismatch, version skew, frame limits, or what a disconnect does. Cover those in a second ring with a real serializer and listener (an RpcServer.layerHttp route on port 0, see HTTP Server), and add hostile protocol cases that a typed client can never produce: a frame split across chunks, several frames in one chunk, an unknown tag, an oversized or never-terminated frame, deeply nested JSON, and prototype-pollution-shaped keys (__proto__, constructor).
Reach for it when you want fast, deterministic tests of a whole group's behaviour without standing up a server.
Plumbing for transport authors. withRun and withRunClient build protocol services that expose a stable send/write handle before the receive loop starts, buffering early messages (with their Context) and replaying them once run installs the real receiver. The built-in HTTP/socket/worker protocols are built with these.
Reach for it when writing a custom RpcClient.Protocol/RpcServer.Protocol and needing correct buffering during connection setup — otherwise never call it directly.
Tip: Define a RpcGroup of Rpc.make procedures → implement with group.toLayer(handlers) → serve with RpcServer.layerHttp + a RpcSerialization layer → on the caller, derive RpcClient.make(group) over layerProtocolHttp + the same serialization → call client.ProposeRaise(payload) and get a typed Effect. Swap serialization for SchemaBinary, or protocol for websocket/worker, and the contract — and your code — doesn't change. Test the whole thing with RpcTest.makeClient.
Note: The query API, schema adapters, resolvers, models, and migrator live in the effect package itself, under effect/sql (tagged @stability unstable). They are database-agnostic. A driver package like @effect/sql-pg contributes one thing: a Layer producing the SqlClient service wired to a real connection pool and the correct dialect compiler. Write your service against SqlClient; swap the driver layer to change databases.
Official example: The release-matched ai-docs SQL example defines a Model.Class, runs migrations, and exposes a derived repository through a service.
Dependencies point one way: transport → use case → domain repository → SQL implementation → SqlClient. A route handler that holds the raw SqlClient has nowhere to put authorization, invariants, or error meaning, and every driver change reaches the edge.
Generated repositories (SqlModel) remove CRUD boilerplate, but keep them behind the domain repository so library churn stays local. For each operation, decide up front: request and result Schemas · cardinality and what absence means · transaction and locking needs · expected domain failures · how SqlError / SchemaError surface · connection cost (a transaction, stream, or listener holds a connection; an ordinary statement borrows one briefly).
SqlClient is the injected service used for every query. It is simultaneously a tagged-template query constructor (sql applied to a template literal), an identifier quoter (sql("employees")), and an object with helpers (sql.in, sql.insert, sql.withTransaction). const sql = yield* SqlClient.SqlClient gives you this callable. Each tagged-template statement is an Effect yielding ReadonlyArray<Row>.
Every value interpolated with ${} becomes a bound parameter, never string-concatenated into the SQL text. The text around interpolations is literal; holes become placeholders ($1, $2 on pg, ? on sqlite/mysql).
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { SqlClient } from "effect/sql"const getEmployee = Effect.fn("getEmployee")(function*(id: number) { // SqlClient is part of the unstable effect/sql module. const sql = yield* SqlClient.SqlClient // `id` is bound as a parameter -> compiles to: select * from employees where id = $1 const rows = yield* sql`select * from employees where id = ${id}` return rows[0]})
Warning:sql(someString) produces a quoted identifier (table/column name), escaped by the dialect. sql.unsafe(text, params) and sql.literal(text) splice raw text unescaped — reserve for trusted, static SQL only. Untrusted values always go through ${} interpolation.
A placeholder can stand for a value, never for a table, column, sort direction, or fragment. Map a user's choice through a closed allow-list first, and only then hand the result to the identifier helper — quoting makes an identifier syntactically safe, not authorized.
Fragment · Type-checked
ts
import { SqlClient } from "effect/sql"// SqlClient is part of the unstable effect/sql module.declare const sql: SqlClient.SqlClientdeclare const requestedSort: string // untrusted: a query-string valueconst sortColumns: Record<string, string> = { name: "name", hired: "hired_at", level: "level" }const column = sortColumns[requestedSort] ?? "name" // unknown input falls back, it is never quoted throughconst page = sql`select * from employees order by ${sql(column)} limit 20`
A statement is also an Effect and exposes execution views. .values returns rows as positional value arrays; .valuesUnprepared does the same through the driver's unprepared/text path. .unprepared keeps object rows, .withoutTransform skips result-name transforms, .stream streams rows, and .compile() returns SQL plus bound parameters. Choose an unprepared form only when the driver or proxy cannot use prepared statements.
import { Effect } from "effect"import { SqlClient } from "effect/sql"// SqlClient is part of the unstable effect/sql module.const findEmployees = Effect.fn("findEmployees")( function*(levels: ReadonlyArray<string>, hiredBefore: Date) { const sql = yield* SqlClient.SqlClient // sql.in -> a safe, parameterized IN (...) list (handles the empty-array case too) // sql.and -> parenthesized AND chain of fragments const rows = yield* sql` select * from ${sql("employees")} where ${ sql.and([ sql.in("level", levels), sql`hired_at < ${hiredBefore}` ]) } ` return rows })const addEmployee = Effect.fn("addEmployee")( function*(name: string, level: string, departmentId: number) { const sql = yield* SqlClient.SqlClient // sql.insert builds the (cols) VALUES (...) clause; .returning("*") adds RETURNING on pg return yield* sql`insert into employees ${ sql.insert({ name, level, department_id: departmentId }).returning("*") }` })
Additional helpers: sql.insert([...]) for bulk rows, sql.update(record, [omitKeys]) for a single-row SET clause, sql.updateValues([...], "alias") for multi-row updates (not on sqlite), sql.or, and sql.csv("order by", [...]) for comma lists. sql.updateValues escapes its alias as an identifier without applying name transforms, so pass a bare alias (not pre-quoted SQL) and quote a mixed-case PostgreSQL alias where the query references it.
Bulk helpers take a non-empty array.sql.insert and sql.updateValues require NonEmptyReadonlyArray rows at the type level; narrow a runtime array first and skip the statement when it is empty.
Self-contained source · Type-checked
ts
import { Array, Effect } from "effect"import { SqlClient } from "effect/sql"export const insertBands = Effect.fn("insertBands")( function*(rows: ReadonlyArray<{ readonly level: string; readonly mid: number }>) { const sql = yield* SqlClient.SqlClient if (!Array.isReadonlyArrayNonEmpty(rows)) return yield* sql`insert into comp_bands ${sql.insert(rows)}` })
Note: An empty list is safe in both sql.in forms. The two-argument sql.in("level", levels) compiles to 1=0 (no rows). The one-argument form level in ${sql.in(levels)} matches no rows with IN and every row with NOT IN when the keyword directly precedes the helper; on PostgreSQL it compiles to = ANY('{}'), so a comparison on the left of IN must be parenthesized (a = (b in ${sql.in([])})), and array-typed columns are not supported there. Bulk sql.insert([...]) and long IN lists bind one parameter per value, so chunk large inputs to stay under the driver's parameter and statement-size limits (PostgreSQL allows 65,535 bound parameters per statement).
A statement built with the sql tag is a Fragment, so it can be interpolated into another query to build queries conditionally without touching strings.
Fragment · Type-checked
ts
import { SqlClient } from "effect/sql"declare const sql: SqlClient.SqlClientdeclare const activeOnly: booleanconst filter = activeOnly ? sql`where terminated_at is null` : sql``const page = sql`select * from employees ${filter} order by id limit 20`
sql.withTransaction(effect) runs every query in the effect on one reserved connection, inside a transaction. Success commits; failure or interruption rolls back. Nested withTransaction calls automatically become savepoints rather than a second BEGIN.
The transaction itself can fail after the body succeeds: a failed COMMIT remains a typed SqlError when cleanup succeeds, so callers can handle it outside withTransaction. Drivers can run commit-failure cleanup (notably SQLite rollback for deferred constraints) before reusing the connection. If that cleanup also fails, the combined causes become defects rather than disguising a broken connection as a routine retryable failure. A successful body is not proof of a durable commit; publish events only after the transaction Effect succeeds.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { SqlClient } from "effect/sql"// Promote an employee and adjust their salary atomically.const promote = Effect.fn("promote")( function*(employeeId: number, newLevel: string, newSalaryCents: number) { const sql = yield* SqlClient.SqlClient yield* sql.withTransaction( Effect.gen(function*() { yield* sql`update employees set level = ${newLevel} where id = ${employeeId}` yield* sql`update employees set base_salary = ${newSalaryCents} where id = ${employeeId}` // throw / fail / interrupt anywhere in here -> automatic ROLLBACK (no half-applied promotion) }) ) })
Tip:withTransaction opens a sql.transaction tracing span, and each transaction control statement runs in its own client span under it, named after the operation and the client's span target: BEGIN comp, SAVEPOINT comp, COMMIT comp, ROLLBACK comp, ROLLBACK TO SAVEPOINT comp, RELEASE SAVEPOINT comp, with db.operation.name set to the operation. The target follows the same rule as statement span names (db.namespace, else server.address[:server.port]), and the span is named by the operation alone when neither attribute is set. A failed COMMIT or ROLLBACK therefore ends its own span with its own exit. With Statement.SpanPropagationEnabled, a top-level transaction also records how long it waited for its connection as db.client.connection.wait_time_ms on the sql.transaction span, and connection spans are parented under it. Every query carries the client's span attributes.
Migration: the effect.sql.transaction.commit, effect.sql.transaction.rollback, and effect.sql.transaction.savepoint span events are gone; dashboards and trace queries that looked for them should match the child spans by db.operation.name instead.
Commit or rollback is decided by exactly one thing: the Exit of the effect you pass in. Sequencing only orders statements; withTransaction never inspects what ran inside. Two plausible mistakes therefore commit half a unit:
Mistake
What happens
Fix
Recovering inside the body — Effect.ignore, Effect.catch, or Effect.orElseSucceed around a failing step
The body's Exit is a success, so every write issued before the failure is committed. Re-raising afterwards is too late.
Let the failure leave the body; recover outsidewithTransaction.
Opening the transaction late — the first write runs before withTransaction
That write already committed on its own; the rollback cannot reach it.
Put the whole unit inside.
Fragment · Type-checked
ts
import { Data, Effect } from "effect"import { SqlClient } from "effect/sql"class BudgetExceeded extends Data.TaggedError("BudgetExceeded")<{ readonly cycle: string }> {}declare const sql: SqlClient.SqlClient// Decrements the merit budget; fails when the budget cannot cover the raise.declare const drawMeritBudget: (cycle: string, amount: number) => Effect.Effect<void, BudgetExceeded>const recordRaise = (employeeId: number, amount: number) => sql`insert into raises ${sql.insert({ employee_id: employeeId, amount })}`// WRONG — swallowed failure: the body succeeds, so the raise commits without its budget draw.const swallowed = sql.withTransaction( Effect.gen(function*() { yield* recordRaise(42, 10_000) yield* drawMeritBudget("2026", 10_000).pipe(Effect.ignore) }))// WRONG — late transaction: the insert is committed before the transaction even opens.const late = Effect.gen(function*() { yield* recordRaise(42, 10_000) yield* sql.withTransaction(drawMeritBudget("2026", 10_000))})// RIGHT — the whole unit inside, recovery outside.const atomic = sql.withTransaction( Effect.gen(function*() { yield* recordRaise(42, 10_000) yield* drawMeritBudget("2026", 10_000) })).pipe( Effect.catchTag("BudgetExceeded", () => Effect.succeed("rejected" as const)))
Test the forced-rollback path: make the second step fail and assert that every related table is unchanged. An identity withTransaction fake proves nothing about atomicity.
Transaction rules:
Membership is by client identity. The active connection travels in the fiber context under a key that is unique per constructed client, so every participant must use the sameSqlClient instance. Two repositories built from one client Layer join one transaction; a second, separately constructed client — even one pointing at the same database — acquires its own connection and runs outside it.
Wrap the smallest database-only unit, at the use-case level. A transaction holds one pooled connection and its locks for its whole duration. Remote calls, sleeps, and unbounded work do not belong inside: rollback cannot undo an email, and retrying the transaction would send it twice. See External effects after commit.
Work forked inside a transaction cannot use it after it ends. A fiber forked inside keeps the context entry that points at the transaction, but once that transaction (or any enclosing one) has committed or rolled back, its statements and nested withTransaction calls fail with a SqlError whose reason is UnknownError ("the transaction has already ended") instead of running on a connection that may already serve someone else. Driver extras that read the transaction directly — MSSQL call and withoutTransforms(), Bun SQLite export, libSQL reserve — fail the same way. Register post-commit work with sql.afterCommit; for a fiber that should run outside the transaction, remove the entry before forking with Effect.updateContext(Context.omit(sql.transactionService)).
Concurrent branches still share the one reserved connection.Effect.all(..., { concurrency }) inside a transaction does not parallelize database work, and nested withTransaction calls made from sibling fibers are serialized. A nested call waiting for a sibling's savepoint can be interrupted; once it holds the savepoint, the savepoint and its cleanup run uninterruptibly.
Nested calls are savepoints, not isolation. A failure that escapes an inner withTransaction rolls back to its savepoint; if you recover around the inner call, the outer transaction continues and commits without the inner writes — the one legitimate way to make a step optional. The helper does not prevent lost updates: pick an isolation level, select … for update, a version column, or a single atomic update … set remaining = remaining - ${n} from the invariant you need.
Savepoints release once a nested transaction settles. The PostgreSQL, PGlite, MySQL, libSQL, and Node/Bun/React Native/WASM SQLite clients release a savepoint as soon as the nested withTransaction succeeds or successfully rolls back, freeing PostgreSQL's transaction locks before the outer transaction completes. If an enclosing transaction ends while a nested rollback is still in flight, the release is skipped and the original failure is kept, so cleanup never touches a connection that has already been released. Clients built on SqlClient.make always send rollbacks and savepoint releases unprepared, so a prepared statement the server has dropped cannot block cleanup. A custom client built with SqlClient.makeWithTransaction opts in with its own releaseSavepoint option.
Retry the whole transaction, never an inner statement. After a DeadlockError or SerializationError the database has already aborted the transaction, so wrap the outermostsql.withTransaction(unit) in a bounded Effect.retry; each attempt begins a fresh transaction and re-runs unit and its COMMIT. Retrying a nested withTransaction only retries its savepoint, which cannot revive an outer transaction the database has aborted. Do not retry ConnectionError here: a COMMIT that lost its connection may have committed, and a retry would apply the writes twice. Because the body runs once per attempt, keep it database-only and put follow-up work in afterCommit, which drops the callbacks of a failed attempt.
Commit errors can be typed too. Acquisition, BEGIN, and SAVEPOINT failures surface as SqlError. A failed COMMIT preserves its typed error if commit-failure cleanup succeeds; if cleanup fails too, the combined failures become defects. ROLLBACK and savepoint-release failures are defects. Observe both channels on sql.transaction spans, and never infer from the error channel alone that a write definitely did not commit.
Isolation level and post-commit hooks. Provide SqlClient.BeginTransaction (a Context.Reference<string | undefined>) to replace the statement that starts a top-level transaction, such as "BEGIN ISOLATION LEVEL SERIALIZABLE", saving a separate SET TRANSACTION round trip; nested transactions still use savepoints. MySQL cannot set an isolation level in START TRANSACTION, so on @effect/sql-mysql2 a value starting with SET TRANSACTION (for example "SET TRANSACTION ISOLATION LEVEL READ COMMITTED") runs immediately before BEGIN; any other value replaces BEGIN. @effect/sql-libsql, @effect/sql-mssql, and @effect/sql-sqlite-do do not start transactions with a SQL statement and ignore it. The value is sent as raw SQL, so never build it from input. sql.afterCommit(effect) runs a never-failing effect once the outermost transaction commits (immediately outside a transaction) and drops it on rollback; Reactivity invalidations inside a transaction are deferred the same way. Callbacks run uninterruptibly after COMMIT and withTransaction waits for them, so keep them short and fork long work. It is an in-process hook, not a durable outbox: a crash after commit, or an unknown COMMIT outcome, loses it.
Under SERIALIZABLE, conflicting transactions abort with SerializationError, so pair the isolation level with a bounded retry of the whole unit:
Fragment · Type-checked
ts
import { Effect, Schedule } from "effect"import { SqlClient } from "effect/sql"import type { SqlError } from "effect/sql"declare const sql: SqlClient.SqlClient// Draws the raise from the department's merit budget; database-only, so safe to run again.declare const drawAndRecord: (employeeId: number, amount: number) => Effect.Effect<void, SqlError.SqlError>export const recordRaise = (employeeId: number, amount: number) => sql.withTransaction(drawAndRecord(employeeId, amount)).pipe( Effect.provideService(SqlClient.BeginTransaction, "BEGIN ISOLATION LEVEL SERIALIZABLE"), // Outermost transaction only, and never on ConnectionError: a lost COMMIT may have committed. Effect.retry({ while: (error) => error.reason._tag === "SerializationError" || error.reason._tag === "DeadlockError", times: 5, schedule: Schedule.exponential("10 millis").pipe(Schedule.jittered) }) )
A queued withTransaction or sql.reserve waiting for a connection can be interrupted (respecting the caller's interruptibility), and an interrupted or failed acquisition always returns the connection and its permits.
A transaction should contain database work only; deliver external effects after it commits. Emails, webhooks, HTTP exports, and model calls are irreversible, while a transaction body can be rolled back after the send or retried after a deadlock. The reverse order — commit, then publish from the same request — loses the event when the process dies between the two steps.
The transactional outbox closes both gaps: write an intent row in the same transaction as the state change, and let a separate relay deliver pending rows after commit.
Fragment · Type-checked
ts
import { Effect } from "effect"import { SqlClient } from "effect/sql"declare const sql: SqlClient.SqlClient// Idempotent on `eventId` at the receiver.declare const publish: (eventId: string, payload: string) => Effect.Effect<void, "delivery-failed">const approveRaise = (employeeId: number, newSalary: number, eventId: string) => sql.withTransaction( Effect.gen(function*() { yield* sql`update employees set base_salary = ${newSalary} where id = ${employeeId}` yield* sql`insert into outbox ${ sql.insert({ id: eventId, topic: "RaiseApproved", payload: JSON.stringify({ employeeId, newSalary }) }) }` }) )// Runs on a schedule, outside any transaction.const deliverPending = Effect.gen(function*() { const rows = yield* sql<{ id: string; payload: string }>` select id, payload from outbox where delivered = false order by seq ` for (const row of rows) { yield* publish(row.id, row.payload) // Acknowledge only after the send succeeded. yield* sql`update outbox set delivered = true where id = ${row.id} and delivered = false` }})
Name the guarantee honestly: at-least-once. A failed send leaves the row pending and the same event id is sent again; a crash between the receiver accepting and the local acknowledgement re-sends an event that already arrived. Receivers must deduplicate on the event id — never write "exactly once". Count attempts durably and park rows that keep failing instead of retrying them forever.
The complete, runnable version — repository errors, forced rollback, acknowledgement loss, and consumer deduplication — is Recipe: A Transactional Write with an Outbox. When the queue itself can live in the same database, PersistedQueue with its SQL store is a ready-made outbox with retry schedules and dead-lettering; the durability ladder covers workflows and cluster delivery.
Each statement exposes alternate execution modes (covered under Statement): .stream, .values, .raw, .unprepared, .withoutTransform, .compile(). For portable libraries, sql.onDialect({ pg, sqlite, mysql, mssql, clickhouse }) / sql.onDialectOrElse({ orElse, pg }) branch on the active database.
sql.reserve hands a scoped raw Connection for manual control. sql.reactive(keys, effect) turns a query into a Stream that re-runs when those keys are invalidated via the Reactivity service.
A Statement<A> is a list of segments (literals, escaped identifiers, bound parameters, insert/update helpers) plus the machinery to compile them to a [sqlText, params] pair for the active dialect. It is both an Effect and a Fragment. The template literal is parsed once into segments; the dialect Compiler walks those segments to produce numbered placeholders and the params array.
On a statement
Gives you
yield* stmt
Decoded/transformed rows — ReadonlyArray<A>. The default.
stmt.stream
A Stream<A, SqlError> for large result sets (see SqlStream).
stmt.values
Rows as positional arrays (ReadonlyArray<ReadonlyArray<unknown>>) — skips object building.
stmt.raw
The driver's raw result object, untouched.
stmt.unprepared
Execute without the named prepared-statement cache (for poolers such as PgBouncer in transaction mode that cannot keep named statements). Driver-dependent: on the native @effect/sql-pg client a query string must still contain exactly one statement, because PostgreSQL's extended protocol rejects multi-statement strings.
stmt.withoutTransform
Skip the client's row/column name transform for this query.
stmt.compile()
[sql, params] — inspect what will actually run.
Fragment · Type-checked
ts
import { SqlClient } from "effect/sql"declare const sql: SqlClient.SqlClient// Inspect the compiled output — exactly what the test suite does:const [text, params] = sql`select * from ${sql("comp_bands")} where level in ${sql.in(["L3", "L4", "L5"])}`.compile()// text: select * from "comp_bands" where level in ($1,$2,$3)// params: ["L3", "L4", "L5"]
Segment constructors (literal, identifier, parameter, arrayHelper, insert/update helpers, and custom for driver extensions) are exported for custom dialect or bespoke helper authoring. Fragments and segments carry the Statement.FragmentTypeId / Statement.SegmentTypeId symbol brands, and sql interpolation recognizes only branded values: a plain object that merely looks like a fragment or segment ({ _tag: "Literal", value: "…" } parsed from JSON, say) binds as an ordinary parameter, never as SQL text. Build fragments and segments with the sql tag and the Statement constructors, not with object literals. The Dialect type — "sqlite" | "pg" | "mysql" | "mssql" | "clickhouse" — is the same one onDialect keys on.
None of the execution views disables parameter binding: .raw and .values change the projection, .unprepared changes the execution strategy, and ${} holes stay bound parameters in all of them.
Note: Every execution opens a client span named by the OpenTelemetry database conventions — the client's db.namespace, else server.address[:server.port], else db.system.name, falling back to sql.execute (the rule is exported as Statement.spanName). It carries db.query.text — the compiled SQL with placeholders, never the bound parameters — and the Effect execution method in effect.sql.method. Text spliced in through sql.literal / sql.unsafeis part of that query text, one more reason to keep values in ${}. Driver-level spans (connection acquisition, stream pulls) are not parented under the statement span by default; opt in for a region with Effect.provideService(Statement.SpanPropagationEnabled, true) (default false, ignored while tracing is disabled). .returning(...) helpers escape identifiers per dialect and number placeholders correctly when a cached fragment is reused.
Reach for it when you need a non-default execution mode (stream, raw, values, unprepared), want to compile() and assert on generated SQL, or you're authoring a custom dialect/helper.
SqlSchema bridges a query and a Schema. It wraps execution so the request is encoded before running and every returned row is decoded through a result Schema. Each helper is a factory: provide a Request schema, a Result schema, and an execute callback; receive (input) => Effect<decoded, SchemaError | ..., R>. The difference between helpers is result cardinality.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { SqlClient, SqlSchema } from "effect/sql"const Employee = Schema.Struct({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.String, departmentId: Schema.Int.check(Schema.isGreaterThan(0))})const makeEmployeeQueries = Effect.gen(function*() { const sql = yield* SqlClient.SqlClient // SqlSchema is part of the unstable effect/sql module. // findOne: decode the first row, fail with NoSuchElementError if there are none const getById = SqlSchema.findOne({ Request: Schema.Int.check(Schema.isGreaterThan(0)), Result: Employee, execute: (id) => sql`select * from employees where id = ${id}` }) // findAll: a parameterized "employees in a department" query, every row decoded const inDepartment = SqlSchema.findAll({ Request: Schema.Int.check(Schema.isGreaterThan(0)), Result: Employee, execute: (departmentId) => sql`select * from employees where department_id = ${departmentId} order by level` }) return { getById, inDepartment } as const})// getById(42): Effect<Employee, SchemaError | NoSuchElementError | SqlError, ...>// inDepartment(7): Effect<Array<Employee>, SchemaError | SqlError, ...>
Helper
Result type & empty-set behavior
findAll
Array<A> — empty is fine.
findNonEmpty
NonEmptyArray<A> — empty fails with NoSuchElementError.
findOne
A from first row — empty fails with NoSuchElementError.
findOneOption
Option<A> — empty is None.
SqlSchema.void
Encodes the request, runs the side-effecting statement, discards rows.
Warning:findOne and findOneOption mean "first row", not "exactly one": both decode rows[0] and silently ignore any further rows. Exactly-one semantics need a unique constraint that the where clause targets, or findAll plus an explicit length check — a helper name containing "one" is not that proof.
A row generic is not validation.sql<Row> is a compile-time annotation only; database output is untrusted (schema drift, nullability, integer width, date and JSON representation, aliases), so decode before branding or constructing domain values. Keep three outcomes distinct:
Outcome
Shows up as
Means
Zero rows
Option.none() from findOneOption, NoSuchElementError from findOne / findNonEmpty
Domain absence — when the operation defines one.
A row that does not decode
SchemaError
Corrupt or incompatible stored data. Not "not found".
Statement or connection fault
SqlError
Infrastructure. Not "not found" either.
To show that row decoding really runs, have one repository test insert a row the current schema must reject, such as one in a pre-migration shape.
Reach for it when you want queries to return real domain types with validation at the boundary instead of hand-casting unknown rows.
SqlResolver builds schema-aware RequestResolvers on top of Effect's Request/Batching machinery: many concurrent lookups collapse into one batched SQL query, with requests deduplicated by payload and results mapped back to callers. Describe one logical lookup (its Id/Request schema, its Result schema, and how to map a result back to the requesting caller). When N callers fire that lookup in one batching window, the resolver encodes all inputs, runs a single IN (...)-style query, decodes rows, and completes each request from the shared result set.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { SqlClient, SqlResolver } from "effect/sql"const CompBand = Schema.Struct({ level: Schema.String, salaryMin: Schema.Finite, salaryMid: Schema.Finite, salaryMax: Schema.Finite})const makeCompBandLoader = Effect.gen(function*() { const sql = yield* SqlClient.SqlClient // SqlResolver is part of the unstable effect/sql module. // findById: batch many levels into one query; map each row back via ResultId const resolver = SqlResolver.findById({ Id: Schema.String, Result: CompBand, ResultId: (band) => band.level, execute: (levels) => sql`select * from comp_bands where ${sql.in("level", levels)}` }) // turn the resolver into a normal effectful function return SqlResolver.request(resolver)})// Pricing 100 raise recommendations? Each needs its level's band.// These collapse into ONE "select ... where level in (...)" — and "L4" is deduped.const program = Effect.gen(function*() { const bandFor = yield* makeCompBandLoader const [l4, l4Again, l5] = yield* Effect.all( [bandFor("L4"), bandFor("L4"), bandFor("L5")], { concurrency: "unbounded" } ) return { l4, l4Again, l5 }})
Constructor
Use for
findById
One result per id, matched by ResultId; missing ids fail with NoSuchElementError. Auto-dedupes.
grouped
Many results per key, grouped by ResultGroupKey back to each request's RequestGroupKey.
ordered
Positional mapping: result row i answers request i; mismatched counts raise ResultLengthMismatch.
SqlResolver.void
Batched side-effect writes with no decoded result.
Tip: Batches are keyed by the active transaction connection, so lookups made inside a withTransaction never get merged with reads outside it.
Reach for it when you'd otherwise fire a query per item in a loop or per field in a GraphQL/RPC resolver.
Official guide: Batching (that guide covers Effect.forEach-driven batching; Effect.forEach has no batching option here — requests batch when they are issued concurrently against the same resolver). The request/resolver model itself is covered in Caching & Batching.
SqlStream turns a driver's push-based cursor (event emitter, server-side cursor, callback firehose) into an Effect Stream with backpressure. It is plumbing that drivers use to implement statement.stream and connection.executeStream. asyncPauseResume registers an emitter with single/array/fail/end callbacks and pause/resume hooks; when the internal bounded queue fills, it calls the driver's onPause so the database stops pushing rows faster than they are consumed.
Self-contained source · Type-checked
ts
import { Effect, Stream } from "effect"import { SqlClient } from "effect/sql"// You almost always interact with it via `.stream` on a statement:const streamAllEmployees = Effect.gen(function*() { const sql = yield* SqlClient.SqlClient yield* sql`select * from employees order by id`.stream.pipe( Stream.runForEach((row) => Effect.log(row)) // rows arrive incrementally, backpressured )})
Reach for it when writing a driver, or building a custom adapter from a row-emitting source into a Stream. For everyday large reads, use statement.stream.
The single typed failure for the whole SQL stack. Every query, transaction, and connection acquire fails with SqlError. It wraps a structured reason — connection, auth, syntax, constraint, deadlock, serialization, timeout, unknown — each preserving the original driver cause and exposing whether a retry could help. The outer error delegates message, cause, and isRetryable to its reason.
Self-contained source · Type-checked
ts
import { Effect, Schedule, Schema } from "effect"import { SqlClient, SqlError } from "effect/sql"class GrantAlreadyExists extends Schema.TaggedError<GrantAlreadyExists>()("GrantAlreadyExists", { employeeId: Schema.Int}) {}// One employee, one active equity grant: `unique (employee_id, status)`, which PostgreSQL// names equity_grants_employee_id_status_key.const grantEquity = Effect.fn("grantEquity")( function*(employeeId: number, shares: number) { const sql = yield* SqlClient.SqlClient return yield* sql`insert into equity_grants ${ sql.insert({ employee_id: employeeId, shares, status: "active" }) }`.pipe( // Retry only the transient reasons (deadlock, serialization, lock/statement timeout, // connection), at most 3 more times. `while`, `times`, and `schedule` must all allow a retry. Effect.retry({ while: (e: SqlError.SqlError) => e.isRetryable, times: 3, schedule: Schedule.exponential("10 millis") }), // Translate the ONE constraint that means "already granted". Every other reason, // including a unique violation on a different index, stays a SqlError. Effect.catchTag("SqlError", (e): Effect.Effect<never, SqlError.SqlError | GrantAlreadyExists> => e.reason._tag === "UniqueViolation" && e.reason.constraint === "equity_grants_employee_id_status_key" ? Effect.fail(new GrantAlreadyExists({ employeeId })) : Effect.fail(e)) ) })
Reasons marked retryable: ConnectionError, DeadlockError, SerializationError, LockTimeoutError, StatementTimeoutError. Not retryable: AuthenticationError, AuthorizationError, SqlSyntaxError, UniqueViolation (carries the violated constraint), ConstraintError, UnknownError. Guards isSqlError / isSqlErrorReason and the SQLite classifier classifySqliteError are included. ResultLengthMismatch lives here too (raised by SqlResolver.ordered).
Match the constraint, not just the tag. A primary-key collision is a UniqueViolation too (equity_grants_pkey on the table above), so translating every UniqueViolation into one domain conflict misreports unrelated bugs. A lost connection, a rejected login, a timeout, a SQL syntax error, or an undecodable row is an infrastructure failure, never a "not found" or a "conflict". Retrying the insert above is safe only because the unique index makes it idempotent: after a ConnectionError the first attempt may have committed, and the retry then reports the conflict instead of writing twice.
A repository owns its failures: map the typed channel into one stable domain error, and leave defects alone. Callers of EmployeeRepository should not import a driver error type, and should not have to guess which of SqlError or SchemaError a method can raise. The repository fails in exactly two places it owns — the statement and the row decode — so that is where the translation goes.
Self-contained source · Type-checked
ts
import { Context, Data, Effect, Layer, Option, Schema } from "effect"import { SqlClient, SqlSchema } from "effect/sql"import type { SqlError } from "effect/sql"class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int, name: Schema.String, email: Schema.String}) {}// One stable storage error. `cause` stays typed, so a caller that needs a domain// decision can still look at `cause.reason` (for example a specific UniqueViolation).class RepositoryError extends Data.TaggedError("RepositoryError")<{ readonly operation: string readonly cause: SqlError.SqlError | Schema.SchemaError}> {}// mapError touches the typed channel only: a defect stays a defect, interruption stays interruption.const owned = (operation: string) =><A, R>(self: Effect.Effect<A, SqlError.SqlError | Schema.SchemaError, R>) => Effect.mapError(self, (cause) => new RepositoryError({ operation, cause }))class EmployeeRepository extends Context.Service<EmployeeRepository, { readonly findById: (id: number) => Effect.Effect<Option.Option<Employee>, RepositoryError> readonly create: (employee: Employee) => Effect.Effect<void, RepositoryError>}>()("app/EmployeeRepository") { static readonly layer = Layer.effect( EmployeeRepository, Effect.gen(function*() { const sql = yield* SqlClient.SqlClient // received once, never opened per method const selectById = SqlSchema.findOneOption({ Request: Schema.Int, Result: Employee, execute: (id) => sql`select id, name, email from employees where id = ${id}` }) const insert = SqlSchema.void({ Request: Employee, execute: (employee) => sql`insert into employees ${sql.insert(employee)}` }) return EmployeeRepository.of({ findById: (id) => selectById(id).pipe(owned("EmployeeRepository.findById")), create: (employee) => insert(employee).pipe(owned("EmployeeRepository.create")) }) }) )}
Choice
Effect on callers
Use when
Effect.mapError into one tagged error (operation + typed cause)
One storage failure to handle; defects and interruption untouched
The default for a service that can degrade, retry, or report storage trouble.
Effect.orDie at the repository
No storage error in the signature; every fault becomes a defect
The failure is genuinely outside the contract — small tools, or a transport that only ever answers 500. You give up isRetryable and constraint-based decisions.
Effect.catchCause to build the error
Avoid. It also captures defects, so a programming bug is reported as a routine storage failure
—
Leaking SqlError / SchemaError through the service API
Every caller couples to the SQL stack
Inside the SQL implementation only.
Anti-patterns: opening connections inside methods, returning undecoded rows, and translating absence into an error the operation never defined. The transport maps RepositoryError to a declared endpoint error — see HttpApi; the outbox recipe uses this exact shape across two repositories.
Reach for it when you handle database failures deliberately — retrying deadlocks, mapping unique violations, or surfacing typed causes upstream.
The low-level, driver-facing contract under SqlClient. A Connection executes already-compiled SQL with positional params and can return transformed rows, raw results, a stream, value arrays, or unprepared results. It also defines the Acquirer (a scoped effect that checks a connection out of the pool) and the generic Row shape. SqlClient is the ergonomic front end; Connection is the raw executor a driver implements. Touch it directly only when using sql.reserve to pin a connection for an operation outside the statement abstraction.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { SqlClient } from "effect/sql"const headcount = Effect.gen(function*() { const sql = yield* SqlClient.SqlClient // sql.reserve is scoped: the connection returns to the pool when the scope closes const conn = yield* sql.reserve const values = yield* conn.executeValues("select count(*) from employees", []) return values // [[1234]]}).pipe(Effect.scoped)
Driver authors: SqlClient.make requires a driver name ("pg", "sqlite-node", …, exposed as sql.driver), and hand-written SqlClient implementations must provide that field. With the unstable SqlClient.makeWithTransaction, acquireConnection receives the interruption mask's restore and returns a scoped connection effect instead of a [scope, connection] tuple, and begin receives the BeginTransaction statement as its second argument; SqlClient.make also accepts a begin option for databases that need more than one statement to start a transaction. A driver whose acquirer or extra methods read its transaction service directly should pass the stored [connection, depth] tuple through SqlClient.activeTransactionConnection(transaction) immediately before using the connection: it fails with a SqlError once that transaction or an enclosing one has ended. Declare the driver's own service interface with extends SqlClient.Base (the client operations without the generic SqlClient type id), and tag it as Context.Service<MyClient, MyClient & SqlClient.SqlClient> so a yielded driver client is still usable wherever a SqlClient is expected — the pattern every shipped driver follows (see the migration note below).
Reach for it when implementing a new driver, or needing a pinned raw connection for operations the statement API does not model.
Versioned, transactional schema migrations. Records applied migration ids in a table (effect_sql_migrations by default), runs only pending ones in order inside a transaction, detects duplicate ids, and treats a concurrent run as locked rather than racing. A migration is a numbered file (0003_create_equity_grants.ts) whose default export is an Effect using SqlClient. A loader discovers them; the migrator diffs recorded vs. existing and applies the gap. Use the driver's Migrator.layer({ loader }) so migrations run during layer construction, before the service starts.
Self-contained source · Type-checked
ts
// migrations/0003_create_equity_grants.tsimport { Effect } from "effect"import { SqlClient } from "effect/sql"export default Effect.gen(function*() { const sql = yield* SqlClient.SqlClient yield* sql` create table equity_grants ( id serial primary key, employee_id integer not null references employees (id), shares bigint not null, strike_price numeric(12, 4), grant_date date not null, status text not null default 'active', created_at timestamptz not null default now(), unique (employee_id, status) ) `})
Self-contained source · Type-checked
ts
// Wire migrations into your layer graph (pg shown). They run before the app boots.import { Layer } from "effect"import { NodeServices } from "@effect/platform-node"import { PgClient, PgMigrator } from "@effect/sql-pg"import * as MigratorFileSystem from "effect/sql/MigratorFileSystem"const SqlLive = PgClient.layer({ database: "comp", username: "comp" })const MigratorLive = PgMigrator.layer({ // MigratorFileSystem is part of the unstable effect/sql module. loader: MigratorFileSystem.fromFileSystem("migrations"), schemaDirectory: "migrations" // optional: dump schema via pg_dump after success}).pipe( Layer.provide(SqlLive), Layer.provide(NodeServices.layer) // FileSystem + Path for the loader / dump)
Loaders: fromFileSystem(dir) lives in effect/sql/MigratorFileSystem (also re-exported by every driver migrator, such as PgMigrator.fromFileSystem, except @effect/sql-sqlite-react-native) and imports numbered .js/.ts/.mjs/.mts files, requires both FileSystem and a host-aware Path, and converts absolute paths to file URLs for Windows-safe ESM loading. Aggregate host layers satisfy both requirements—do not pair it with core's POSIX-only Path.layer on Windows. fromGlob(importMap) is the bundler-friendly route; fromRecord / fromBabelGlob cover in-code or transpiled setups. MigrationError carries a kind of BadState | ImportError | Failed | Duplicates | Locked, and every kind except Locked is a typed failure: a migration whose own effect fails is wrapped as kind: "Failed" with the original error as cause, so Effect.catchTag("MigrationError", ...) and retries see it. Locked is handled internally and turns the run into a no-op that returns an empty list. ClickHouse has no transactions, so ClickhouseMigrator runs each migration on its own and records it only after it succeeds; it creates and writes the migrations table as ClickHouse commands. Driver authors with the same need pass Migrator.make({ transformWrites }), which wraps only the migrations-table creation and inserts (default identity).
Migration:Migrator.fromFileSystem and the effect/sql barrel's fromFileSystem were removed so React Native's Metro bundler can import effect/sql; import it from effect/sql/MigratorFileSystem or from the driver's migrator module.
Tip: All pending migrations run inside onesql.withTransaction (ClickHouse excepted, as above). On PostgreSQL the migrator first takes an ACCESS EXCLUSIVE lock on the migrations table, so a concurrent instance waits and then finds nothing pending; on other dialects the loser's conflicting insert into the migrations table is reported as Locked and swallowed. Either way nothing is applied twice.
Migrations are production code: append-only, tested from real snapshots, and compatible with the release that is still running.
PostgreSQL migrations-table discovery uses to_regclass without intentionally failing a statement, so discovery does not poison an enclosing transaction. It quotes the configured table identifier consistently, and rechecks existence if another runner wins the initial table-creation race. This does not make arbitrary migration effects idempotent: keep the ordered ledger and database transaction as the authority.
Rule
Reason
Never edit an applied migration, and only ever add higher ids.
The migrator applies files whose id is greater than the latest recorded id and compares nothing else: an edited file is silently skipped wherever it already ran, and a lower-numbered migration merged late from another branch never runs at all.
One pending batch is one transaction — where the database allows it.
On PostgreSQL a failing migration rolls back the whole batch, earlier files included, and records nothing. Do not assume transactional DDL elsewhere: MySQL commits implicitly around DDL.
Expand → migrate → contract across releases.
During a rolling deploy old and new binaries share one schema, so additive changes ship first and destructive ones a release later.
Keep long backfills out of startup.
Migrator.layer runs during Layer construction, inside the migration transaction (and, on PostgreSQL, under the migrations-table lock); a long backfill blocks every replica's boot. Make backfills bounded, observable, restartable jobs.
Decide who migrates.
Running on every instance is safe against double-apply, but a dedicated migration job keeps DDL privileges out of the runtime role and keeps failure handling in one place. Verify the locking behavior on the real database.
Recover forward.
Ship a fixing migration and rely on restore-tested backups; a down migration is not a backup.
Test the schema, not the ledger.
Run migrations from empty and from a representative prior snapshot; assert constraints, indexes, defaults, and backfilled values — not merely rows in effect_sql_migrations.
Reach for it when you need reproducible, ordered schema evolution checked into the repo and applied automatically on deploy.
The directory loader for Migrator, kept out of effect/sql/Migrator and the effect/sql barrel because its dynamic import() breaks React Native's Metro bundler. MigratorFileSystem.fromFileSystem(directory) returns a Loader<FileSystem | Path> that imports <id>_<name>.js/.ts/.mjs/.mts files sorted by id. Import it by its subpath (effect/sql/MigratorFileSystem) or through a driver's migrator (PgMigrator.fromFileSystem, SqliteMigrator.fromFileSystem, …); @effect/sql-sqlite-react-native deliberately does not re-export it, so bundle migrations there with Migrator.fromRecord or fromGlob.
Define a table's shape once as a Model schema and derive a typed CRUD repository — insert, insertVoid, update, updateVoid, findById, delete — automatically. A Model.Class is a family of variants built on VariantSchema: the same definition yields a select schema, an insert schema (db-generated columns dropped), an update schema, and JSON-API variants (json, jsonCreate, jsonUpdate). SqlModel.makeRepository reads those variants to type each operation correctly. Insert/update inputs are encoded with the model's input variants, returned rows decoded with the full model, and dialect quirks (pg RETURNING vs. mysql LAST_INSERT_ID) are handled automatically.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { Model } from "effect/schema"import { SqlModel } from "effect/sql"const EmployeeId = Schema.Int.check(Schema.isGreaterThan(0)).pipe(Schema.brand("EmployeeId"))// Model and SqlModel are part of the unstable effect/schema and effect/sql modules.// One definition -> select / insert / update / json variantsclass Employee extends Model.Class<Employee>("Employee")({ // A repository needs its id in select + update, but not insert. id: EmployeeId.pipe(Model.FieldExcept(["insert"])), name: Schema.String, level: Schema.String, departmentId: Schema.Int.check(Schema.isGreaterThan(0)), baseSalary: Schema.Finite, createdAt: Model.DateTimeInsertFromDate, // set on insert updatedAt: Model.DateTimeUpdateFromDate // bumped on update}) {}// Derive a repository bound to the SqlClient in contextconst makeEmployees = SqlModel.makeRepository(Employee, { tableName: "employees", spanPrefix: "Employees", idColumn: "id"})const program = Effect.gen(function*() { const employees = yield* makeEmployees // insert takes the insert variant (no id/createdAt to supply), returns a full Employee const created = yield* employees.insert(Employee.insert.make({ name: "Ada Lovelace", level: "L5", departmentId: 7, baseSalary: 195_000 })) const found = yield* employees.findById(created.id) // Effect<Employee, NoSuchElementError | ...> yield* employees.delete(created.id) return found})
Pass softDeleteColumn and deletes flip that column to CURRENT_TIMESTAMP while every read filters out soft-deleted rows automatically. SqlModel.makeResolvers returns RequestResolvers (insert, insertVoid, findById, delete) so model lookups participate in request batching. It is scoped (SqlClient | Scope), and requests made through the insert resolver also require the model's decoding services, because it decodes the returned row; use insertVoid when you do not need the row back.
Reach for it when a schema model maps cleanly to a table and you want standard CRUD without re-typing insert/update/select shapes — drop to a raw sql tagged template for anything bespoke.
Size pools from the database-wide budget, not per service. Replicas × maxConnections, plus migration jobs, listeners, long streams, and an admin reserve, must fit under the server's connection limit. A bigger pool is not backpressure — bound application admission instead (see Semaphore).
Know what holds a connection. A transaction, a .stream, sql.reserve, and a listen subscription keep one for their whole lifetime; an ordinary statement borrows one briefly. With @effect/sql-pg's multiplex, plain statements share connections, but transactions, streams, and listeners still reserve one each.
Result streaming is driver-dependent. The native PostgreSQL client streams incrementally on a pinned session and cancels the statement when the stream is abandoned; PGlite's .stream runs the query to completion and then emits the rows. Consume streams inside a scope, keep buffers bounded, and prefer keyset pagination over a stream that would hold a connection for hours.
Interruption expresses cancellation intent; the driver decides what reaches the server.@effect/sql-pg sends a PostgreSQL CancelRequest for an interrupted statement, except on an unpinned multiplexed connection, where cancelling could hit another fiber's query. @effect/sql-mysql2 stops an interrupted statement or stream with KILL QUERY sent over a separate one-off connection, keeps the pool connection until the statement has settled (destroying it if the kill and the statement have not settled within five seconds), and makes statements that share one transaction or reserved connection run one at a time, so a kill reaches only the interrupted statement; an interrupted wait for a connection in sql.reserve or withTransaction returns at once. For other drivers, verify whether server-side work is cancelled or merely abandoned.
Watch the pool, and bound the wait.PgClient.poolStats (and PgPool.stats) sample { idle, used, pending, min, max } for exporting pool metrics; a single-session client from makeClient always reports one used connection. acquireTimeout on PgClient / PgPool fails a borrower with a ConnectionError reason when the pool stays exhausted, and onAcquire runs an effect in the borrowing fiber after each checkout (per checkout, not per socket); its requirements become requirements of the client layer.
Give readiness probes a short deadline and their own headroom. A probe that queues behind a saturated pool turns overload into a restart loop. Keep liveness independent of the database.
Never log connection strings, full parameter lists, or personal row values. Name operations with low-cardinality, allow-listed span names (Effect.fn("Employees.findById")) rather than interpolated text, and remember that db.query.text is exported with every statement span.
Behavior of a different engine — SQLite does not prove PostgreSQL
Application graph
Only external systems
Layer wiring, pool sharing, startup order
Production load, contention
Mandatory contract cases: valid and malformed rows; zero / one / many cardinality; the specific constraint each domain conflict maps from; rollback across two repositories sharing one client; savepoints; contention and transient-error classification; timeout and interruption; pool exhaustion; stream cleanup. In-process PGlite gives a genuine PostgreSQL dialect for the fast lane; pin the container image for the real-server lane, isolate a database per test worker, and keep logs on failure. An in-memory SQLite database may be per connection, which breaks pool assumptions.
Each driver is a thin satellite package contributing a Layer producing SqlClient wired to a real connection and the correct dialect compiler. All expose layer(config) and layerConfig(Config.Wrap<...>), and most ship a matching *Migrator. Each layer provides both the driver's own service (PgClient.PgClient, MysqlClient.MysqlClient, …) and the generic SqlClient.SqlClient; yielding the driver service gives a value that is also a SqlClient, so it can be passed to code written against the generic client.
Migration: driver client interfaces (PgClient, PgliteClient, MysqlClient, MssqlClient, SqliteClient, LibsqlClient, D1Client, ClickhouseClient) extend SqlClient.Base instead of SqlClient.SqlClient, so a driver requirement is no longer a subtype of the generic one. Previously, providing only a generic SqlClient layer silently removed a requirement such as PgClient from an effect's type, and the program failed at runtime with Service not found; now that requirement stays visible until the driver layer is provided. Code that chooses between driver layers at runtime may need an explicit Layer.Layer<SqlClient.SqlClient, E> annotation, because the two layers' output types no longer unify on their own.
Fragment · Type-checked
ts
import { PgClient } from "@effect/sql-pg"import { PgliteClient } from "@effect/sql-pglite"import type { Layer } from "effect"import type { SqlClient, SqlError } from "effect/sql"declare const useEmbedded: boolean// Pick a driver at startup; downstream code only asks for the generic SqlClient.export const Database: Layer.Layer<SqlClient.SqlClient, SqlError.SqlError> = useEmbedded ? PgliteClient.layer() : PgClient.layer({ database: "comp", username: "comp_api" })
pkg @effect/sql-pg — PostgreSQL through Effect's native wire-protocol client (no pg, pg-pool, or pg-types dependency). Dialect pg with $1 placeholders and RETURNING. The native stack handles connection setup, binary codecs, named prepared statements, optional pipelining (multiplex), streaming, cancellation, and notifications. PgClient.layer / layerConfig build a layer; PgClient.make(PgPoolConfig) builds a pool and PgClient.makeClient(PgClientConfig) a single connection. PgMigrator shells out to pg_dump for schema dumps. Result decoding, JSON parameters, statement limits, prepared statements, and listen() are covered in Native client behavior: codecs, JSON, and LISTEN. Session defaults, TLS mode, and rotating passwords are configured per physical connection (Session settings at connect time). Span names and the db.namespace, server.address, and server.port attributes follow the resolved connection — a url included — and db.namespace falls back to the user name, as PostgreSQL does, when no database is configured. If the server ends the session mid-transaction, withTransaction fails with a typed SqlError rather than a defect.
pkg @effect/sql-mysql2 — MySQL / MariaDB via the mysql2 driver. ? placeholders; inserts/updates use the LAST_INSERT_ID + reselect path. Set disablePreparedStatements: true to use mysql2's text protocol globally, notably for proxies such as Cloudflare Hyperdrive that do not support COM_STMT_PREPARE. Every statement outside a transaction checks out its own pool connection, so an interrupted one can be stopped with KILL QUERY (see Pools, reservations, and streaming); a SET TRANSACTION …BeginTransaction runs just before BEGIN.
pkg @effect/sql-mssql — Microsoft SQL Server (Azure SQL). mssql dialect with its own identifier quoting and migrations table DDL. Its extended MssqlClient adds param(type, value, options?) for typed Tedious parameter fragments and call(Procedure.compile(...)) for stored procedures; Procedure.make, param, outputParam, and withRows track inputs, outputs, and row types. TLS encryption and certificate validation are enabled by default; use encrypt: false only for a server without TLS, or trustServer: true for an explicitly trusted self-signed certificate.
pkg @effect/sql-sqlite-node — SQLite through Node's built-in node:sqlite module (requires Node 22.16+). File-based and synchronous; ideal for tests, CLIs, and local-first apps. The extended client exposes backup(destination) with page-count metadata and loadExtension(path); streaming queries and updateValues are unsupported. Its default five-second busy timeout and immediate transactions serialize competing writers and can block the event loop while SQLite is busy, so tune them for latency-sensitive applications. A transaction left open by a failed COMMIT — a deferred foreign key violation, for example — is rolled back so the connection can be reused.
pkg @effect/sql-sqlite-bun — SQLite using Bun's built-in bun:sqlite. Same dialect, zero extra native deps on Bun. file: SQLite URI filenames open correctly on Linux, including the readonly and create options. Streaming queries are not implemented. As with @effect/sql-sqlite-node, a transaction left open by a failed COMMIT is rolled back so the connection can be reused.
pkg @effect/sql-sqlite-wasm — SQLite compiled to WebAssembly via @effect/wa-sqlite, in-memory in the current runtime or connected to an OPFS-backed worker for durable storage. Only the in-memory client can stream query rows; the worker-backed client cannot. updateValues is unsupported by this driver.
pkg @effect/sql-d1 — Cloudflare D1, the edge SQLite service. Bind a D1 database and query it with the same sql tagged-template API from a Worker. Its D1Client.batch(statements) sends a fixed tuple as one atomic D1 batch — executed directly on the binding, so it cannot join a SqlClient transaction — and returns typed results in statement order. Transactions, streaming queries, and updateValues are not supported by this driver.
pkg @effect/sql-sqlite-react-native — SQLite on React Native via @op-engineering/op-sqlite. Uses the driver's synchronous query API by default; AsyncQuery / withAsyncQuery switch a scoped effect to the asynchronous API. Streaming queries and updateValues are not supported by this driver.
pkg @effect/sql-sqlite-do — SQLite backed by a Cloudflare Durable Object's storage — per-object strongly-consistent SQL at the edge. Nested withTransaction calls roll back independently of their parent, a failure to complete the native storage transaction surfaces as SqlError, and storage-backed transactions do not yield to the scheduler automatically (a queued fiber could deadlock the Durable Object's input gate). Explicit asynchronous work inside a transaction is unsupported.
pkg @effect/sql-clickhouse — ClickHouse for analytics/OLAP. clickhouse dialect tuned for columnar, append-heavy workloads: its compiler reports the clickhouse dialect, so sql.onDialect / onDialectOrElse fragments pick the ClickHouse branch, and connection validation uses ClickHouse's ping() endpoint, with failed health checks as SqlError. ClickhouseClient.insertQuery accepts a columns option — an array (["a", "b"]) to insert into a subset of columns, or { except: ["a"] } for all columns except the listed ones.
pkg @effect/sql-libsql — libSQL / Turso — SQLite-compatible with remote HTTP/edge protocol and embedded replicas. Each client exposes its active transaction through its transactionService tag. On remote (http and ws) clients, independent statements and transactions run concurrently up to the SDK's concurrency limit, so concurrent write transactions contend on the server's write lock rather than queueing in the client; local-file, :memory:, and embedded-replica clients still run one statement or transaction at a time.
pkg @effect/sql-pglite — PGlite: Postgres compiled to WASM. Genuine pg dialect that runs in-process or in the browser — great for tests and local dev. Its extended client adds notify and a scoped listen(channel) — an Effect yielding a Queue.Dequeue<string> of payloads, not a Stream — plus dumpDataDir(compression?) for portable snapshots, and refreshArrayTypes after extensions or schema changes introduce array types.
Put per-session defaults in the connection config, not in a SET statement. A SET issued through sql changes one pooled connection and disappears when the pool replaces it. PgClient.layer (and PgConnection.make / PgPool.make) send session defaults in the startup packet of every physical connection: the first one, each connection the pool adds, and each replacement after idleTimeout, connectionTTL, or a failure. RESET ALL returns a session to these defaults.
The pool also recovers failed connections on its own: a background acquisition that fails is retried while a caller is still waiting to borrow one, and a connection that reports a fatal session error is replaced before the next borrow rather than handed out broken. A statement interrupted mid-flight whose CancelRequest is never confirmed by the server retires that session instead of returning it to the pool. Named prepared statements are namespaced per connection, so two connections never collide on the same statement name. If PostgreSQL answers a COMMIT with ROLLBACK after a caught statement error, the transaction fails instead of reporting a false commit. Closing a connection sends Terminate and destroys the socket once that message has flushed (or after one second), without waiting for the peer's FIN, so a half-open proxy cannot pin released sockets.
Field
Shape
Behavior
startupParameters
Record<string, string> of PostgreSQL settings
Names are lowercased. user, database, replication, and options are reserved (use username, database, and startupOptions). client_encoding accepts only UTF8 / UTF-8. PostgreSQL validates every other name and value when the connection opens.
startupOptions
one opaque string, sent as the packet's options field, e.g. "-c lock_timeout=2000"
Overrides the URL's ?options= query parameter, even when the explicit value is empty. It is forwarded without parsing, so do not set the same setting here and in startupParameters.
applicationName
string
The startup application_name is the first of: applicationName, startupParameters.application_name, the URL's application_name, "@effect/sql-pg". It is never read out of startupOptions.
password
Redacted or Effect<Redacted> with no error and no requirements
An Effect runs for each connection attempt and for each PgMigrator schema dump, which suits short-lived cloud IAM tokens. Handle its failures inside the Effect; Effect.orDie turns them into defects, not retryable SqlErrors.
Fragment · Type-checked
ts
import { PgClient } from "@effect/sql-pg"import { Effect, Redacted } from "effect"// Mints a short-lived database token (for example from a cloud IAM signer).declare const signDatabaseToken: Effect.Effect<string>export const CompDatabase = PgClient.layer({ url: Redacted.make("postgres://comp_api@db.internal:5432/comp?sslmode=require"), password: Effect.map(signDatabaseToken, (token) => Redacted.make(token)), // fresh per connection applicationName: "comp-api", // shows up in pg_stat_activity next to each payroll query startupParameters: { TimeZone: "UTC", // `Date` parameters written to `timestamp` columns keep their UTC fields statement_timeout: "30s", // a runaway comp-band report cannot hold a connection forever search_path: "comp, public" }, startupOptions: "-c lock_timeout=2000" // opaque; wins over a URL `options` parameter})
The driver checks the fields it owns (empty names, NUL bytes, reserved names, a non-UTF-8 client_encoding) before it opens a socket. The pool is lazy, though, so the layer still builds, and the first query fails with a SqlError whose reason is ConnectionError. That reason reports isRetryable: true, so a retry loop around the query spins on a configuration typo; run one query in a readiness check, and let a bounded schedule end any retry.
TLS follows the URL's sslmode unless ssl is set explicitly. sslmode=prefer and sslmode=allow both try TLS first and fall back to plaintext only when the server declines the SSLRequest; handshake and certificate failures stay fatal. An attacker on the path can make the server appear to decline, so production connections should use sslmode=require or ssl: true.
keepAlive: Duration.Input enables native TCP keepalive after the configured idle duration (whole-second precision, minimum one second); omission leaves it disabled. Unix sockets and custom streams are unaffected. It is not a query/write deadline: bound application operations with Effect.timeout as well.
Native client behavior: codecs, JSON, and LISTEN
@effect/sql-pg speaks the PostgreSQL wire protocol itself — there is no pg, pg-pool, or pg-types dependency. That native stack decides what comes back from a query and what the server will accept as a parameter.
Result decoding (binary codecs).int8 decodes as bigint; date decodes as a string; timestamp and timestamptz decode as a Date at millisecond precision, with infinity, -infinity, and any value outside the JavaScript Date range (±8.64e15 epoch milliseconds) decoding to an invalidDate — Schema.Date rejects an invalid Date, so map those sentinels in SQL if a column can hold them. bytea decodes as Uint8Array. oid and regclass both decode as a numeric OID; cast ::text in SQL to get a readable name. inet and cidr decode as formatted strings (through the same formatting NetAddress, IpInterface, and IpNetwork use), not as typed IpInterface / IpNetwork objects. An OID with no registered codec — an enum, an extension type, any other user-defined type — decodes as UTF-8 text, so a scalar enum column returns its label. A value that cannot be text fails with PgTypes.CodecError: invalid UTF-8, or a NUL byte, which PostgreSQL text output never contains and binary layouts almost always do — so enum arrays, composites, PostGIS geometries, and pgvector vector columns fail rather than decode. The error names the column, its type OID, and (for a table column) the table OID and attribute number; it fails only the query that read the row, and the connection, its transaction, and its LISTEN channels stay usable. A binary layout with no zero bytes at all (ltree, for example) still decodes as garbled text without an error. Register a codec for any of those (below), or cast the column to text in SQL, rather than relying on the fallback. Decode rows with Schema.Date, Schema.DateTimeUtcFromDate, Model.DateTimeInsertFromDate / DateTimeUpdateFromDate, and Schema.Literals([...]) for enum columns.
Parameters. A plain object parameter is not inferred as JSON — wrap it with sql.json(value). The timestamp and timestamptz encoders (PgTypes.timestamp(value), PgTypes.timestamptz(value)) accept a Date or epoch milliseconds; encoding an invalid Date fails. A Date interpolated with ${} binds as timestamptz, so inserting it into a timestamp (without time zone) column converts it through the session TimeZone. Either run sessions in UTC (TimeZone: "UTC" at connect time) or bind PgTypes.timestamp(date), which stores the Date's UTC fields whatever the session zone is; timestamptz round trips preserve the instant in any zone. Otherwise inferred parameters stay permissive: strings bind untyped so the server derives the type from the statement, and safe integers beyond the int4 range bind as int8.
One statement per query string. The extended protocol rejects more than one statement per string, even through stmt.unprepared — split migrations and seed scripts into separate statements.
Prepared statements are named and on by default, cached per connection (preparedStatementCacheSize, default 100) and namespaced so two connections never collide on the same statement name. Behind a pooler that cannot keep named statements between queries (PgBouncer in transaction mode with max_prepared_statements = 0), set prepare: false. If a pooler drops prepared statements anyway, the transaction still ends: rollbacks run unprepared, and a pinned session released while its transaction is still aborted is closed rather than returned to the pool. Statement.unprepared / valuesUnprepared use unnamed extended queries without touching the cache.
listen(channel) is a scopedEffect yielding Queue.Dequeue<PgConnection.Notification, SqlError> ({ processId, channel, payload }), returned only after PostgreSQL confirms LISTEN. Take from the queue inside a scope. Because acquisition completes after confirmation, a notification sent right after it returns cannot be missed. The listener holds a connection until the scope closes; a connection failure after LISTEN fails the queue with the original SqlError, while closing the scope still interrupts.
Raw results.executeRaw returns a PgConnection.Result, the native client's own result shape.
New tuning knobs beyond the ones above include multiplex / multiplexConcurrency (pipelining several statements over one connection), maxMessageSize, and the pool options minConnections, maxConnections, idleTimeout, and connectionTTL. Pass Statement.SpanPropagationEnabled (default false) with Effect.provideService to parent driver spans under the statement span.
A per-client PgTypes.Registry starts from the built-in codecs and overrides them without touching other clients. Use it for enum arrays, and for any type that needs a codec the built-ins do not provide:
Fragment · Type-checked
ts
import { PgClient, PgTypes } from "@effect/sql-pg"import { Result } from "effect"// The `raise_status` enum and its array type. Read them once with// select oid, typarray from pg_type where typname = 'raise_status'declare const raiseStatusOid: numberdeclare const raiseStatusArrayOid: number// An enum's binary form is its label, so the text codec fits.const label: PgTypes.Codec<string> = { encode: (value) => PgTypes.encode(value, PgTypes.OID.text), decode: (bytes) => Result.map(PgTypes.decode(bytes, PgTypes.OID.text, 1), String)}const types = PgTypes.makeRegistry()// raise_status[] now decodes to Array<string> instead of garbled text.types.register(raiseStatusOid, label, { arrayOid: raiseStatusArrayOid })// Temporary: timestamptz back to epoch milliseconds (arrays follow the element codec).types.register(PgTypes.OID.timestamptz, { encode: (value: number) => PgTypes.encode(value, PgTypes.OID.timestamptz), decode: (bytes) => Result.map(PgTypes.decode(bytes, PgTypes.OID.timestamptz, 1), (date) => (date as Date).getTime())})export const CompDatabase = PgClient.layer({ database: "comp", username: "comp_api", types })
PgTypes.register(oid, codec) does the same for every client in the process and has no arrayOid option.
A listener that survives connection loss is a Stream that re-runs listen on failure. PostgreSQL does not replay notifications sent while nobody was listening, so treat a notification as a wake-up signal and re-read the source of truth after each (re)registration:
Self-contained source · Type-checked
ts
import { PgClient } from "@effect/sql-pg"import { Effect, Schedule, Stream } from "effect"// Wake the payroll outbox relay early; polling stays the safety net.export const outboxWakeups = Stream.unwrap(Effect.gen(function*() { const pg = yield* PgClient.PgClient const notifications = yield* pg.listen("payroll_outbox") return Stream.fromQueue(notifications)})).pipe( // A dropped listener connection fails the stream with its SqlError; LISTEN again. Stream.retry(Schedule.exponential("500 millis")))
Note: Typical usage: build SqlLive = PgClient.layer({ ... }), run PgMigrator.layer({ loader }) on top at startup, define table models as Model.Class, derive repositories with SqlModel.makeRepository, reach for SqlResolver in resolvers to batch lookups, and drop to the sql tagged-template API plus SqlSchema for anything custom. One client service, swappable driver, typed all the way down.
Effect's platform layer separates service interfaces (in the core effect package, runtime-agnostic) from concrete implementations (provided as a Layer from @effect/platform-node, @effect/platform-bun, @effect/platform-deno, or @effect/platform-browser; the experimental @effect/platform-cloudflare hosts Effect Cluster on Durable Objects). Business logic imports only from effect/*; only the entrypoint imports the platform package. Swapping the Layer swaps the runtime.
Official guides:Introduction to Effect Platform (its module table lists a PlatformLogger that this release does not ship — the function is Logger.toFile — and it routes Deno through @effect/platform-node, while Effect also publishes a dedicated @effect/platform-deno). These guides track Effect's main branch rather than this stable release, so where they differ, this page and the tagged source win.
Service interface for filesystem operations: read, write, stat, copy, move, delete, make directories, create temp paths, stream bytes, watch for changes. Discrete operations return an Effect failing with PlatformError (BadArgument or SystemError carrying the OS reason); stream and watch expose that failure through a Stream. PlatformError.isPlatformError(error) is a type guard for narrowing an unknown caught value — useful at a boundary that re-throws or logs errors from several sources.
Mental model: typed composable wrapper over node:fs/promises, working identically on Bun. Business modules import from effect/FileSystem; the entrypoint imports NodeFileSystem.layer. Use FileSystem.layerNoop to stub in tests.
Common methods: readFileString / writeFileString (text), readFile / writeFile (Uint8Array), exists, stat, makeDirectory, copy, remove, stream (lazy byte Stream, configurable chunk size), and glob(pattern, { root, exclude, dot }) (it reads subdirectories concurrently, in at most 16 forked fibers per call, and returns results in a stable order). watch(path) observes direct children by default; pass { recursive: true } for subdirectories. Scoped helpers makeTempDirectoryScoped and makeTempFileScoped auto-clean on scope close. An opened File is the public handle type; its seek(offset, from) takes and returns a plain bigint position and rejects a negative result with BadArgument, leaving the cursor unchanged (there is no public FileDescriptor type).
The service covers the whole node:fs surface, so reaching for raw node:fs costs typed errors and testability without buying an operation:
Group
Operations
Whole-file I/O
readFile, readFileString, writeFile, writeFileString (both writes take flag and mode)
Streams and handles
stream (lazy bytes), sink (a byte Sink; opens with flag "w" unless you pass one, so use { flag: "a" } to append), open (a scoped File: read, readAlloc, write, writeAll, seek, truncate, sync, stat)
Directories and trees
makeDirectory (recursive), readDirectory (recursive), readDirectoryEntries (names with a File.Type), glob, copy (like cp -r), rename, remove (recursive, force)
exists, access (readable, writable), stat, lstat (does not follow a final symlink), chmod, chown, utimes
Temporary paths
makeTempDirectory, makeTempFile, and the …Scoped variants that delete on scope close
Change notification
watch
Sizes are ByteSize values.File.Info.size is a stable ByteSize.ByteSize — an exact non-negative bigint brand — so compare it with ByteSize.isGreaterThan and friends rather than with >; there is no separate FileSystem.Size brand or KiB / MiB / GiB / TiB / PiB family on FileSystem. stream's offset and bytesToRead accept any ByteSize.Input; chunkSize and truncate's length are plain numbers. The 64-bit stat metadata uses exact arithmetic: dev is bigint, while ino, rdev, and blocks use Option<bigint>; unavailable optional metadata remains Option.none(). The same exact-arithmetic treatment reaches HTTP file responses: HttpPlatform clamps a requested range to the file's size, so Content-Length always matches the bytes actually sent.
Self-contained source · Type-checked
ts
import { ByteSize, FileSystem } from "effect"import { NodeFileSystem } from "@effect/platform-node"import { Effect, Layer, Stream } from "effect"// Read a comp-bands CSV and stream large files in chunksconst loadCompBands = Effect.gen(function*() { const fs = yield* FileSystem.FileSystem // Load the comp-bands definition for this merit cycle const csv = yield* fs.readFileString("./data/comp_bands.csv") const bands = csv.split("\n").slice(1).map((row) => { const [level, min, mid, max] = row.split(",") return { level, min: Number(min), mid: Number(mid), max: Number(max) } }) // Write a lock file so a second process knows the import is running const lockExists = yield* fs.exists("./data/.import.lock") if (!lockExists) { yield* fs.writeFileString("./data/.import.lock", `started:${new Date().toISOString()}`) } // Stat the full employee dump — stream it if it's large const info = yield* fs.stat("./data/employees.bin") if (ByteSize.isGreaterThan(info.size, ByteSize.mebibytes(100))) { yield* Effect.log(`large employee dump (${ByteSize.format(info.size, { system: "binary" })}), streaming instead`) const bytes = fs.stream("./data/employees.bin", { chunkSize: 64 * 1024 }) yield* bytes.pipe(Stream.runDrain) } // Scoped temp file for an in-progress export — deleted automatically const tmp = yield* fs.makeTempFileScoped({ prefix: "merit-export-" }) yield* fs.writeFileString(tmp, JSON.stringify(bands)) yield* Effect.log(`staged comp bands at: ${tmp}`) return bands})// Entrypoint wires in the Node implementationconst program = loadCompBands.pipe( Effect.provide(NodeFileSystem.layer), // ... NodeRuntime.runMain)
fs.glob(pattern, options) is one shared implementation on Node, Bun, and Deno, using the Glob syntax. Results are /-separated paths relative to root (default: the working directory), or absolute when the pattern is absolute, visited depth-first with each directory sorted by name. Wildcards skip dotfiles unless the segment starts with . or dot: true; ** does not descend through directory symlinks; an exclude match drops the path and prunes the directory so it is never read. A missing path yields [], an unreadable directory reached through a wildcard is skipped, and a read failure at root or at a leading literal directory fails with PlatformError. Patterns use / and backslash escapes on every host, and extglobs are not expanded.
Migration: a custom FileSystem passed to FileSystem.make must now supply lstat and readDirectoryEntries (mapping readDirectory names to { name, type: "Unknown" } is acceptable; glob then falls back to stat). make derives glob and no longer accepts one, so override it afterwards with FileSystem.of({ ...fs, glob: customGlob }). Wrappers that rewrite directory listings must change both readDirectory and readDirectoryEntries.
fs.watch(path) returns a Stream<WatchEvent> whose tags are Create, Update, and Remove. Watching is host-dependent and may fail with PlatformError. A caller-provided FileSystem.WatchBackend is honored at the watch call, so provide it around consumption rather than assuming the backend was captured when the filesystem layer was built. open supports noFollow, and handle reads accept explicit positions without advancing the implicit cursor.
When to use: any filesystem I/O in an Effect program. Use FileSystem.layerNoop to stub in unit tests.
FileSystem.layerNoop(partial) builds a complete service from only the methods the code under test calls (FileSystem.makeNoop(partial) is the same object without the Layer, for Effect.provideService). A forgotten override is loud, not silent: most defaults fail with a typed PlatformError whose reason is NotFound; makeDirectory and the makeTemp* family die with not implemented; only exists (answers false) and remove (succeeds) are quiet.
Pure path matching with the same syntax FileSystem.glob uses, without touching a disk. Glob.make(pattern, { dot? }) compiles a reusable value, Glob.match(glob, path) (dual) tests a /-separated path, and Glob.escape(text) makes a literal file name match only itself. Syntax: * and ? within one segment, [...] classes (with !/^ negation and POSIX classes such as [[:digit:]]), nested {a,b} alternatives, ** as a whole segment for zero or more segments (so dir/** matches dir too), a trailing / for directories only, and \ escapes. Wildcards never match . or .. and skip dot-names unless dot is set. Leading ! negation and extglobs are not interpreted, malformed syntax such as an unclosed [ matches literally, and UNC paths never match.
Reach for it when filtering paths you already have (an upload's file list, a zip's entries, a watch event) with the same rules as a file-system search.
Service interface wrapping platform path utilities: join, resolve, dirname, basename, extname, normalize, relative, isAbsolute, parse, format, plus effectful fromFileUrl and toFileUrl helpers. The sep property gives the platform separator.
Mental model: node:path as a service. Core Path.layer deliberately provides POSIX semantics. On Node/Bun/Deno, the aggregate host layer supplies the host-aware implementation; Node also exposes NodePath.layerPosix and NodePath.layerWin32 for cross-platform tooling and tests.
fromFileUrl and toFileUrl are effectful because malformed or unsupported URLs fail with PlatformError.BadArgument; use them instead of slicing file: strings by hand.
resolveWithin(root, input) returns Option<string> after checking containment using the implementation's path semantics, unlike a raw prefix check; rooted inputs and escapes return None. It is a lexical boundary, not protection against symlinks or filesystem races: combine it with an appropriate file-opening policy for untrusted paths.
When to use: building or decomposing file paths inside an Effect. Inject via service rather than calling path.join directly so tests can control path logic.
Interactive terminal I/O: query dimensions (columns, rows), follow resizes (size), read a line (readLine), receive a stream of key events (readInput), display text (display). Input reading fails with QuitError on Ctrl+C or Ctrl+D.
size is a scoped Effect yielding a Queue.Dequeue<Terminal.Size> ({ columns, rows }) that starts with the current dimensions, receives each resize until its scope closes, and keeps only the latest value, so a slow renderer never processes stale sizes.
Mental model: the abstraction @effect/cli builds on. Provide a fake terminal in tests via Terminal.make to assert output and simulate input without a real TTY. Migration: the object passed to Terminal.make must now include size; a fixed-size fake can return a queue offered one Size.
Self-contained source · Type-checked
ts
import { Effect, Queue, Terminal } from "effect"// Re-render a status table whenever the terminal is resized.export const followResizes = Effect.gen(function*() { const terminal = yield* Terminal.Terminal const sizes = yield* terminal.size while (true) { const { columns } = yield* Queue.take(sizes) yield* terminal.display(`${"=".repeat(columns)}\n`) }}).pipe(Effect.scoped)
Self-contained source · Type-checked
ts
import { Terminal } from "effect"import { Effect } from "effect"// Interactive CLI prompt for confirming a merit cycle runconst confirmMeritRun = Effect.gen(function*() { const terminal = yield* Terminal.Terminal yield* terminal.display("Confirm merit cycle run? [y/N] ") const answer = yield* terminal.readLine if (answer.toLowerCase() !== "y") { yield* Effect.log("Aborted by user.") return false } yield* terminal.display("Starting merit cycle processing...\n") return true})// QuitError surfaces if user hits Ctrl+C — handle or let it propagate
Re-prompt by recursion, deferred with Effect.suspend. A validation loop is the prompt calling itself; suspend makes the self-reference lazy so each retry is built only when it is needed. The error channel is the union of the two operations: readLine fails with QuitError, display with PlatformError.
Self-contained source · Type-checked
ts
import { Effect, Option, Terminal } from "effect"import type { PlatformError } from "effect"const parsePercent = (input: string): Option.Option<number> => { const value = Number(input.trim()) return input.trim() !== "" && value >= 0 && value <= 25 ? Option.some(value) : Option.none()}// Ask until the answer parses. Ctrl+C / Ctrl+D ends the loop as QuitError.const askMeritPercent: Effect.Effect< number, Terminal.QuitError | PlatformError.PlatformError, Terminal.Terminal> = Effect.gen(function*() { const terminal = yield* Terminal.Terminal yield* terminal.display("Merit increase % (0-25): ") const answer = parsePercent(yield* terminal.readLine) if (Option.isSome(answer)) return answer.value yield* terminal.display("Enter a number between 0 and 25.\n") return yield* Effect.suspend(() => askMeritPercent)})
A small script does not need the whole aggregate: NodeTerminal.layer (or BunTerminal.layer) provides Terminal alone.
When to use: CLIs, interactive prompts, or TUI-adjacent tools requiring testable platform-independent I/O.
Lower-level counterpart to Terminal: process.argv via args, write Sinks for stdout and stderr (accepting string | Uint8Array), raw byte Stream for stdin, and stdinIsTerminal / stdoutIsTerminal / stderrIsTerminal effects for adapting output to pipes versus TTYs. I/O can fail with PlatformError. Stdio.layerTest lets you stub any field for unit testing.
Mental model: where Terminal is for interactive programs, Stdio is for pipeable Unix-filter style tools — read stdin, write stdout, parse argv.
Self-contained source · Type-checked
ts
import { Stdio } from "effect"import { Effect, Stream } from "effect"// A pipeable tool that accepts NDJSON employee records on stdin// and echoes validated records to stdoutconst validateEmployeeStream = Effect.gen(function*() { const stdio = yield* Stdio.Stdio const args = yield* stdio.args // ReadonlyArray<string> const interactive = yield* stdio.stdoutIsTerminal yield* Effect.log(`argv: ${args.join(" ")}`) yield* Effect.log(`stdout is ${interactive ? "interactive" : "redirected"}`) // Pipe stdin → decode text → validate → stdout yield* stdio.stdin.pipe( Stream.decodeText(), Stream.map((chunk) => chunk.trim()), Stream.filter((line) => line.length > 0), Stream.run(stdio.stdout()) )})
When to use: streaming CLI tools, stdin byte processing, or typed argv access without globals.
Platform-neutral abstraction for a bidirectional socket (TCP, Unix domain, or WebSocket). A Socket is pull-based: it exposes a scoped reader and a scoped writer, and nothing is read from the transport until the consumer pulls.
socket.reader — acquiring it dials the connection; its scope owns the connection lifetime. It yields a Reader whose pull returns the next non-empty batch (one buffer for TCP, one entry per WebSocket frame) and whose upgrade(options?) wraps a live connection in TLS (STARTTLS) using TlsUpgradeOptions (key/cert/ca/passphrase/alpnProtocols/requestCert/rejectUnauthorized); an adapter that cannot upgrade in place fails with SocketUpgradeError. Socket.readerBytes(socket) and Socket.readerString(socket, encoding?) acquire a pull already normalized to Uint8Array or string; readerString decodes binary frames with one streaming decoder per acquisition, so a character split across frames is kept intact, and flushes leftover bytes (as U+FFFD) before a text frame or on a 1000 close. Use readerBytes and decode each frame yourself when every binary message must be decoded independently.
socket.writer — acquisition cannot fail. It yields a Writer with write(chunk | CloseEvent) and writeAll(chunks); both wait for the transport's native drain signal, so a slow peer backpressures the producer. Writes issued while disconnected suspend until the next connection.
Mental model: a connection is a scoped read loop. Code placed between acquiring the reader and the first pull runs exactly once per (re)connection, which is where a handshake belongs. A pullnever completes normally — every termination, a clean close included, fails with SocketError wrapping a SocketCloseError (or SocketReadError, SocketWriteError, SocketOpenError, SocketUpgradeError). Reconnection is therefore ordinary Effect.retry around the scoped loop, not a special socket option.
Backpressure is end to end: TCP pauses while nobody pulls; pausable WebSockets pause at highWaterMark (64 KiB by default) and resume after draining. Browser WebSockets cannot pause, so they fail with SocketReadError when a configured highWaterMark is exceeded — size it for the burst you expect.
WebSockets: Socket.makeWebSocket(url) creates a Socket from a URL; Socket.layerWebSocket(url) provides it as a service. A WebSocketConstructor service controls the underlying constructor. Its second argument is either subprotocols or a typed WebSocketClientOptions ({ headers } for the opening handshake, e.g. an Authorization header): NodeSocket.layerWebSocketConstructor passes it to Node's global WebSocket, BunSocket to Bun's, and NodeWS.layerWebSocketConstructor to the ws package, while the browser constructor throws a TypeError, because browsers cannot set handshake headers. Node's global WebSocket cannot pause reads (frames buffer without limit, or fail with SocketReadError past a configured highWaterMark), ignores a custom Host header, does not compress outgoing messages, and reports connection errors without the underlying error code; provide NodeWS.layerWebSocketConstructor when any of those matter. makeWebSocket forwards only protocols, so to send headers call the constructor service yourself and wrap the result with Socket.fromWebSocket.
TCP in Node: use NodeSocket.layerNet(opts) where opts is a Net.NetConnectOpts object (e.g., { host, port }) plus an optional chunkSize. There is no layerTCP export. For a TLS connection from the start, NodeSocket.makeTls(options) (and its layerTls/makeTlsChannel counterparts) dials tls.connect directly, accepting the same options as tls.connect (ca, cert, key, alpnProtocols, servername, plus an openTimeout); a failed handshake, including an untrusted or expired certificate, fails with SocketOpenError.
Self-contained source · Type-checked
ts
import { Socket } from "effect/socket"import { NodeSocket } from "@effect/platform-node"import { Effect, Schedule } from "effect"// Connect to the payroll service over TCP, send a sync trigger, log every ack.const triggerPayrollSync = Effect.gen(function*() { // Socket is part of the unstable effect/socket module. const socket = yield* Socket.Socket // Acquiring the reader dials; this scope owns the connection. const pull = yield* Socket.readerString(socket) const writer = yield* socket.writer // Runs once per (re)connection, before the first pull: the handshake slot. yield* writer.write("SYNC:merit-cycle-2025\n") // Pull until the peer closes. The close arrives as a SocketError failure. while (true) { for (const ack of yield* pull) { yield* Effect.log(`payroll ack: ${ack}`) } }}).pipe( Effect.scoped, // Every termination is a failure, so reconnecting is plain retry. Effect.retry({ schedule: Schedule.exponential("200 millis"), times: 5 }), // NodeSocket.layerNet — correct name; no layerTCP exists Effect.provide(NodeSocket.layerNet({ host: "127.0.0.1", port: 4000 })))
For combinator-style consumption, Socket.toStream(socket) is a read-only binary Stream backed by the same pull, and Socket.toChannel / Socket.toChannelString expose the duplex connection as a Channel. All three fail on close for the same reason pull does.
Client-side TLS upgrades also accept servername for SNI/certificate-name selection independently of the numeric connection address. Keep verification enabled and use the intended peer name; a successful TCP connection alone authenticates nothing.
When to use: typed Effect-native TCP or WebSocket communication over a persistent connection.
Server-side counterpart to Socket. The SocketServer service exposes: address — the bound NetAddress.SocketAddress (an InetAddressV4 | InetAddressV6 with address and port, or a UnixPathAddress with path) — and run(handler), a never-ending Effect that accepts connections and passes each as a Socket.Socket to the handler. Errors are SocketServerError with reason SocketServerOpenError | SocketServerUnknownError.
Mental model: provide a handler; the server calls it concurrently per accepted connection. Each handler gets a fresh Socket whose scope closes when the handler completes. An accepted socket starts paused and its reader attaches to the existing connection, so it cannot reconnect after close — a failed pull simply ends that handler. NodeSocketServer.layer({ port: 4000 }) wires up a Node TCP server; NodeSocketServer.layerWebSocket({ port: 8080 }) wires up a WebSocket server backed by ws; NodeSocketServer.makeTls(options) wires up a TLS server from tls.TlsOptions & net.ListenOptions — the tls.createServer options, so a server supplies its own key and cert (the client-side NodeSocket.makeTls takes tls.ConnectionOptions instead).
Self-contained source · Type-checked
ts
import { NetAddress } from "effect/net"import { Socket, SocketServer } from "effect/socket"import { NodeSocketServer } from "@effect/platform-node"import { Effect } from "effect"// A small HRIS push-notification server: echo events back with a prefixconst hrisNotificationServer = Effect.gen(function*() { // SocketServer, NetAddress helpers, and Socket.readerString are part of the // unstable effect/socket and effect/net modules. const server = yield* SocketServer.SocketServer const bound = NetAddress.isInetAddress(server.address) ? NetAddress.formatInet(server.address) : server.address.path yield* Effect.log(`HRIS push server listening on ${bound}`) return yield* server.run((socket) => Effect.gen(function*() { const pull = yield* Socket.readerString(socket) const writer = yield* socket.writer while (true) { for (const msg of yield* pull) { yield* writer.write(`ACK:${msg}`) } } }).pipe( Effect.scoped, // The peer hanging up is the normal end of this connection, not a server fault. Effect.catchTag("SocketError", (error) => Effect.logDebug("connection closed", error)) ) )}).pipe( Effect.provide(NodeSocketServer.layer({ port: 4000 })), Effect.scoped)
The bound address and every accepted peer address are NetAddress values rather than strings.
When to use: accepting TCP or WebSocket connections — custom protocols, push event relays, or bidirectional streaming pipelines.
Pure, platform-neutral values for network addresses: Ipv4Address / Ipv6Address (IpAddress), MacAddress, internet socket addresses InetAddressV4 / InetAddressV6 (InetAddress, an IP plus a port), and UnixPathAddress. SocketAddress = InetAddress | UnixPathAddress is what SocketServer.address and HttpServer.address report. Ipv4Address and Ipv6Address store their bits as numbers rather than a Uint8Array, so Equal/Hash and comparisons are cheap; every value implements Equal and Hash, so addresses work as HashMap keys and compare structurally.
Classifications are generic branded types parameterized by the address kind, not separate ad-hoc predicates: MulticastAddress<A>, UnicastAddress<A>, BroadcastAddress<A>, LoopbackAddress<A>, LinkLocalAddress<A>, UnspecifiedAddress<A>, PrivateAddress<A>, UniqueLocalAddress<A> narrow an IpAddress or MacAddress to the matching refinement, and Schema.IpMulticastAddress / Schema.IpMulticastAddressFromString / Schema.MacMulticastAddress / Schema.MacMulticastAddressFromString validate multicast addresses straight out of untrusted input.
Mental model: parse once at the boundary, then pass a typed address instead of a string. Parsing is checked — ipFromString, inetAddressFromString, and macAddressFromString return a Result with a NetAddressError, and each has a throwing *Unsafe twin for trusted literals. Formatting is canonical: formatIp, formatInet (brackets IPv6 before the port), and formatUrlHost (brackets IPv6 for use inside a URL; scoped IPv6 is rejected by the URL helpers). Classification predicates — isLoopback, isPrivate, isLinkLocal, isMulticast, isUniqueLocal, isUnspecified — replace ad-hoc prefix string checks, which is what an SSRF or allow-list guard should be built on.
Self-contained source · Type-checked
ts
import { Result } from "effect"import { IpNetwork, NetAddress } from "effect/net"// Untrusted input: checked parsing returns a Result, never throws.// NetAddress and IpNetwork are part of the unstable effect/net module.const parsed = NetAddress.ipFromString("10.20.3.999")if (Result.isFailure(parsed)) { console.log(parsed.failure._tag) // "NetAddressError"}// Trusted literal: the Unsafe twin throws on a typo instead of limping on.const payrollHost = NetAddress.ipFromStringUnsafe("10.20.3.7")NetAddress.isLoopback(payrollHost) // falseNetAddress.formatIp(payrollHost) // "10.20.3.7"// A socket address keeps the port typed; IPv6 is bracketed when formatted.const hris = NetAddress.inetAddressFromStringUnsafe("[2001:db8::1]:8443")hris.port // 8443NetAddress.formatInet(hris) // "[2001:db8::1]:8443"NetAddress.formatUrlHost(hris.address) // "[2001:db8::1]"// Allow-list an outbound webhook target by CIDR membership, not by string prefix.const internalRange = IpNetwork.fromStringUnsafe("10.20.0.0/16")const isInternal = IpNetwork.contains(internalRange, payrollHost) // true
Some socket APIs take the host and the port separately (node:net's { host, port }, a driver's host field). formatHost(address) renders only the numeric host, without brackets or port, and keeps a nonzero IPv6 scope ID as a % suffix. The reverse, inetAddressFromHostString(host, port, scopeIds?), parses an unbracketed numeric host plus a port into an InetAddress and returns a Result; a hostname such as payroll.internal is a failure, because this module never resolves DNS. A named IPv6 zone (fe80::1%en0) needs a map from interface name to numeric scope ID, which scopeIdsFromInterfaces(Object.entries(os.networkInterfaces())) builds from entries you supply; numeric zones need no map, and an unknown name fails with unknown IPv6 interface.
Native socket APIs (raw dgram/net bindings for multicast, scope IDs) need slightly different formatting than formatHost: formatNativeHost(address, scopeIds, platform?) formats an InetAddress host without brackets or a port, keeping IPv6 zones numeric on "win32" and resolving them to an interface name elsewhere; formatMulticastInterface(networkInterface, scopeIds, platform?) formats an IPv4 address or an IPv6 interface index the same way for multicast join/leave calls. Both take the scopeIdsFromInterfaces map and an optional platform string, and neither performs OS lookups itself.
toCanonical(address) converts an IPv4-mapped IPv6 address (and the IP side of an InetAddress) to plain IPv4, preserving the port on an internet address and leaving already-canonical or IPv6-scoped addresses unchanged — use it before comparing or classifying an address that may have arrived in mapped form (common with dual-stack listeners).
Self-contained source · Type-checked
ts
import { Result } from "effect"import { NetAddress } from "effect/net"import { networkInterfaces } from "node:os"// A payroll relay configured with `host` and `port` as separate settings.// NetAddress is part of the unstable effect/net module.const scopeIds = NetAddress.scopeIdsFromInterfaces(Object.entries(networkInterfaces()))const relay = NetAddress.inetAddressFromHostString("fe80::1%lo0", 8443, scopeIds)if (Result.isSuccess(relay)) { NetAddress.formatHost(relay.success) // "fe80::1%1" (lo0's scope ID on this host) NetAddress.formatInet(relay.success) // "[fe80::1%1]:8443"}
Schema ships matching codecs — Schema.IpAddressFromString, Schema.InetAddressFromString, Schema.MacAddressFromString, Schema.SocketAddress, and the v4/v6-specific variants — so a config value or request field decodes straight to an address. A server address has no hostname string field; read NetAddress.formatIp(address.address) instead, and use address.path for Unix sockets. Bun and Deno HTTP server layers can fail with ServeError when the listener address cannot be converted.
The *FromInput constructors normalize supported strings, address values, octets/segments, bytes, or parts objects to their corresponding address kind; IpNetwork.fromInput and IpInterface.fromInput provide the same boundary convenience for networks/interfaces. Each accepts its own declared input union, not arbitrary JSON. Checked forms return Result; keep Unsafe variants at trusted boundaries.
When to use: any time an address crosses a boundary — config, request data, allow/deny lists, logging a bound listener — and whenever address equality or classification matters.
Pure values for DNS domain names, numeric hosts (including scoped IPv6), and host/port endpoints. Checked domainNameFromString, hostFromString, and hostPortFromString return Results with NetAddressError; *Unsafe forms are for trusted literals. *FromInput constructors accept the corresponding supported value/string/parts inputs without doing DNS. Format endpoints with formatHostPort so IPv6 gets brackets; bare numeric-address parsing belongs to NetAddress.
toFullyQualified adds the terminal DNS dot; toRelative removes it. parseHostsFile reads text you supply into a name-to-nonempty-addresses map, skips invalid entries and comments, and normalizes names to relative form. It does not read the OS hosts file itself. NetAddress.loopbackAddresses supplies typed loopback values without resolution.
Reach for it when parsing configuration that may contain a name rather than only an IP address.
Dns.Dns separates lookup (OS host resolution, including hosts-file/system sources), resolve (DNS records of a selected type), and reverse (names for an address). Inputs accept supported strings and typed host/address values. Records include A, AAAA, CAA, CNAME, MX, NAPTR, NS, PTR, SOA, SRV, TXT, and TLSA; record values support structural equality and hashing. A TLSA answer is DNS data, not automatic certificate verification.
Failures are DnsError; do not collapse “lookup failed” into “this name is safe” or silently fall back to another destination. NodeDns.layer, BunDns.layer, and DenoDns.layer provide host adapters. A separate resolver instance can configure name servers for DNS queries; it is not a replacement for the OS lookup policy. Browsers have no equivalent raw DNS layer.
Dns.layerStatic(zone) provides deterministic lookup/record/reverse data without network I/O; invalid zone input fails layer construction with NetAddressError. Use it with AddressResolver.layer() for portable tests, rather than replacing DNS with live public queries. Native lookups do not attach a usable interface to link-local IPv6 addresses; resolve scoped endpoints through AddressResolver when that distinction matters.
Reach for it when querying DNS records or resolving host names without embedding a host API in application code.
AddressResolver.AddressResolver.resolve(target, { family? }) converts a socket address or host/port input to a nonempty list of socket addresses. Numeric hosts avoid lookup; names use Dns.lookup. Results retain resolver order and are filtered by family; Unix-domain addresses pass through. Invalid endpoints or unsupported numeric families fail with NetAddressError, and lookup failures with DnsError.
Core AddressResolver.layer() requires Dns and handles numeric IPv6 zones only. NodeAddressResolver.layer, BunAddressResolver.layer, and DenoAddressResolver.layer add host interface lookup for named zones. Unscoped link-local IPv6 lookup results are skipped because the resolver cannot infer their interface; a name resolving only to such addresses fails rather than returning unusable endpoints. Supply a zoned literal instead.
Resolution alone is not an SSRF defense. Validate every resolved candidate and the actual connected peer, consider DNS rebinding and redirects, and do not substitute string-prefix tests for address classification.
Reach for it when turning configured endpoints into typed connection candidates while keeping DNS and interface policy explicit.
Pull-based UDP with scoped native handles. Acquiring reader opens and binds the socket; only one reader may be open, and another acquisition waits interruptibly. The scoped writer cannot fail to acquire, but writes wait until a reader is open — even send-only applications must acquire one. reader.pull yields a nonempty packet batch; packets retain their bytes safely. writer.write takes { payload, address? }, where payload is text or bytes; omit the destination only for a configured/connected peer.
Closing the reader scope discards queued packets and fails waiting pulls. After a terminal error, queued packets drain before subsequent pulls fail. reader.dropped() counts this reader's receive-buffer overflow, not kernel or network loss. UDP does not guarantee ordering, delivery, uniqueness, or application acknowledgment. writeAll does not resend on failure and does not identify which packet failed; bound sends with Effect.timeout if required.
Use NodeDatagramSocket.layer, BunDatagramSocket.layer, or DenoDatagramSocket.layer; these and DNS/address-resolver adapters are explicit exports, not part of NodeServices.layer, BunServices.layer, or DenoServices.layer. reader.joinMulticast owns membership until its scope closes; the ingress interface is distinct from the adapter's multicast sending interface. Browser WebSockets are not UDP and do not provide this service.
Reach for it when implementing datagram protocols or multicast discovery with deliberate loss and lifetime handling.
A CIDR network: a network address plus a prefix length, generic over the address family (Ipv4Network, Ipv6Network). Construction is strict — IpNetwork.fromString("10.20.3.7/16")fails because host bits are set; use IpNetwork.fromAddress (which masks them) or go through IpInterface when you have a host address. Operations: contains(network, address), containsNetwork, overlaps, firstAddress / lastAddress, addressCount (a bigint, since an IPv6 range does not fit a number), and format. The native @effect/sql-pg client decodes PostgreSQL cidr columns to their formatted text (for example "10.20.0.0/16"), not to an IpNetwork value — parse it with IpNetwork.fromString where you need the structure.
When to use: allow/deny lists, subnet planning, and tenant or region routing by address range.
An address with its prefix length — 10.20.3.7/16 — the form a host or network interface is configured with. Unlike IpNetwork, host bits are preserved. IpInterface.fromString parses it (with ParseOptions), IpInterface.format renders it, and IpNetwork.fromInterface(iface) yields the containing network (10.20.0.0/16). @effect/sql-pg decodes PostgreSQL inet columns to formatted text as well ("10.20.3.7/16", or just the address when the prefix covers the whole address); parse it with IpInterface.fromString.
When to use: modelling "this host, on this subnet" without losing either half.
Parent-side API for communicating with a worker thread or IPC child process. A Worker<O, I> provides: send(message: I) — fire a typed message into the worker; run(handler) — a never-completing Effect calling the handler for each emitted O. Errors are WorkerError.
Mental model: typed bidirectional channel where I flows in and O flows out. The parent buffers sends until the worker signals readiness, then drains the queue.
Setup: call NodeWorker.layer(spawnFn) to provide both WorkerPlatform and Spawner; acquire a typed Worker via WorkerPlatform.spawn(id). The spawn function receives a numeric ID and returns a WorkerThreads.Worker or IPC ChildProcess.
Lifetime: run owns the worker. A worker that exits or throws — before or after the ready handshake — fails run with a WorkerError: the Node adapter reports both exit and error events as WorkerReceiveError, the browser adapter reports error events the same way (a dedicated browser worker has no parent-visible exit event), and the Bun adapter reports error events as WorkerUnknownError and does not fail run on a plain exit. A worker that dies before signalling readiness does not leave run hanging uninterruptibly. When the scope around run closes, the Node and Bun adapters send the worker a close message, wait up to five seconds for it to exit, and then call terminate() (Node: kill("SIGKILL") for an IPC child) — so worker-side finalizers get a bounded chance to run. The browser adapter only sends the close message; it does not terminate a dedicated worker you spawned.
Self-contained source · Type-checked
ts
import { Worker } from "effect/workers"import { NodeWorker } from "@effect/platform-node"import { Effect } from "effect"import * as WorkerThreads from "node:worker_threads"// Parent side: dispatch vesting-schedule computations to worker threads// Each message is an EquityGrant; workers reply with vestedShares countconst workerLayer = NodeWorker.layer( (id) => new WorkerThreads.Worker(new URL("./vesting-worker.js", import.meta.url)))const computeVestedSharesInParallel = Effect.gen(function*() { // Worker is part of the unstable effect/workers module. const platform = yield* Worker.WorkerPlatform // Spawn a typed Worker: output = number (vestedShares), input = EquityGrant id const worker = yield* platform.spawn<number, string>(0) // Send a grant ID; the worker replies with vestedShares yield* worker.send("grant-2024-001") return yield* worker.run((vestedShares) => Effect.log(`vested shares computed: ${vestedShares}`) )}).pipe( Effect.scoped, Effect.provide(workerLayer))
When to use: offloading CPU-heavy computation to a worker thread while retaining typed error handling and structured concurrency.
Worker-side counterpart to Worker. A WorkerRunner<O, I> listens for I messages from the parent (tagged by port ID), calls the handler, and sends O replies via send(portId, message) or sendUnsafe. The optional disconnects queue notifies when a port closes; the browser and Deno runners provide it (many ports can share one worker there), the Node runner has a single parent and does not. An RPC server running over a worker forwards every disconnect, so a closed port's in-flight requests are interrupted rather than left running.
Mental model: if Worker is the client, WorkerRunner is the server. Write the worker's main function by yielding the WorkerRunnerPlatform service and calling platform.start(), then provide the platform layer from NodeWorkerRunner.layer.
Self-contained source · Type-checked
ts
// vesting-worker.ts — runs inside the worker threadimport { WorkerRunner } from "effect/workers"import { NodeWorkerRunner } from "@effect/platform-node"import { Effect } from "effect"// Receive a grant ID, compute vested shares, reply to parentconst runner = Effect.gen(function*() { // WorkerRunner is part of the unstable effect/workers module. const platform = yield* WorkerRunner.WorkerRunnerPlatform // start<O, I>() — O is what we send back, I is what we receive const workerRunner = yield* platform.start<number, string>() yield* workerRunner.run((portId, grantId) => Effect.gen(function*() { // CPU-bound vesting math const vestedShares = computeVested(grantId) yield* workerRunner.send(portId, vestedShares) }) )}).pipe( Effect.provide(NodeWorkerRunner.layer), Effect.runFork)function computeVested(grantId: string): number { // ... real vesting schedule math here return 1000}
When to use: writing the worker-thread side of a Worker/WorkerRunner pair.
Typed error union for worker communication. WorkerError wraps one of four reasons: WorkerSpawnError (worker failed to start), WorkerSendError (message serialization failed), WorkerReceiveError (message decode failed), WorkerUnknownError (anything else). Catch with Effect.catchTag("WorkerError", ...).
Transfer-list support for worker message fields. Annotate fields with Transferable.schema; a Transferable.Collector records backing ArrayBuffers, MessagePorts, or ImageData buffers for the platform's postMessage transfer list. The surrounding message still passes through Schema encoding and structured clone; only the transferred resources avoid copying. Transferring an ArrayBuffer detaches it from the sender, so do not retain a usable-sender-buffer assumption after sending. Without a Collector the annotation does not collect anything.
Value type describing a command to run — a typed ProcessBuilder. Use ChildProcess.make(cmd, args, options) to create a StandardCommand, or chain two commands with ChildProcess.pipeTo to create a PipedCommand (shell | equivalent). Modifiers: setEnv, setCwd, prefix.
Mental model: a Command is pure data describing what to run. Nothing executes until passed to a ChildProcessSpawner. Commands are composable and trivially testable. On Windows, the Node spawner hides the child console/GUI window by default unless the command is detached; set windowsHide: false explicitly when a visible window is intended. The option has no effect on other hosts.
Self-contained source · Type-checked
ts
import { ChildProcess } from "effect/process"// ChildProcess is part of the unstable effect/process module.// Describe a payroll-export command (pure data, nothing runs yet)const payrollExportCmd = ChildProcess.make("payroll-cli", ["export", "--format=csv"])// Pipe pipeline: export payroll data and sign itconst signedExport = ChildProcess.make("payroll-cli", ["export", "--format=csv"]).pipe( ChildProcess.pipeTo(ChildProcess.make("gpg", ["--sign", "--armor"])))// Override environment for a production payroll runconst prodExportCmd = ChildProcess.make("payroll-cli", ["export"]).pipe( ChildProcess.setEnv({ PAYROLL_ENV: "production", DB_HOST: "prod-db.internal" }), ChildProcess.setCwd("/app/payroll"))
make also has a template-literal form, with or without options first. Interpolations are arguments, never shell text: each interpolated value becomes exactly one argument (an array becomes several), so untrusted input cannot inject a command. The literal text is split the way a POSIX shell splits words — quotes group words and backslashes escape — but no shell runs, so shell syntax in the literal text (|, ;, $HOME, *, a leading ~, {a,b}, an assignment such as FOO=bar cmd) throws a CommandLine.CommandLineError with reason UnsupportedSyntax when make is called. Quote such characters or pass them through ${}. Arguments and env values may be Redacted strings: the child receives the value, and logs and CommandLine.display show <redacted>; the program name cannot be Redacted.
With the shell option the template text is the shell script, kept as written; it cannot contain ${} values (that throws), and extra arguments fail with BadArgument when spawned. Build such a script with CommandLine and pass it as a plain string.
Migration: templates that relied on whitespace-only splitting change meaning when they contain quotes, and templates containing shell syntax now throw. ChildProcess.TemplateExpression and ChildProcess.TemplateExpressionItem moved to CommandLine.
When to use: composing commands before running them, separating command description from execution.
Builds the single strings that a shell or a Windows program splits back into arguments — for sh -c, SSH, or a shell command — and argument lists from templates. It is unrelated to effect/cli, which parses your own program's arguments. quote(word, { format? }) quotes one argument, join(words, { format? }) quotes a whole argument list, and both return a Result failing with CommandLineError (a NUL character, or an argument the format cannot carry). display(words) renders the same text for logs with Redacted values replaced by <redacted>; quote and join include the secret, because their output is meant to run. template is the parser ChildProcess.make uses, returning Result<Array<Word>, CommandLineError>. Formats are "posix" (default; sh, bash, zsh, and readable by fish), "powershell" (7.3+), and "windows" (C runtime rules). The format follows the receiving shell: SSH sends the line to the remote account's login shell, and cmd.exe is not supported.
Self-contained source · Type-checked
ts
import { Redacted, Result } from "effect"import { ChildProcess, CommandLine } from "effect/process"const cycle = "2026 H1; rm -rf /"const token = Redacted.make("s3cret")// One shell script, every value quoted for sh.const script = Result.getOrThrow(CommandLine.join(["payroll-cli", "export", "--cycle", cycle]))export const viaShell = ChildProcess.make(`${script} | gzip > export.gz`, { shell: "/bin/sh" })// Safe to log: the token is hidden.export const logged = CommandLine.display(["curl", "-H", token, "https://payroll.internal"])// "curl -H <redacted> https://payroll.internal"
string collects stdout as a single string. lines collects stdout as Array<string>. streamString / streamLines are the incremental Stream forms, and exitCode(cmd) runs a command for its status alone; all five take { includeStderr } except exitCode. spawn returns a scoped ChildProcessHandle with stdout, stderr, all (merged) as byte Streams, and exitCode as an Effect waiting for process completion. Exit code is a branded ExitCode; compare with ChildProcessSpawner.ExitCode(0).
The collecting helpers never deadlock on an unread pipe: exitCode reads and discards stdout and stderr until the process exits, and string, lines, streamString, and streamLines discard stderr unless includeStderr is set. A failure while reading that output (for example from an output Sink) fails the helper. Output sinks configured for stdout, stderr, or output additionalFds only receive data while the matching handle stream is consumed.
Platform implementations: NodeServices.layer includes NodeChildProcessSpawner.layer; Bun uses BunServices.layer.
Termination waits, and only forceKillAfter bounds it. On Node and Bun, closing the scope around spawn (or calling handle.kill(options?)) signals the child's whole process group with killSignal (default SIGTERM), then waits for the leader to exit and up to one more second for descendants to disappear. Nothing escalates by default, so a child that ignores SIGTERM holds the scope — and therefore your shutdown — open until it exits by itself (probed: a trap '' TERM; sleep 4 child delayed release by the remaining four seconds). Set forceKillAfter on the command (or pass it to kill) to send SIGKILL to the group at that deadline; the probe then released in 300 ms. The waits use native timers rather than the Effect Clock, so they elapse under TestClock without adjust. The Node and Bun spawners also clean up the group when the leader has already exited, successfully or by a signal, before the scope closes: a grandchild the command left running in the background (sh -c 'sleep 47 & exit 0' in the probe) is gone once the scope closes. That cleanup targets a numeric process-group ID, so if the group disappears and the operating system reuses its ID first, an unrelated group can be signalled. On Windows the tree is ended with taskkill /T /F and only the leader is awaited; the Deno adapter differs again (see Platform packages).
Self-contained source · Type-checked
ts
import { ChildProcess, ChildProcessSpawner } from "effect/process"import { NodeServices } from "@effect/platform-node"import { Console, Data, Effect, Stream } from "effect"// ChildProcess and ChildProcessSpawner are part of the unstable effect/process module.class PayrollExportFailed extends Data.TaggedError("PayrollExportFailed")<{ readonly exitCode: ChildProcessSpawner.ExitCode}> {}// Spawn a payroll-export child process and stream its output line by lineconst runPayrollExport = Effect.gen(function*() { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner // Collect the version string of the payroll CLI tool const cliVersion = yield* spawner.string( ChildProcess.make("payroll-cli", ["--version"]) ) yield* Effect.log(`payroll-cli version: ${cliVersion.trim()}`) // Collect which employee IDs are in the current export batch const batchIds = yield* spawner.lines( ChildProcess.make("payroll-cli", ["list-pending", "--format=ids"]) ) yield* Effect.log(`batch size: ${batchIds.length} employees`) // Stream a long-running payroll export, logging each output line yield* Effect.scoped(Effect.gen(function*() { const handle = yield* spawner.spawn( ChildProcess.make("payroll-cli", ["export", "--format=csv"], { env: { PAYROLL_ENV: "production" }, extendEnv: true }) ) yield* handle.all.pipe( Stream.decodeText(), Stream.splitLines, Stream.runForEach((line) => Console.log(`[payroll-export] ${line}`)) ) const code = yield* handle.exitCode if (code !== ChildProcessSpawner.ExitCode(0)) { return yield* new PayrollExportFailed({ exitCode: code }) } })) return batchIds}).pipe(Effect.provide(NodeServices.layer))
When to use: running external tools with typed I/O, structured error handling, and streamed output.
The services above are interfaces. Platform packages provide concrete Layer implementations and a runMain entry point.
@effect/platform-node — package
Implements FileSystem, Path, Terminal, Stdio, ChildProcessSpawner, the effect/crypto services, Socket, SocketServer, Worker, WorkerRunner, HTTP, Redis, cluster transports, and stream adapters using Node.js APIs; it requires Node.js 22.19.0 or newer. NodeServices.layer is deliberately narrower: it aggregates ChildProcessSpawner, FileSystem, Path, Stdio, and Terminal. Crypto (NodeCrypto.layer or one family layer, see Cryptography), sockets, workers, HTTP (NodeHttpServer.layer), and other adapters have explicit layers.
NodeSocket WebSocket clients use Node's global WebSocket, so the ws package is loaded only by NodeSocketServer.layerWebSocket and the NodeWS module (NodeWS.WebSocket, NodeWS.layerWebSocketConstructor). Migration:NodeSocket.NodeWS and NodeSocket.layerWebSocketConstructorWS were removed; import NodeWS from @effect/platform-node instead. Node socket and stream readers return at most chunkSize chunks per pull (default 4096; Infinity restores unbounded batching), and Node stream read(size) byte sizes moved to a separate readSize option.
@effect/platform-node has no Mime export — use Mime from effect/http instead. NodeRedis wraps the redis (node-redis) client, so the optional peer dependency is redis >=5.1.0 <7.0.0; its accessors are unstable because they expose that client's own types directly.
Self-contained source · Type-checked
ts
import { NodeRuntime, NodeServices } from "@effect/platform-node"import { Effect } from "effect"const program = Effect.gen(function*() { // ... your app})program.pipe( Effect.provide(NodeServices.layer), NodeRuntime.runMain)
@effect/platform-bun — package
Bun-native counterparts cover the same broad host responsibilities, but use Bun* namespaces and layers rather than promising every Node adapter is interchangeable. Like Node's aggregate, BunServices.layer includes ChildProcessSpawner, FileSystem, Path, Stdio, and Terminal; BunCrypto, HTTP, sockets, workers, BunRedis (unstable — it exposes the underlying redis client's types), and cluster adapters remain explicit. BunHttpServer disables Bun's default 10-second idleTimeout unless you pass one, so quiet response streams and slow uploads are not cut; a server exposed directly to the internet should set idleTimeout (seconds) itself.
Self-contained source · Type-checked
ts
import { BunRuntime, BunServices } from "@effect/platform-bun"import { Effect } from "effect"const program = Effect.gen(function*() { // same code as the Node version})program.pipe( Effect.provide(BunServices.layer), BunRuntime.runMain)
@effect/platform-deno — package
The Deno host package (Deno 2.9.3+) covers FileSystem, Path, DenoCrypto, Stdio, Terminal, child processes, HTTP client/server, sockets, workers, DenoRedis (unstable, same caveat as NodeRedis/BunRedis), multipart parsing, key-value storage, and cluster HTTP/socket adapters. DenoServices.layer is the standard aggregate (ChildProcessSpawner, FileSystem, Path, Stdio, Terminal); crypto and specialized HTTP/socket/worker layers remain explicit. DenoRuntime.runMain installs structured SIGINT/SIGTERM interruption and teardown.
The Deno child-process adapter has narrower process-control semantics than Node: commands using detached or additionalFds fail as unsupported, and killing a handle terminates only the direct child, not its descendants. Design process-tree cleanup explicitly when Deno is a deployment target.
Self-contained source · Type-checked
ts
import { DenoRuntime, DenoServices } from "@effect/platform-deno"import { Effect, FileSystem } from "effect"const program = Effect.gen(function*() { const fs = yield* FileSystem.FileSystem return yield* fs.readFileString("./deno.json")})program.pipe( Effect.provide(DenoServices.layer), DenoRuntime.runMain)
@effect/platform-cloudflare — package
Experimental (every module is tagged @stability experimental, and its APIs may change in patch releases). It is not a general Workers host adapter with FileSystem or runMain: it runs Effect Cluster on Cloudflare Durable Objects, giving each entity id, workflow execution, durable queue, and singleton its own SQLite-backed Durable Object. The root import exposes five modules:
Module
Role
CloudflareCluster
layer({ entities, entityNamespace, workflowNamespace, queueNamespace, singletonNamespace, keepAliveHeartbeat? }) provides Sharding, WorkflowEngine, and PersistedQueueFactory; also DurableObjectSqlClient (the entity object's own SQLite as an SqlClient), clusterCronSingletonName, and the encodeName/decodeName naming scheme.
CloudflareDurableObjects
The four classes the Worker entry re-exports and binds as SQLite-backed classes (ClusterEntity, ClusterWorkflow, ClusterDurableQueue, ClusterSingleton), plus setInitializer for an asynchronously built layer (must finish within 15 seconds).
CloudflareWorkflowEngine
The WorkflowEngine on the workflow namespace alone; it sets DurableClock.InMemoryThreshold to zero, so a DurableClock.sleep without an explicit inMemoryThreshold always schedules a durable timer.
CloudflarePersistedQueue
The PersistedQueueFactory on the queue namespace alone; PersistedQueue.layerCleanup is unsupported.
CloudflareDurableObjectPrograms
Class-independent programs behind those classes, for frameworks that create their own Durable Object classes.
AlchemyCloudflareCluster is a subpath-only import (@effect/platform-cloudflare/AlchemyCloudflareCluster) behind the optional @alchemy.run/cloudflare peer (>=2.0.0-beta.85 <3); make registers the classes and bindings from inside an Alchemy Cloudflare.Worker program, so there is no wrangler.jsonc, class re-export, or initializer. Workers' types such as DurableObjectNamespace come from @cloudflare/workers-types, a dependency of the package. The Durable Object classes accept calls only through same-Worker bindings; never route public traffic to them.
@effect/platform-node-shared — package
Contains implementation shared by the Node, Bun, and Deno adapters: Node-compatible Path/FileSystem/Terminal/child-process/socket/worker/Redis building blocks. It is public for adapter authors, but application entrypoints should normally depend on the host package rather than assembling these internals.
@effect/platform-browser — package
Browser-specific implementations: BrowserCrypto.layer (every effect/crypto service on Web Crypto, or one family layer such as BrowserCrypto.layerDigest), BrowserSocket.layer (native WebSocket), BrowserWorker.layer and BrowserWorkerRunner.layer (dedicated/shared workers via postMessage). No FileSystem or ChildProcess in browsers. Additional APIs include Permissions, Clipboard, Geolocation, typed DOM event streams, Fetch/XHR clients, browser persistence/key-value layers, and the typed IndexedDB subsystem below.
BrowserRuntime.runMain listens for pagehide and interrupts the root fiber when the document is being discarded. A persistedpagehide — the page entering the back/forward cache — is ignored, because that document may be restored with its fibers intact. The interruption is best effort: the browser may tear the page down before asynchronous finalizers, network flushes, or timers complete, so persist anything important before unload rather than in a finalizer.
Self-contained source · Type-checked
ts
import { BrowserRuntime, BrowserWorker } from "@effect/platform-browser"import { Effect } from "effect"const app = Effect.gen(function*() { // browser-specific effects})app.pipe( Effect.provide(BrowserWorker.layer((id) => new Worker(new URL("./worker.js", import.meta.url)))), BrowserRuntime.runMain)
A platform Layer says how a capability is implemented. The host decides something more important: who owns the runtime, what cancels work, and whether cleanup is actually awaited. Pick the row first, then the package.
Host
Runner and owner
What the host guarantees
What it cannot promise
Node / Bun / Deno process
NodeRuntime.runMain, BunRuntime.runMain, DenoRuntime.runMain once at the root; the launched Layer's scope owns everything
SIGINT and SIGTERM interrupt the main fiber; finalizers run; the process exits after teardown with 0, 130 (interrupt-only), the largest Runtime.InterruptExitCode when every interruption carries one, or the error's exit code
Surviving SIGKILL or an expired grace period; signal delivery when another process is PID 1 in the container; identical signal behavior on Windows — verify on the target
Web-standard handler (serverless, edge)
HttpRouter.toWebHandler or HttpEffect.toWebHandlerLayer returns { handler, dispose }; module scope owns the Layer, each request owns its own scope
The Layer is built eagerly; each request's scope closes once its response body has finished; request.signal interrupts the request fiber
That dispose is ever awaited, that the isolate is reused, or that work continues after the response. A Fetch-shaped API is not Node: no node:* modules unless the platform says so
One ManagedRuntime, created at boot and disposed by the host's shutdown hook
One shared Layer graph; idempotent dispose()
Cancellation and drain — nothing happens unless you forward the host's AbortSignal and stop admission yourself
Browser page
BrowserRuntime.runMain
A non-persisted pagehide interrupts the main fiber
Completion of asynchronous finalizers or network flushes during teardown
Worker thread or IPC child
The parent's scope around Worker.run; worker side runs a WorkerRunner with its platform Layer
Node and Bun: close message, five-second grace, then terminate()
Worker-side cleanup that needs longer than the grace; termination of a browser worker (the adapter only asks it to close)
CLI
Command.run handed to the platform runMain
Same as a process; Ctrl+C inside a prompt is a typed QuitError
—
Test
The scope of it.effect / it.layer
Scope closes at the end of the test; time is virtual
Anything about real signals, ports, files, or bundling — fakes do not exercise them
Same program, different owner. Business code is identical in every row; only the outermost line and the platform Layer change. If a module has to know which row it runs in, a platform import has leaked inward.
Server-side rendering is two hosts. The server request and the hydrated page have separate scopes and runtimes: serialize validated data across that seam, never a service, fiber, Scope, or runtime.
Edge isolates may forbid timers at module scope. The default scheduler falls back to a microtask when setting a timer throws (Cloudflare Workers' global scope), so an Effect run at module load does not crash there. A module-level ManagedRuntime amortizes acquisition across invocations of a reused isolate, but it must not capture request data and must not assume disposal runs.
Platform-specific defaults follow the host.Logger.consolePretty() detects TTY versus browser rendering; pin one with Logger.consolePrettyTty or Logger.consolePrettyBrowser. Logger.toFile writes through the FileSystem service, so it needs a platform Layer in scope (both in Observability).
An intentional shutdown can pick its exit code.runMain reports 130 for an interrupt because it assumes someone outside stopped the program. When your own code ends the program by interrupting the main fiber (a stdio server whose input closed, say), interrupt it with Fiber.interruptAs(fiber, undefined, Context.make(Runtime.InterruptExitCode, 0)). Runtime.defaultTeardown uses the largest annotated code when every interrupt reason carries one and falls back to 130 as soon as one does not; a cause mixing interrupts with errors still takes the error path. The code is read from the Cause, so providing Runtime.InterruptExitCode as a service does nothing. RPC and MCP stdio servers use this to exit 0 after stdin closes and pending responses drain.
Fragment · Type-checked
ts
import { Context, Effect, Fiber, Runtime } from "effect"// Stop the main fiber on purpose and exit 0 instead of 130.declare const mainFiber: Fiber.Fiber<void>const finishCleanly = Fiber.interruptAs( mainFiber, undefined, Context.make(Runtime.InterruptExitCode, 0))export const program = Effect.asVoid(finishCleanly)
Keep platform and unstable imports behind a capability
Let domain code depend on a small app-owned service, and let exactly one module import the platform package or the unstable module that implements it. The reason is churn as much as portability: unstable modules (effect/socket/*, effect/net/*, effect/process/*, effect/workers/*) may change in any release, and a stable module's surface can move across a major version too. A quarantined import turns such a change into a one-file edit. Tests provide a fake Layer instead of patching globals.
Self-contained source · Type-checked
ts
import { Context, Data, Effect, Layer } from "effect"import { ChildProcess, ChildProcessSpawner } from "effect/process"class PayrollCliFailed extends Data.TaggedError("PayrollCliFailed")<{ readonly cause: unknown}> {}// Domain code sees only this capability.class PayrollCli extends Context.Service<PayrollCli, { readonly pendingEmployeeIds: Effect.Effect<ReadonlyArray<string>, PayrollCliFailed>}>()("app/PayrollCli") { // The one place that knows about the unstable process API. static layer = Layer.effect( PayrollCli, Effect.gen(function*() { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner return { pendingEmployeeIds: spawner.lines( ChildProcess.make`payroll-cli list-pending --format=ids` ).pipe(Effect.mapError((cause) => new PayrollCliFailed({ cause }))) } }) ) static layerTest = (ids: ReadonlyArray<string>) => Layer.succeed(PayrollCli)({ pendingEmployeeIds: Effect.succeed(ids) })}
Note: This applies to leaf capabilities — a file store, a status client, a subprocess. Framework-level unstable modules such as HttpApi, RpcServer, or SqlClient are used directly throughout a codebase; manage those by pinning one Effect version and re-auditing on upgrade (see Incompatible unstable package versions).
Use .add(V2, (from, to) => ...) to preserve/copy rows while changing stores or indexes. withTransaction({ tables, mode: "readwrite" })(effect) aborts writes when the effect fails. Queries provide equals, comparison/range operators, limit, offset, reverse, filter, first, paged stream, and reactive variants; mutations expose invalidation. rebuild deletes and recreates the database, so data not reintroduced by migrations is lost.
Reach for it when a browser application needs local, typed, queryable state with deliberate migrations and transactions. For simple keys, use BrowserKeyValueStore; for generic persistence, BrowserPersistence.layerIndexedDb is a separate, simpler store that talks to the raw indexedDB API directly rather than building on these typed modules.
Typed permission status; querying does not itself grant permission.
Clipboard
Text/blob reads and writes, subject to browser security and user-activation rules.
Geolocation
Current position and a scoped watchPosition stream with typed permission/timeout failures.
BrowserStream
Typed window and document event streams with automatic listener cleanup.
BrowserHttpClient
Portable Fetch layer plus an XHR escape hatch and array-buffer response mode.
BrowserKeyValueStore
LocalStorage, SessionStorage, or IndexedDB-backed key/value layers.
BrowserPersistence
The unstable Persistence abstraction backed by IndexedDB, including TTL behavior.
Tip: Browser APIs remain ordinary services and layers. At portable test boundaries, FileSystem.layerNoop, Stdio.layerTest, and a seeded SecureRandom.make(...) or Layer.mock crypto service (Cryptography) avoid reaching host globals.
The effect/crypto modules split cryptography into one service per job: SecureRandom, Digest, Mac, Aead, Cipher, Kdf, Signature, KeyAgreement, and KeyWrap. KeyFormat reads and writes keys, CryptoError is the only error they fail with, and WebCrypto is the reference that the WebCrypto-backed layers run on. Each service is an ordinary Context.Service, so a program asks for only the services it uses and a test replaces just those. The effect/jose modules build JSON Web Keys, signatures, encryption, and tokens on top of these services.
Choose by the job, not by the algorithm:
You need
Use
Not
Random bytes, UUIDs, ULIDs, dice rolls, shuffles that must not be guessable
Every module is unstable. Keys are opaque values: they print only their algorithm, compare by reference, and carry their algorithm in their type, so passing an Ed25519 key where an ECDSA key is expected is a type error.
Providing the services. The runtime aggregates (NodeServices.layer, BunServices.layer, DenoServices.layer) do not include any crypto service; provide crypto separately. Each host package has a crypto module with one layer per family and a combined layer, and none of them has requirements:
Host
Module
Notes
Node.js
NodeCrypto from @effect/platform-node
layerDigest and layerMac run synchronously on node:crypto; layerAead runs ChaCha20-Poly1305 on node:crypto; layerKdf adds Argon2id (Node.js 24.7+ with OpenSSL 3.2)
Bun
BunCrypto from @effect/platform-bun
Re-exports NodeCrypto; ChaCha20-Poly1305 falls back to the pure TypeScript implementation, and Argon2id needs Bun 1.4
Deno
DenoCrypto from @effect/platform-deno
The core WebCrypto layers with SecureRandom already provided
Browser
BrowserCrypto from @effect/platform-browser
Same as Deno; crypto.subtle exists only in secure contexts
Portable code can use each module's own layerWebCrypto instead. Those layers run on the WebCrypto reference, and every family except Digest and Kdf needs SecureRandom for key generation, so provide SecureRandom.layerWebCrypto underneath.
Fragment · Type-checked
ts
import { Effect, Layer } from "effect"import { Digest, Mac, SecureRandom } from "effect/crypto"import { NodeCrypto, NodeRuntime, NodeServices } from "@effect/platform-node"declare const app: Effect.Effect<void, never, Digest.Digest | Mac.Mac | SecureRandom.SecureRandom>// Node entrypoint: platform services and crypto are separate layers.app.pipe( Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), NodeRuntime.runMain)// Portable alternative: only the families this program uses, on WebCrypto.export const PortableCrypto = Layer.mergeAll( Digest.layerWebCrypto, Mac.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))
Testing. There is no TestCrypto module. Replace the services a test touches with Layer.mock, which accepts a partial implementation and makes any unimplemented method die with an UnimplementedError. For reproducible random output, build a service with SecureRandom.make from a deterministic byte source; Ed25519 and X25519 key generation, and every family's symmetric generateKey, draw from that SecureRandom, but ECDSA, ECDH, and RSA keys use WebCrypto's own randomness and cannot be seeded, so test those with round trips such as verify(sign(data)).
Self-contained source · Type-checked
ts
import { Effect, Layer } from "effect"import { SecureRandom } from "effect/crypto"// Only the method the code under test calls.export const FixedIds = Layer.mock(SecureRandom.SecureRandom, { uuidV4: () => Effect.succeed("00000000-0000-4000-8000-000000000000")})// A deterministic byte source: every operation derives from it.let counter = 0export const SeededRandom = Layer.succeed(SecureRandom.SecureRandom)( SecureRandom.make((size) => Uint8Array.from({ length: size }, () => (counter++ * 31) & 255)))
Migration:effect/Crypto and effect/testing/TestCrypto were removed. Map old calls as follows:
Old Crypto.Crypto call
Replacement
randomBytes(n)
SecureRandom.randomBytes(n) — no error channel; a bad size is a defect
randomUUIDv4() / randomUUIDv7()
uuidV4() / uuidV7(); the default format is now "string" (was "hex"), and { format: "bytes" } is unchanged
No secure equivalents: use effect/Random for non-secret numbers, or derive a bit from randomBytes(1)
digest("SHA-256", data)
Digest.digest(Digest.sha256, data), or digestHex for lowercase hex instead of converting by hand
Crypto.make(...) / TestCrypto.layer(seed)
SecureRandom.make(randomBytes) or Layer.mock(...) for the services a test needs
NodeServices.layer providing Crypto
Add NodeCrypto.layer (or a single family layer such as NodeCrypto.layerDigest)
Code that passed Crypto.Crypto to cluster SqlMessageStorage or SingleRunner now provides Digest.Digest, and EventLogEncryption takes Aead, Digest, Signature, and SecureRandom from context. Stored workflow IDs, idempotency keys, and encrypted event-log data are unchanged.
The SecureRandom service generates randomBytes(size), uniform integers with intBetween(min, max, { halfOpen? }) (exactly uniform, by rejection sampling), Fisher–Yates shuffle, uuidV4(), uuidV7(), and the ulid Effect. Every operation has a never error channel; a negative size or an empty range dies with a RangeError. uuidV4 and uuidV7 are functions returning Effects: by default they return the lowercase hyphenated string, and { format: "bytes" } returns the 16 bytes.
UUIDv7 and ULID read the timestamp from Clock, so TestClock controls their time prefix. Values from one service instance are strictly increasing, even within one millisecond or when the clock moves back; there is no ordering across separate services, processes, or workers. Because consecutive values reveal their order, never use them as secrets.
SecureRandom.make(randomBytes) builds the service from any byte source, and layerWebCrypto uses getRandomValues (which also works in insecure browser contexts). randomBytesUnsafe, uuidV4Unsafe, uuidV7Unsafe, and ulidUnsafe draw synchronously from globalThis.crypto for constructors and model defaults that cannot read a service; a mocked SecureRandom does not affect them.
There are no float, boolean, or full-range integer helpers. Insecure random numbers belong to effect/Random.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { SecureRandom } from "effect/crypto"export const newGrant = Effect.gen(function*() { const random = yield* SecureRandom.SecureRandom const grantId = yield* random.uuidV7() // time-ordered primary key const exportName = yield* random.ulid // 26 sortable characters for file names const token = yield* random.randomBytes(32) // secret material const reviewer = yield* random.intBetween(0, 4) // inclusive on both ends return { grantId, exportName, token, reviewer }})
The Digest service computes digest(algorithm, data) as bytes and digestHex(algorithm, data) as lowercase hex. Algorithms are values: Digest.md5, Digest.sha1, Digest.sha256, Digest.sha384, and Digest.sha512. Output is stable byte for byte, so digests can be persisted. layerWebCrypto runs SHA on crypto.subtle and MD5 on a vendored pure TypeScript implementation; NodeCrypto.layerDigest runs both synchronously on node:crypto, which is faster for small inputs.
MD5 and SHA-1 are broken for collision resistance; use them only for compatibility with existing checksums and protocols. A digest of a low-entropy value such as a national ID can be reversed by guessing; use a Mac with a server-side key when the input is guessable.
HMAC with Mac.hmacSha1, hmacSha256, hmacSha384, or hmacSha512. The service has generateKey(algorithm), sign(key, data), and verify(key, tag, data), which returns a boolean and compares in constant time. Build keys with Mac.key(algorithm, bytes) (any non-empty length; an empty key fails with InvalidKey) or Mac.fromCryptoKey for a non-extractable WebCrypto key, and export with Mac.toBytes. Mac.timingSafeEqual(a, b) compares fixed-length secrets you computed elsewhere; arrays of different lengths return false immediately.
Fragment · Type-checked
ts
import { Effect } from "effect"import { Mac } from "effect/crypto"declare const webhookSecret: Uint8Array// Verify a payroll provider's webhook signature.export const verifyWebhook = (body: Uint8Array, signature: Uint8Array) => Effect.gen(function*() { const mac = yield* Mac.Mac const key = yield* Mac.key(Mac.hmacSha256, webhookSecret) return yield* mac.verify(key, signature, body) })
Schema.MacKeyFromBytes(algorithm) decodes key bytes (base64 under Config.schema) into a Mac.Key, so a secret can be read straight from configuration. Key schemas exist for every family (Schema.AeadKeyFromBytes, Schema.SignaturePublicKeyFromFormat, Schema.KeyWrapKeyFromFormat, …). Encoding a secret or private key back to bytes fails with a Forbidden issue unless the schema was built with { allowEncode: true }, and the plain key schemas refuse JSON serialization.
Authenticated encryption with Aead.aes128Gcm, aes256Gcm, chacha20Poly1305, or xchacha20Poly1305. The service has generateKey(algorithm), encrypt(key, plaintext, { nonce, aad? }), and decrypt(key, ciphertext, { nonce, aad? }). Ciphertext is ciphertext‖tag with a 16-byte tag. Any tampering with the ciphertext, tag, or additional data fails decrypt with a detail-free DecryptionFailed reason. Aead.key validates the key length (a wrong length fails with InvalidKey; AES-192 is not supported), and Aead.fromCryptoKey accepts AES-GCM CryptoKeys only.
Never reuse a nonce with the same key. Random 12-byte nonces are safe up to roughly 2³² messages per key; past that, use a counter, or XChaCha20-Poly1305 whose 24-byte nonce can be random. ChaCha20 variants run a vendored pure TypeScript implementation unless the layer supplies a native one (NodeCrypto.layerAead does on Node.js; Aead.layerWebCryptoWith({ implementations }) lets you supply your own).
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Aead, SecureRandom } from "effect/crypto"export const sealSalaryFile = (key: Aead.Key, plaintext: Uint8Array, employeeId: string) => Effect.gen(function*() { const aead = yield* Aead.Aead const random = yield* SecureRandom.SecureRandom const nonce = yield* random.randomBytes(24) // XChaCha20 nonces may be random const aad = new TextEncoder().encode(employeeId) // bound to the record, not secret const ciphertext = yield* aead.encrypt(key, plaintext, { nonce, aad }) return { nonce, ciphertext } })export const openSalaryFile = (key: Aead.Key, nonce: Uint8Array, ciphertext: Uint8Array, employeeId: string) => Effect.gen(function*() { const aead = yield* Aead.Aead return yield* aead.decrypt(key, ciphertext, { nonce, aad: new TextEncoder().encode(employeeId) }) }).pipe( // Collapse every decryption failure to one response; detail leaks oracles. Effect.catchReason("CryptoError", "DecryptionFailed", () => Effect.succeed(undefined)) )
Unauthenticated AES-CTR (Cipher.aes128Ctr, aes256Ctr) and AES-CBC with PKCS#7 padding (aes128Cbc, aes256Cbc), with the same generateKey / encrypt / decrypt shape as Aead but an { iv } option. Use it only for protocols that pair these modes with their own MAC (SSH, SRTP, JWE, CMS); otherwise use Aead. An attacker can change the ciphertext undetected, AES-CTR decryption never fails, and AES-CBC reports bad padding and bad length as the same DecryptionFailed. Verify a MAC before decrypting (encrypt-then-MAC), and never reuse an IV with one key.
The Kdf service has one method, derive(algorithm, secret, { salt, length, info? }), which returns plain bytes. Turn them into a typed key with the target family's constructor, such as Aead.key or Mac.key. Algorithms are Kdf.hkdfSha1 … hkdfSha512 (or Kdf.hkdf(Digest.sha256)), Kdf.pbkdf2Sha256 (600,000 iterations) or Kdf.pbkdf2({ hash, iterations }), and Kdf.argon2id({ memory?, passes?, parallelism? }), which defaults to 64 MiB, 3 passes, and 4 lanes.
The secret is bytes, so encode passwords yourself, normalizing Unicode first when users type on different platforms. Kdf.layerWebCrypto cannot run Argon2id and fails with an Unsupported reason, so a portable program can fall back to PBKDF2; NodeCrypto.layerKdf supports it on Node.js 24.7+ and Bun 1.4.
Digital signatures with Signature.ed25519, ecdsaP256 / ecdsaP384 / ecdsaP521 (hashed with SHA-256/384/512, as JOSE ES256/384/512), and RSA-PSS or RSASSA-PKCS1-v1_5 (rsaPssSha256, rsaPkcs1v15Sha256, … at 3072 bits, or Signature.rsaPss({ hash, modulusLength })). The service has generateKeyPair(algorithm), sign(privateKey, data), verify(publicKey, signature, data) (a boolean), and publicKeyOf(privateKey).
Only Ed25519 private keys (the 32-byte seed) and Ed25519 or uncompressed-point ECDSA public keys have raw constructors (Signature.privateKey, Signature.publicKey); other keys come from generateKeyPair, privateKeyFromCryptoKey / publicKeyFromCryptoKey, or KeyFormat. Ed25519 needs Chrome 137, Firefox 129, or Safari 17 in browsers.
X25519 (KeyAgreement.x25519) and ECDH on P-256, P-384, and P-521 (ecdhP256, …). The service has generateKeyPair, deriveSharedSecret(privateKey, publicKey), and publicKeyOf. Both keys must use the same algorithm, which the types enforce. The shared secret is raw bytes: pass it through Kdf (HKDF) before using it as a key. X25519 needs Chrome 133, Firefox 130, or Safari 17 in browsers.
AES-KW (KeyWrap.aes128Kw, aes256Kw) and RSA-OAEP (rsaOaepSha256, rsaOaepSha1, or KeyWrap.rsaOaep({ hash, modulusLength })). The service has generateKey (AES-KW), generateKeyPair (RSA-OAEP), wrap(wrapKey, key), and unwrap(unwrapKey, algorithm, wrapped), which returns a typed key of the given algorithm. wrap takes an Aead, Cipher, Mac, or KeyWrap key, never raw bytes. AES-KW wraps keys whose length is a multiple of 8 and at least 16 bytes; other lengths fail with InvalidArgument. A key-encryption key is the key most worth keeping non-extractable, so in browsers build it with KeyWrap.fromCryptoKey.
Plain functions, not a service, that run on the WebCrypto reference and require nothing: decodePublic(format, algorithm, data), decodePrivate(...), decodeSecret(...), and encode(format, key). Formats are KeyFormat.spki (public DER), pkcs8 (private DER), jwk (every role), import-only pkcs1 (RSA) and sec1 (EC), and KeyFormat.pem(format) for PEM text with 64-column lines. The algorithm decides the family of the result: decoding with Signature.ecdsaP256 gives a Signature key, with KeyAgreement.ecdhP256 a KeyAgreement key. Secret keys are read and written only as JWK.
Malformed data or a key of another algorithm fails with InvalidKey; encoding a non-extractable CryptoKey fails with NotExtractable. EC private keys must include their public point, written JWKs contain only kty, crv, and the key material, and callers parse and stringify JSON themselves. JWK data is typed as KeyFormat.JsonWebKey, the module's own declaration of the RFC 7517 members, so code that reads or writes JWKs type-checks without the DOM library. For JWKs that carry kid, alg, and use, use Jwk.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { KeyFormat, Signature } from "effect/crypto"// Publish a freshly generated signing key as a JWK for a JWKS endpoint.export const newSigningKey = Effect.gen(function*() { const signatures = yield* Signature.Signature const { privateKey, publicKey } = yield* signatures.generateKeyPair(Signature.ecdsaP256) const jwk = yield* KeyFormat.encode(KeyFormat.jwk, publicKey) // { kty: "EC", crv: "P-256", x, y } const pkcs8Pem = yield* KeyFormat.encode(KeyFormat.pem(KeyFormat.pkcs8), privateKey) return { jwk, pkcs8Pem }})
Every effect/crypto failure is one CryptoError whose module and method name the operation ("Aead", "decrypt") and whose reason is InvalidArgument, InvalidKey, DecryptionFailed, Unsupported, or NotExtractable. The message reads "Aead.decrypt: <reason message>". Match reasons with Effect.catchReason("CryptoError", "DecryptionFailed", ...), and narrow unknown values with CryptoError.isCryptoError / isCryptoErrorReason. SecureRandom and Digest never fail this way.
The error is not a schema, so it cannot be a typed failure in an HttpApi or Rpc contract. Map it at the boundary to a deliberately vague response (for example DecryptionFailed to 401); sending crypto failure detail to clients is how oracles leak.
WebCrypto.WebCrypto is a Context.Reference to the WebCrypto Crypto object (typed as typeof globalThis.crypto), defaulting to globalThis.crypto. Every layerWebCrypto, the KeyFormat functions, and key functions that touch crypto.subtle (such as Mac.toBytes on a CryptoKey) read it. WebCrypto.layer(crypto) swaps it for a polyfill, a worker's object, or a test double. A CryptoKey passed to fromCryptoKey must come from that same object. In a browser's insecure context, operations that need crypto.subtle die with crypto.subtle is unavailable, while layers still build and SecureRandom and the pure TypeScript algorithms (MD5, ChaCha20) keep working.
The fromCryptoKey, privateKeyFromCryptoKey, and publicKeyFromCryptoKey constructors of Aead, Cipher, KeyAgreement, KeyWrap, Mac, and Signature accept WebCrypto.CryptoKey, a structural type (algorithm.name, extractable, type, usages) that keys from both the browser's crypto.subtle and Node's webcrypto satisfy, so the declarations compile with only @types/node or only the DOM library. Satisfying the type proves nothing at runtime: the constructor checks the key's type, algorithm, and usages and fails with InvalidKey when they do not fit.
The effect/jose modules implement compact JSON Web Keys, Signatures, Encryption, and Tokens on the services above: HMAC runs on Mac, asymmetric signatures on Signature, encryption on Aead with IVs from SecureRandom, thumbprints on Digest, and key import and export on KeyFormat. Each function's requirements name only the services it uses (verifying with an HMAC key needs Mac, with a public key Signature), so provide the same crypto layers as for direct use. Import them from the barrel: import { Jwk, Jwks, Jwt } from "effect/jose".
The supported profile is deliberately small, and everything outside it is rejected rather than ignored:
Allowed
JWS algorithms
HS256, HS384, HS512; RS256/RS384/RS512 (RSASSA-PKCS1-v1_5) and PS256/PS384/PS512 (RSA-PSS), RSA keys of at least 2048 bits; ES256/ES384/ES512 on P-256/P-384/P-521; EdDSA with Ed25519 only
JWE
dir key management with A256GCM content encryption only: no RSA-OAEP, AES key wrap, ECDH-ES, or password-based key management, so both sides share one 32-byte key
Serialization
compact only; the JSON serializations and the crit, b64, and (JWE) zip header parameters fail as InvalidToken
alg: "none" is not an algorithm here. An unsecured token, or a token whose alg is not in the table, fails with InvalidToken before any key is used, in every function including Jwt.decodeUnverified.
The key chooses the algorithm. A key is imported for exactly one algorithm (Jwk.importPublic(jwk, "ES256")), signing writes that algorithm into the protected header, and verifying a token whose alg differs from the key's fails with AlgorithmNotAllowed. An HS256 token is never checked with an RSA public key as the HMAC secret.
Key sets require an allow-list.Jws.verifyWithKeySet and Jwt.verifyWithKeySet take a non-empty algorithms list of asymmetric algorithms. The token's alg is checked against it before any key lookup, and an HMAC token never verifies through a key set.
Nothing bounds token size. Reject over-long input, such as an oversized Authorization header, before verifying, decrypting, or decoding it.
Secrets stay redacted.sign and encrypt return Redacted<string>, the verify and decrypt functions accept a string or a Redacted, generated private and secret JWKs are Redacted, and the crypto key inside an imported key prints only its algorithm.
Key sets are services. Verification by kid reads a Jwks service: a fixed set from Jwks.layerLocal, or an HTTPS endpoint from Jwks.layerRemote. The remote layer fetches on first use, caches the set for timeToLive (10 minutes), refetches for an unknown key at most once per cooldown (30 seconds), and fails lookups with KeySetUnavailable when an expired set cannot be refreshed. It never falls back to the expired set.
back to a JWK carrying alg, kid, and use: "sig", or to DER (default) or { format: "pem" }; private output is Redacted
An import fails with InvalidKey when the key's family or curve does not fit the algorithm, when its alg, use, or key_ops members forbid the use (use must be "sig", or "enc" for dir; key_ops must include verify for a public key, sign for a private key, and both operations of a secret key: sign and verify, or encrypt and decrypt for dir), when an RSA modulus is shorter than 2048 bits, or when a key member is not canonical unpadded base64url. Failures on private and secret material use a fixed message and drop the backend's diagnostic.
generateKeyPair({ algorithm, kid?, modulusLength? }) (needs Signature) returns { publicKey, privateKey } as JWKs that both carry alg, use: "sig", and the kid when one is given, with the private half redacted; RSA defaults to and requires at least 2048 bits. generateSecret(algorithm, { kid? }) (needs SecureRandom) returns a redacted secret JWK of 32, 48, or 64 random bytes for HMAC and 32 for dir. thumbprint(input, hash?) computes an RFC 7638 thumbprint (SHA-256 by default, SHA-384 and SHA-512 allowed) and thumbprintUri its RFC 9278 URN; both need Digest, hash only the required members, and give a private key the same thumbprint as its public key. A secret key's thumbprint is derived from the secret, so treat it as sensitive.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Jwk, type Jwks } from "effect/jose"// Rotate in a new signing key; publish only the public half.export const rotateSigningKey = (kid: string) => Effect.gen(function*() { const pair = yield* Jwk.generateKeyPair({ algorithm: "ES256", kid }) const signingKey = yield* Jwk.importPrivate(pair.privateKey, "ES256") const fingerprint = yield* Jwk.thumbprint(pair.publicKey) // Serve as /.well-known/jwks.json; KeySet rejects private members. const document: Jwks.KeySet = { keys: [pair.publicKey] } return { signingKey, document, fingerprint, privateJwk: pair.privateKey } })
Compact JSON Web Signatures over raw bytes. Jws.sign(payload, key, header?) returns a Redacted<string>. The header may set typ, cty, a kid (defaulting to the key's), and further JSON-valued parameters; alg comes from the key, and crit and b64 cannot be set (a runtime attempt fails with InvalidArgument). Jws.verify(token, key) returns { protectedHeader, payload }. Both require Jws.KeyRequirements<K>: Mac for an HMAC SecretKey, Signature for a PrivateKey or PublicKey.
Jws.verifyWithKeySet(token, { algorithms }) reads the token's alg and kid, resolves a public key from the Jwks service, and also returns the key it used; it requires Jwks | Signature. A resolved key whose algorithm differs from the token's is rejected with AlgorithmNotAllowed, even from a custom Jwks implementation.
Failure
Reason
Wrong number of segments, non-canonical base64url, a header that is not a JSON object, an unsupported or malformed parameter, alg: "none"
InvalidToken
The token's alg is not the key's, is outside algorithms, or is HMAC through a key set
AlgorithmNotAllowed
The signature does not match
SignatureVerificationFailed
Key set lookup
KeyNotFound, AmbiguousKey, KeySetUnavailable
Use Jws for signed non-JSON payloads; for JSON claims use Jwt. On Node.js and Bun, NodeCrypto.layerMac computes HMAC signatures synchronously on node:crypto.
Signed and encrypted JWTs whose claims are a Schema. Jwt.sign(schema, claims, key, header?) encodes the claims through the schema and signs them; the encoded value must be a JSON object whose registered claims have the right shapes, or sign fails with a Schema.SchemaError. Jwt.verify(schema, token, key, options?), Jwt.verifyWithKeySet(schema, token, { algorithms, ...options }), and, for encrypted tokens, Jwt.encrypt / Jwt.decrypt (see Jwe) complete the set. The error type is Jwt.JwtError, which is JoseError | Schema.SchemaError. A verified result is { claims, registeredClaims, protectedHeader }, plus key from verifyWithKeySet and decrypt.
Verification works in a fixed order: the options are validated, the token is authenticated, the registered claims are checked against the policy, and only then is the payload decoded with the application schema. A schema never sees an unauthenticated or expired payload, so its SchemaError always concerns an authentic token.
Check
Default and rule
exp
Checked whenever present: the token is expired once the current second reaches exp, beyond clockTolerance. Not required unless listed in requiredClaims
nbf
Checked whenever present: notYetValid while it is later than now plus clockTolerance
iat
Ignored unless maxTokenAge is set; then it is required, fails future when later than now plus the tolerance, and tooOld when older than the maximum age
iss, sub, aud
Checked only when issuer (one value or a list), subject, or audience is given. A missing claim then fails missing; aud, a string or an array, must contain at least one accepted audience
typ header
Checked only when typ is given; compared case-insensitively, with the application/ prefix optional, so "at+jwt" matches "application/at+jwt"
jti
Never checked beyond presence through requiredClaims
clockTolerance
Zero. A number is milliseconds; a negative, NaN, or infinite duration (here or in maxTokenAge) fails with InvalidArgument before any cryptography
Claim shapes
A registered claim of the wrong type, such as a string exp, fails invalid whether or not a policy reads it
The current time comes from Clock in whole seconds, so TestClock drives expiry in tests. For access tokens, pass requiredClaims: ["exp"]; without it a token with no exp never expires.
Jwt.decodeUnverified(token) returns the protected header and the raw JSON claims of a signed JWT, and requires nothing. It still rejects a malformed token and an unsupported alg (including none), but it checks no signature, no time, and no claim shapes, and the claims are not schema-decoded. Use it only to choose how to verify, for example to read iss and pick the issuer's key set; never authorize from it.
Self-contained source · Type-checked
ts
import { Effect, Layer, Redacted, Schema } from "effect"import { SecureRandom, Signature } from "effect/crypto"import { FetchHttpClient } from "effect/http"import { Jwks, Jwt } from "effect/jose"class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {}const AccessClaims = Schema.Struct({ sub: Schema.String, scope: Schema.optionalKey(Schema.String)})// Every rejection becomes the same 401; the reason is logged server-side only.export const authenticate = (bearer: string) => Jwt.verifyWithKeySet(AccessClaims, Redacted.make(bearer), { algorithms: ["RS256", "ES256"], issuer: "https://login.example.com/", audience: "payroll-api", requiredClaims: ["exp"], clockTolerance: "30 seconds" }).pipe( Effect.map(({ claims }) => claims), Effect.tapError((error) => Effect.logDebug("token rejected", error.message)), Effect.mapError(() => new Unauthorized()) )// A fetch client that reports a redirect instead of following it.const NoRedirectFetch = FetchHttpClient.layer.pipe( Layer.provide(Layer.succeed(FetchHttpClient.RequestInit, { redirect: "manual" })))export const AuthLive = Layer.mergeAll( Jwks.layerRemote({ url: "https://login.example.com/.well-known/jwks.json" }).pipe( Layer.provide(NoRedirectFetch) ), Signature.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))
Compact JSON Web Encryption with a shared key: dir key management and A256GCM content encryption. Jwe.encrypt(plaintext, key, header?) takes a SecretKey<"dir"> from Jwk.importSecret(jwk, "dir"), draws a random 96-bit IV, and requires Aead | SecureRandom. alg and enc are fixed, kid defaults to the key's, and crit and zip are rejected. The protected header is the AEAD's additional data, so a modified header fails decryption.
Jwe.decrypt(token, keyOrResolver) returns { protectedHeader, plaintext, key } and requires Aead. To rotate keys, pass a resolver (header) => Effect<SecretKey<"dir">, E, R> instead of a key: it runs after the structural checks, its errors and requirements are added to the result, and it receives an unauthenticated header, so use it only to select a key, for example by kid. A tampered token or the wrong key fails with a detail-free DecryptionFailed. Jwt.encrypt and Jwt.decrypt add schema-typed claims and the same claim policy as Jwt.verify, applied after authenticated decryption.
dir tokens are for one party, or for services that already share a secret. To encrypt for a recipient's public key, combine KeyAgreement, Kdf, and Aead yourself; JWE has no public-key key management in this profile.
The Jwks.Jwks service resolves a verification key for a Selection of { algorithm, kid?, protectedHeader? }. Jwks.makeLocal(keySet) and Jwks.layerLocal(keySet) serve a fixed set; Jwks.makeRemote(options) (requires HttpClient | Scope) and Jwks.layerRemote(options) (a Layer<Jwks, JoseError, HttpClient>) fetch one. The Jwks.KeySet schema accepts public JWKs, keeps keys of other families or curves without ever selecting them, and fails on a private or symmetric member anywhere in the set. A custom service built with Jwks.Jwks.of({ resolve }) can select keys another way, for example from an extra header parameter; the protectedHeader it receives is unauthenticated.
Key selection. A key is a candidate when its family and curve fit the algorithm (RSA for RS* and PS*, EC on the matching curve for ES*, OKP Ed25519 for EdDSA), its alg, use, and key_ops members (when present) allow verification with that algorithm, and, when the token has a kid, its kid is equal. A key without kid never matches a token that has one. No candidate fails with KeyNotFound; more than one fails with AmbiguousKey, which is what a token without kid meets in a set holding two keys of one type. Issue tokens with a kid: Jws.sign copies the key's into the header. Each selected JWK is imported once per algorithm and cached.
Remote key sets.layerRemote validates its options when the layer is built and fails with InvalidArgument for a URL that is not HTTPS or that carries credentials or a fragment, a negative or non-finite duration, a zero timeToLive or timeout, or a limit that is not a positive integer. It does not fetch until the first lookup.
Option
Default
Behavior
url
required
Take it from configuration, never from a token. Only a 200 response from exactly this URL is accepted
timeToLive
10 minutes
How long a fetched set is used. Concurrent lookups share one request
cooldown
30 seconds
Minimum time since the last fetch attempt before refetching for an unknown key or retrying after a failure
timeout
5 seconds
Covers the request and reading the body
maxResponseBytes
131072
A larger body fails the fetch
maxKeys
64
Counts every key in the document, including unsupported ones
A lookup that finds no key in a fresh set refetches, unless the last attempt was within cooldown; then it fails with KeyNotFound. Unknown kids cannot drive one request per token, and a key published seconds after a fetch is found only once the cooldown has passed. When there is no fresh set (first use, or after timeToLive), a failed fetch (non-200 status, another URL, invalid document, size or key limits, timeout, transport error) fails every waiting lookup with KeySetUnavailable, and later lookups fail fast with the same reason until cooldown passes. There is no fallback to the expired set. A failed refetch for an unknown key fails only that lookup and keeps the fresh set in use. Closing the layer's scope interrupts a fetch in flight, and later lookups fail with KeySetUnavailable.
The URL check runs on the response, so it cannot stop a client from sending the redirected request. Give the layer a client that does not follow redirects: FetchHttpClient follows them unless its layer is given FetchHttpClient.RequestInit with { redirect: "manual" } (as in the Jwt example), and a client wrapped with HttpClient.followRedirects follows them too.
Every effect/jose failure is one JoseError whose reason says what went wrong. Configuration, transport, and import reasons carry a description (and a cause when there is one); authentication reasons carry nothing about the token, its claims, the plaintext, or the key.
Reason
Raised when
InvalidToken
The compact serialization, protected header, or payload is malformed, or uses an unsupported parameter or algorithm
InvalidKey
Key material cannot be imported or does not fit the algorithm or operation
InvalidArgument
An option is rejected before any work: empty algorithms, an unusable key-set URL, an invalid duration, a forbidden header parameter
AlgorithmNotAllowed
The token's alg is not the key's or is outside the allow-list
SignatureVerificationFailed / DecryptionFailed
Authentication failed
KeyNotFound / AmbiguousKey
No key, or more than one key, matches the algorithm and kid
KeySetUnavailable
A remote key set cannot be fetched or read, is cooling down after a failed fetch, or belongs to a closed layer
ClaimValidationFailed
claim is one of iss, sub, aud, exp, nbf, iat, jti, or typ, and reason is invalid, missing, mismatch, expired, notYetValid, tooOld, or future
Match reasons with Effect.catchReason("JoseError", "ClaimValidationFailed", ...) and narrow unknown values with JoseError.isJoseError / isJoseErrorReason. Like CryptoError, it is not a schema; map it at the boundary to one vague response, such as a 401 for every authentication and claim failure, because telling a client which check failed helps an attacker.
Note: Eight core modules under effect/reactivity, one mental model. Atom describes a reactive value (a constant, a derived computation, a writable cell, or an Effect/Stream). AtomRegistry is the store that runs atoms, caches them, and tracks the dependency graph. AsyncResult is the loading/success/failure state every effectful atom produces. AtomRef is a lightweight standalone observable cell (no registry). Reactivity is the low-level key-based invalidation engine. AtomHttpApi and AtomRpc turn a typed comp-service client into ready-made query/mutation atoms. Hydration ships server-computed atom state to the client. Then three framework bindings wrap it for components.
An Atom<A> is not a value — it's a recipe with a read function the registry runs, plus metadata for caching, laziness, and refresh. Atom.make is overloaded: pass a plain value for a writable cell, a function of get for a derived/computed atom, or an Effect/Stream for an atom whose value is an AsyncResult.
Mental model: spreadsheet cells. A writable atom is a cell you type into. A derived atom is a formula cell — it calls get(other) to read inputs, and the registry records that edge so the formula reruns only when an input changes. An effectful atom is an async formula; instead of a bare value it exposes the state of that computation.
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import { Atom } from "effect/reactivity"// 1. Writable state — pass a plain value. Atom.make(x) returns Writable<x>.// A planner-controlled proposed raise, in percent.const proposedRaisePct = Atom.make(4)// 2. Derived / computed — a function of `get`. Re-reads only when the raise changes.// New salary as a multiplier of the current base (base read elsewhere).const raiseMultiplier = Atom.make((get) => 1 + get(proposedRaisePct) / 100)// 3. Effect-backed — value becomes AsyncResult<EquityGrant, HrisUnavailable>.const equityGrant = Atom.make( Effect.gen(function*() { return yield* fetchEquityGrant("emp_1042") }))// 4. Derived effectful — depends on another atom AND runs an Effect.// Re-fetch the comp summary whenever the proposed raise changes.const compSummary = Atom.make((get) => Effect.gen(function*() { const pct = get(proposedRaisePct) // tracked dependency return yield* computeCompSummary("emp_1042", pct) }))
For event-driven work, use Atom.fn. It returns an AtomResultFn<Arg, A, E>: a writable atom whose value is an AsyncResult and whose write kicks off the computation with the supplied argument. Write Atom.Reset to clear it or Atom.Interrupt to cancel the in-flight fiber. Atom.fnSync is the synchronous sibling (value is an Option until first call).
Fragment · Type-checked
ts
import { Effect } from "effect"import { Atom } from "effect/reactivity"interface RaiseRecommendation { readonly employeeId: string readonly newSalary: number}declare const recordRaise: (rec: RaiseRecommendation) => Effect.Effect<void>// A "mutation"-style atom: setting a raise recommendation runs the Effect.// The construction option allows overlapping writes; without it, a new write// replaces the in-flight one.const submitRaise = Atom.fn( (rec: RaiseRecommendation) => recordRaise(rec), { concurrent: true })// registry.set(submitRaise, rec) -> Initial -> waiting -> Success// registry.set(submitRaise, Atom.Reset) -> back to Initial// registry.set(submitRaise, Atom.Interrupt) -> cancel the in-flight write
With { concurrent: true }, two overlapping calls that both resolve synchronously each still land their own Success/Failure outcome — a synchronous result is no longer lost when another concurrent call settles around the same time.
Tip:Atom.map / Atom.mapResult transform an atom's value (the latter maps inside the AsyncResult success). Every atom uses Object.is by default; Atom.withEquality<A>(equals) installs a comparator that suppresses dependent and listener updates when successive values compare equal. Atom.keepAlive stops an atom being disposed when it has no subscribers; Atom.setIdleTTL(atom, "30 seconds") disposes it after a quiet period instead. Atom.family((employeeId) => Atom.make(...)) memoizes one atom per argument (via WeakRef where available); a finalizer for an evicted entry never removes a newer atom that has since been cached under the same key. Atom.withLabel tags an atom for debugging. Atom.subscriptionRef bridges a SubscriptionRef into an atom, and Atom.pull turns a Stream into a paginated, writable "load more" atom.
Other high-value combinators stay on the same graph: debounce(duration) delays noisy publications; withRefresh(duration) schedules a refresh; swr({ staleTime, ... }) adds stale-while-revalidate behavior, deferring a stale refresh until after the triggering read and skipping it outright if the source has since become fresh or the atom was disposed — so a one-shot unmounted read never kicks off a refresh for a source it no longer needs; withFallback(fallback) supplies an async result (marked waiting) while the primary is Initial — when the primary is writable the combined atom stays writable and forwards every write and refresh to the primary, never to the fallback; and optimistic / optimisticFn model provisional mutation state with refresh or rollback. batch(fn) coalesces synchronous writes, including writes that a batch commit listener itself queues — those are processed rather than dropped. Persistence and URL helpers include platform-neutral kvs (schema-typed KeyValueStore persistence), browser-oriented searchParam (preserves the URL hash and omits empty query strings), and refreshOnWindowFocus (safe to use on the server — no window means no focus events, so it simply never fires); on the server, withServerValue, withServerValueInitial, and getServerValue provide deterministic reads. The Reactivity deep dive shows these in a connected application.
Where services come from. An effectful atom that needs services can't conjure a Layer out of thin air. Atom.runtime(layer) builds an AtomRuntime — itself an atom holding the built Context — and gives you runtime.atom(...), runtime.fn(...), and runtime.pull(...) constructors that run Effects with that layer provided. By default its Layer.MemoMap is registry-scoped: derived atoms share built services inside one AtomRegistry, while separate SSR requests and tests build isolated instances. Use Atom.context({ memoMap }) only when you intentionally need custom or cross-registry sharing. Replacing a runtime atom's layer through registry initial values (for example to inject a test layer) keeps the Reactivity and global layers, so invalidation stays shared. When an atom is disposed, a failing scope finalizer is logged at References.UnhandledLogLevel through the runtime's logger; interruption-only cleanup is not logged.
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import { Atom } from "effect/reactivity"// The built Layer is shared by live/retained runtime atoms in this registry.// If the final consumer is disposed, a later read may acquire it again.const runtime = Atom.runtime(CompService.layer)// This effect can `yield* CompService` — the runtime provides it.const roster = runtime.atom( Effect.gen(function*() { const comp = yield* CompService return yield* comp.listEmployees("dept_eng") }))
Reach for it when you have application state — local, derived, or fetched — that something needs to react to.
The store. A Registry evaluates atoms, caches their current values in Nodes, tracks parent/child dependency links, applies writes and refreshes, fans out to subscribers, and disposes unused nodes. Atoms are stateless descriptions; the registry is where state lives. The same atom can hold different values in two different registries. Most apps have exactly one (a framework provider creates it); tests and SSR spin up throwaway registries freely.
Mental model: the spreadsheet engine. Atoms are formulas; the registry is the running document with cached cell values and the recalculation graph. It also owns the scheduler that batches update work.
Self-contained source · Type-checked
ts
import { Atom, AtomRegistry } from "effect/reactivity"const proposedRaisePct = Atom.make(4)const raiseMultiplier = Atom.make((get) => 1 + get(proposedRaisePct) / 100)const registry = AtomRegistry.make()registry.get(proposedRaisePct) // 4registry.set(proposedRaisePct, 6)registry.get(raiseMultiplier) // 1.06 — recomputed because the raise changed// Subscribe imperatively; returns an unsubscribe fn.const cancel = registry.subscribe(raiseMultiplier, (m) => console.log("multiplier =", m))registry.set(proposedRaisePct, 8) // logs: multiplier = 1.08cancel()// `mount` keeps an atom alive (and running, for effectful atoms) for a lifetime.const unmount = registry.mount(proposedRaisePct)unmount()
subscribe(atom, f) calls f on the atom's next change; pass { immediate: true } to also receive the current value at once. Either way, subscribing builds the atom (running its read function, and starting an effectful atom), so the listener hears later changes even when nothing has read the atom yet. The same holds for get.subscribe, get.stream with withoutInitialValue, and useAtomSubscribe in @effect/atom-react.
As a service.AtomRegistry is also a Context.Service with a layer. AtomRegistry.getResult waits for an AsyncResult atom to leave Initial. AtomRegistry.toStream / toStreamResult turn an atom into a Stream of its changes. make accepts initialValues (seed atoms before first read — basis of hydration), a custom scheduleTask, and a defaultIdleTTL.
The dependency graph underneath is robust against races between reads, writes, and disposal: an update reaches every current dependent through its node (no missed updates through a stale node), a dependency is released only once it is actually safe to do so, a superseded build of an atom cannot leak past the node that replaced it, and an atom whose build failed while being observed recovers on the next read instead of staying stuck.
Reach for it when you need to read or write atoms outside a component — in tests, in an Effect, at the SSR boundary — or to scope a self-contained bundle of reactive state to a subtree.
A standalone observable cell — read, set, map, subscribe — that does not go through a registry. AtomRef.make(value) gives a mutable ref; .prop("field") derives a child ref focused on one property of an object (or index of an array), and writing the child writes back through the parent immutably. AtomRef.collection(items) manages a reactive list of item refs with push/insertAt/remove.
Mental model: a featherweight observable independent of the spreadsheet. Equality-aware — a set to an equal value is a no-op and notifies nobody. No dependency graph, no async story. Use for fine-grained form state where a stable handle to one nested field should re-render only its own consumers.
Note: Don't confuse AtomRef with a handle to an atom's value. It is its own cell type, used standalone. The bridge in the other direction is Atom.subscriptionRef, which lifts a SubscriptionRef into a registry-managed atom. In React, useAtomRef(ref) subscribes a component straight to an AtomRef.
Reach for it when you want surgical, per-field observable state with minimal machinery and no need for the registry's dependency tracking.
The state of an asynchronous value. An AsyncResult<A, E> is one of three tags — Initial (no value yet), Success (carries value + timestamp), Failure (carries a Cause<E> on .cause, plus a previousSuccess) — and every state also carries a waiting boolean. The waiting flag lets you keep showing the last value while a refresh, retry, or revalidation is in flight instead of flashing back to a spinner.
Mental model: Exit plus "I might still be loading," designed for rendering. Every effectful atom (Atom.make(effect), Atom.fn, query atoms) produces one. You almost never construct these by hand — you match on them.
Fragment · Type-checked with fixture
ts
import { AsyncResult } from "effect/reactivity"declare const result: AsyncResult.AsyncResult<CompSummary, HrisUnavailable>// Three-way match — initial vs failure vs success.// onFailure receives the Failure, whose `.cause` is a Cause<HrisUnavailable>.const view = AsyncResult.match(result, { onInitial: () => "Loading comp…", onFailure: (f) => `Error: ${f.cause}`, onSuccess: (s) => `${s.value.employeeName}: $${s.value.proposedBase}`})// The UI-grade matcher: treats `waiting` (and Initial) as one "loading-ish"// case, and splits Failure into your typed error vs an unexpected defect.const ui = AsyncResult.matchWithWaiting(result, { onWaiting: (r) => ({ status: "loading", stale: AsyncResult.value(r) }), onError: (e) => ({ status: "error", error: e }), // e is HrisUnavailable onDefect: (d) => ({ status: "crash", defect: d }), onSuccess: (s) => ({ status: "ready", data: s.value })})
Tip:AsyncResult.value(r) returns an Option<A> of the latest success and, while a Failure is showing, falls back to its previousSuccess. getOrElse supplies a default, map/flatMap transform the success, and guards isSuccess/isFailure/isInitial/isWaiting let you branch directly. Because Failure holds a full Cause, matchWithError and matchWithWaiting are preferred over a raw three-way match when defects and typed errors should render differently. AsyncResult.Schema encodes results across the wire — used by AtomHttpApi/AtomRpc for hydration. AsyncResult.isInterrupted returns a plain boolean and does not narrow; branch with isFailure first. Two results are equal only when their contents are equal, so unrelated Equal values that share a tag and hash no longer compare equal. When an effect atom's asynchronous run fails, the last exposed success (an initialValue or a value published with get.setSelf) stays available as the failure's previousSuccess.
AsyncResult.all combines records or iterables (and plain values) into one result. The first non-success determines the result; an all-success result is waiting if any input success is waiting. When that first non-success is a failure, previousSuccess is rebuilt in the combined record or tuple shape, using each input's current or previous value. If any input has no value, the combined previous success is absent. Never render a single failed input's old value as though it were the whole combined view.
Reach for it when — any atom backed by an Effect or Stream gives you one; render its four states (loading, stale-while-revalidating, error, success) cleanly.
The bridge from a typed HttpApi client to ready-made atoms. AtomHttpApi.Service<Self>()(id, { api, httpClient }) builds a Context.Service that wraps the generated client and exposes two atom factories: .query(group, endpoint, request) returns a read atom of AsyncResult<Success, Error>, and .mutation(group, endpoint) returns an AtomResultFn you write to fire the call. It owns its own Atom.runtime, so the HTTP client layer is provided automatically.
Mental model: your API definition is the contract; this turns each endpoint into a reactive cell. Query atoms are deduped via Atom.family when their complete request keys are structurally equal: endpoint, params/query/payload/headers, response mode, reactivity keys, TTL, and serialization key all participate. For decoded-only queries, a serializationKey makes the decoded result hydratable and must be stable and unique for each distinct request within an endpoint, or different query atoms can share the same hydration identity. timeToLive controls idle retention, and reactivityKeys enable auto-refresh. Mutations run the endpoint and invalidate their supplied reactivity keys on success.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"import { FetchHttpClient } from "effect/http"import { AtomHttpApi } from "effect/reactivity"const CompSummary = Schema.Struct({ employeeId: Schema.Int, baseSalary: Schema.Finite, level: Schema.String})const CompApi = HttpApi.make("comp").add( HttpApiGroup.make("comp").add( HttpApiEndpoint.get("getCompSummary", "/employees/:id/comp", { params: { id: Schema.FiniteFromString }, success: CompSummary }) ))// One service = the client + atom factories, with its HTTP client layer baked in.class CompClient extends AtomHttpApi.Service<CompClient>()("app/CompClient", { api: CompApi, httpClient: FetchHttpClient.layer, baseUrl: "https://hr.internal/api"}) {}// This API declares no endpoint/middleware errors, so the typed result is// AsyncResult<CompSummary, never>. Transport and decoding failures are defects.const summary1042 = CompClient.query("comp", "getCompSummary", { params: { id: 1042 }, serializationKey: "comp:1042" // makes it hydratable})
Query atoms preserve endpoint and middleware errors in the typed error channel. The client catches transport and response-decoding failures of the request itself and converts them to defects, so render those through the Cause/onDefect path. A declared write endpoint would be exposed with CompClient.mutation(group, endpoint); this read-only example deliberately does not invent one.
Result types follow the generated client. The success type of a query or mutation atom is exactly what the generated HttpApiClient method returns for that endpoint and responseMode, including the non-JSON shapes:
Endpoint / mode
Atom success value
Where failures show up
Ordinary endpoint, "decoded-only" (the query default)
the decoded success type
endpoint + middleware errors typed; transport/decoding as defects
a [decoded, HttpClientResponse] tuple, or the HttpClientResponse alone
same; "response-only" drops the endpoint's error type
Server-sent events (HttpApiSchema.StreamSse)
a Stream of event values
in the stream's error channel: the declared stream error plus HttpClientError, Schema.SchemaError, Sse.Retry, and Sse.SseError (it was never before), so whoever consumes the stream must handle them
timeToLive: 0 is an explicit opt-out. Omitting timeToLive leaves the query under the registry's defaultIdleTTL; passing 0 (or 0n) sets a zero idle TTL, so an unmounted query is disposed as soon as it is unused and fetched again on remount. A finite duration keeps it that long; an infinite one keeps it alive.
Per-call SSE decoding options. A request may carry sseOptions (native Sse.DecodeOptions); they are part of the query key, so two queries that differ only in sseOptions are distinct atoms.
Mutations are isolated per service. Two AtomHttpApi (or AtomRpc) services that share an endpoint name or RPC tag each invoke their own client with their own arguments.
Literal and union responseMode values infer the corresponding success types.
Top-level groups work. Endpoints of an HttpApiGroup declared with topLevel: true are dispatched on the client root rather than under a group property; you still pass the group identifier to query / mutation.
Only "decoded-only" results are serializable.serializationKey has no effect in the other response modes, and a Stream is not a value a hydration packet can carry — do not give streaming queries a serialization key.
Reach for it when you have an HttpApi and want its endpoints as cache-aware, hydratable, auto-invalidating query/mutation atoms.
Same as AtomHttpApi but for an RpcGroup. AtomRpc.Service<Self>()(id, { group, protocol }) builds a service over a flattened RPC client with the same .query(tag, payload, options) and .mutation(tag) factories. If an RPC's success is an RpcSchema.Stream, its query returns a pull atom (Atom.PullResult) — write to it to pull the next batch and accumulate streamed results.
Mental model: same query/mutation/invalidation machinery as HTTP, keyed off the procedure tag + payload. reactivityKeys and idle retention (timeToLive) carry over. A non-stream query can also use a serializationKey; keep it unique for each distinct payload within its RPC tag. Streaming pull queries ignore serialization keys. Per-request headers are RPC-flavored. Supply the transport as the protocol layer; the runtime is built for you.
The result error type is the full client-side union: the RPC's declared error, RpcClientError, and both the declared error and the client-side error of every middleware on that RPC. A streaming query's PullResult error also includes the stream's own error type. Matching exhaustively on _tag has to account for middleware failures such as an expired-session error.
RPCs whose middleware declares requires are queryable.query infers the same types as mutation for them rather than resolving to never.
Tag-selected flat clients infer correctly.AtomRpc.query and AtomRpc.mutation built from a flat (union-of-tag) RPC client infer the selected RPC's actual payload and result types instead of never.
The atom types have names.AtomRpc.Query<R> and AtomRpc.Mutation<R> are the types query and mutation return for an RPC R (they distribute over a union), so an exported atom can be annotated as AtomRpc.Query<Rpc.ExtractTag<RpcGroup.Rpcs<typeof CompRpcs>, "getVestedEquity">>. Selecting an RPC by tag no longer tests every RPC of the group, which keeps type-checking fast for large groups.
timeToLive: 0 opts out of idle retention, exactly as in AtomHttpApi; omit the option to inherit the registry default.
Stream-backed mutations invalidate on success only. Reactivity keys of an atom Stream mutation are invalidated after successful completion, not on failure, defect, interruption, or replacement by a newer write.
Mutations cannot target streaming RPCs (the type is never); use query and pull.
Reach for it when your backend speaks Effect RPC and you want the frontend to consume it as atoms — including streaming procedures surfaced as incremental pull atoms.
Server-to-client state transfer for atoms. Hydration.dehydrate(registry) walks a registry and encodes every atom marked Atom.serializable; decoded-only HttpApi queries and non-stream RPC queries become serializable when given a serializationKey. Entries are keyed by that serialization key. With the default encodeInitialAs: "ignore", or with "value-only", the array is JSON-compatible; embed it only through a framework-safe escaped serialization channel, never raw string interpolation into a <script>. Hydration.hydrate(registry, state) preloads encoded values into another registry before atoms are first read, so the client renders without an initial refetch.
Mental model: freeze-dry the relevant cells on the server, ship the value packet in your HTML, and reconstitute it into the client registry. encodeInitialAs: "promise" instead attaches a live resultPromise; it is only for a streaming transport that preserves promises and must not be JSON-stringified or embedded as ordinary data.
Fragment · Type-checked with fixture
ts
import { Hydration } from "effect/reactivity"// On the server, after rendering with a registry that ran your comp query atoms:const packet = Hydration.dehydrate(serverRegistry)// JSON-serialize `packet` into the page…// On the client, before first render:Hydration.hydrate(clientRegistry, packet)
Seeded atoms still run by default. A hydrated (or Atom.initialValue-seeded) effect or stream atom builds on first read or mount and runs its effect, because the dependencies it reads are only known once it has run. Pass skipInitialRun: true to Atom.serializable({ key, schema, skipInitialRun }) or Atom.initialValue(atom, value, { skipInitialRun: true }) to keep the seeded value until the atom is refreshed or a dependency changes; get(...) calls in the factory and withReactivity keys are still tracked, and an Initial seed never skips the run.
Newer client results are kept. For an atom already in the registry, hydrate does not overwrite a non-InitialAsyncResult with an Initial one, or a Success with an older Success (compared by the results' timestamps). Plain values and failures are always applied, and the packet's dehydratedAt is not consulted. Existing subscribers are notified immediately.
Decode failures fall back to client computation. If hydration data fails schema decoding, or a streamed initial result cannot be encoded, the atom computes on the client instead of throwing or waiting forever.
Atom.Serializable encodes to and decodes from Schema.Json, matching the JSON codec Atom.serializable uses at runtime. Code that reads the encoded value directly may need to narrow it.
One bad atom does not abort the packet. If a serializable atom's current value cannot be encoded by its schema (a SchemaError), dehydrate skips that atom and encodes the rest; any other exception still propagates. The skipped atom simply refetches on the client, so treat a missing key as "not hydrated", not as an error — and log encode failures in development, because the usual cause is a schema that does not cover the atom's whole value.
For custom serializable atoms, the codec covers the atom's complete value. In particular, an effectful atom needs an AsyncResult.Schema(...), not just its success schema; the release-matched comprehensive upstream Schema guide covers codecs and serialization in depth.
Reach for it when you do SSR or static rendering and want fetched atom state to survive the trip to the browser instead of refetching on mount.
The low-level invalidation engine that reactivity keys ride on. Reactivity is a Context.Service that maps arbitrary keys to handlers: invalidate(keys) runs every handler registered for those keys, mutation(keys, effect) wraps an effect so a successful run invalidates them, and query(keys, effect) / stream(keys, effect) expose an effect as a queue/stream that reruns whenever its keys are invalidated. It caches nothing — it is pure pub/sub for "this data changed."
Mental model: the wiring under the magic. When an AtomHttpApi mutation lists reactivityKeys: ["comp"] and a query atom was built with matching keys, this service connects the write to the refetch. You rarely call it directly, but it explains how cache invalidation propagates and lets you wire key-based invalidation into non-atom Effects.
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import { Reactivity } from "effect/reactivity"const recordRaise = (rec: RaiseRecommendation) => Effect.gen(function*() { const reactivity = yield* Reactivity.Reactivity // run the write, and on success invalidate everything keyed "comp". return yield* reactivity.mutation(["comp"], db.insertRaise(rec)) })
Reactivity.Reactivity is both the Context key and the branded service type. There is no Reactivity.Service alias; annotate a dependency as Reactivity.Reactivity, and build a custom instance with Reactivity.make (it adds the [Reactivity.TypeId] brand) rather than an object literal.
Keys may repeat. A query or stream whose key list names the same key twice (or a record form that expands to a key you also listed) stores its handler once per key, and its scope cleanup does not fail on the repeat.
Reruns are serialized and coalesced. While one rerun is in flight, further invalidations collapse into a single pending rerun, and a query matched by several invalidated keys reruns once per invalidation or batch flush.
A failed query stops rerunning. When a query (or SqlClient.reactiveMailbox) run fails, later invalidations do not rerun it and pending reruns are discarded.
Invalidations inside a SQL transaction wait for the outermost commit and are dropped on rollback.
Keys can be typed. Augment Reactivity.Keys (declare module "effect/reactivity/Reactivity" { interface Keys { readonly employee: number } }) and the public reactivity APIs — Reactivity.mutation / query / invalidate, Atom reactivity options, AtomHttpApi, AtomRpc, SqlClient.reactive, and EventLog.groupReactivity — reject undeclared key names and mismatched ids. With no keys declared, any keys are accepted. Methods on the Reactivity service instance still accept any key, for keys known only at runtime.
Reach for it when you need key-based invalidation outside the atom layer (e.g. a SQL repo), or to understand what reactivityKeys are doing.
The core above is framework-agnostic. Each binding (1) provides an AtomRegistry through the framework's context and (2) exposes hooks/primitives that subscribe a component to that registry.
pkg @effect/atom-react — React hooks + RegistryProvider. Peer range: react >=19.0.0 <20.0.0 and scheduler >=0.25.0 <0.29.0 (relaxed from react >=19.2.7, so any React 19 works). useAtomValue(atom) reads, useAtom(writable) returns [value, set], useAtomSet / useAtomRefresh / useAtomMount give write/refresh/keep-alive without subscribing, and useAtomSuspense reads an AsyncResult atom through React Suspense. HydrationBoundary applies dehydrated state; ScopedAtom.make makes a subtree-local atom. RegistryProvider's initialValues accepts [atom, value, { skipInitialRun }] tuples. Atom writes triggered while React renders (for example an atom whose initializer sets another atom) are deferred, so other components do not update during render.
pkg @effect/atom-solid — The Solid binding. useAtomValue(() => atom) returns an accessor, useAtom(() => writable) returns an accessor/setter tuple, and useAtomResource bridges an AsyncResult atom to a Solid resource. Its RegistryProvider may leave defaultIdleTTL undefined, matching React: unused atoms are then cleaned up immediately instead of lingering for a provider-imposed TTL.
pkg @effect/atom-vue — The Vue binding. useAtomValue(() => atom) returns a readonly Ref, while useAtom(() => writable) returns a readonly Ref plus a setter through Vue's provide/inject registry.
In every binding, a setter in promise or promiseExit mode resolves with the atom's next settled result, not a result tied to that write; serialize writes when each caller needs its own result.
Hooks built on React.useSyncExternalStore that read from the nearest RegistryContext. Wrap your tree in RegistryProvider; it creates one registry, accepts an optional defaultIdleTTL, and schedules whole-registry disposal 500 ms after unmount so an immediate remount can reuse it. The provider does not impose an idle TTL unless you pass one. The fallback context uses a standalone registry with a 400 ms default idle TTL, so a lone hook still works without a provider.
Mental model: the hooks are the only React-specific code. useAtomValue subscribes and re-renders on change; useAtom adds a setter; useAtomSuspense throws a promise while the result is Initial so a <Suspense> boundary shows the fallback (and throws the squashed cause for an error boundary unless you pass includeFailure).
Self-contained source · Type-checked
tsx
import { RegistryProvider, useAtomValue, useAtom } from "@effect/atom-react"import { Atom } from "effect/reactivity"// A writable atom for a proposed raise %, and a derived preview of the new base.const proposedRaisePct = Atom.make(4)const newBasePreview = Atom.make((get) => Math.round(120000 * (1 + get(proposedRaisePct) / 100)))function RaiseSlider() { const [pct, setPct] = useAtom(proposedRaisePct) // [value, setter] const newBase = useAtomValue(newBasePreview) // read-only, re-renders on change return ( <label> Raise {pct}% → new base ${newBase.toLocaleString()} <input type="range" min={0} max={20} value={pct} onChange={(e) => setPct(e.target.valueAsNumber)} /> </label> )}export function App() { return ( <RegistryProvider> <RaiseSlider /> </RegistryProvider> )}
End-to-end: effectful atom → AsyncResult → React
A query atom from AtomHttpApi (or an RPC client) produces an AsyncResult; the component reads it with useAtomValue and renders the four states with AsyncResult.matchWithWaiting. No useEffect, no manual loading flags, no race conditions.
Fragment · Type-checked with fixture
tsx
import { Option } from "effect"import { useAtomValue } from "@effect/atom-react"import { AsyncResult } from "effect/reactivity"// `CompClient` is the AtomHttpApi.Service from the AtomHttpApi section above.const summary1042 = CompClient.query("comp", "getCompSummary", { params: { id: 1042 }, serializationKey: "comp:1042"})function CompSummaryCard() { const result = useAtomValue(summary1042) // AsyncResult<CompSummary, never> return AsyncResult.matchWithWaiting(result, { // Initial or revalidating: keep showing the last good summary if we have it. onWaiting: (r) => Option.match(AsyncResult.value(r), { onNone: () => <p>Loading compensation…</p>, onSome: (s) => ( <p aria-busy="true">Refreshing employee {s.employeeId}: ${s.baseSalary.toLocaleString()}</p> ) }), onError: (e) => <p role="alert">Declared endpoint error: {String(e)}</p>, onDefect: (d) => <p role="alert">Unexpected defect: {String(d)}</p>, onSuccess: (s) => ( <div> <h3>Employee {s.value.employeeId}</h3> <p>Base salary: ${s.value.baseSalary.toLocaleString()}</p> <p>Level: {s.value.level}</p> </div> ) })}
Tip: Prefer Suspense over manual matching? const s = useAtomSuspense(summary1042) returns the Success directly and suspends while Initial — wrap the component in <Suspense fallback> and an error boundary. For SSR, render on the server with a registry, Hydration.dehydrate it, ship the packet, and feed it to <HydrationBoundary state={packet}> on the client.
Reach for it when building UI: useAtom for local writable state, useAtomValue + matchWithWaiting (or useAtomSuspense) for fetched data, useAtomSet for mutations, and RegistryProvider/HydrationBoundary at the edges.
effect/ai provides a provider-agnostic AI toolkit. Business logic depends on LanguageModel.LanguageModel from context; a concrete provider (OpenAI, Anthropic, Amazon Bedrock, OpenRouter, or any OpenAI-compatible endpoint) is injected as a Layer. Schemas validate structured outputs and tool parameters, streaming is a Stream, errors are typed, and all calls are traced. Swapping providers requires changing a Layer, not application code. For fixed-answer judgments (a label, a rating on a scale, or a probability) there is a second, narrower service, DecisionModel, with its own providers.
Model Context Protocol servers built from the same tools, and McpClient for consuming another server's tools as a Toolkit, are on MCP Servers.
Official companions: The release-matched AI examples cover language-model calls, tools, and stateful chat. The broader AI documentation source tree and LLMS.md are the official executable corpus and coding-agent entry point.
Note: Every example below assumes a provider client Layer built from Config. Providers need an HttpClient — you choose which one (here FetchHttpClient):
Self-contained source · Type-checked
ts
import { Config, Layer } from "effect"import { OpenAiClient } from "@effect/ai-openai"import { FetchHttpClient } from "effect/http"// Reads OPENAI_API_KEY from your ConfigProvider; the key is Redacted, so it// never leaks into logs. Provide an HttpClient for the provider to use.const OpenAiClientLayer = OpenAiClient.layerConfig({ apiKey: Config.Redacted("OPENAI_API_KEY")}).pipe(Layer.provide(FetchHttpClient.layer))
A provider-agnostic service for generating text, schema-validated objects, and streaming with first-class tool calling. Write against LanguageModel.LanguageModel; supply a provider Layer via Effect.provide.
Three verbs: generateText returns a rich response (text, tool calls/results, finish reason, token usage). generateObject asks for JSON and decodes it through your Schema — response.value is typed and validated; bad output becomes a typed AiError. streamText returns a Stream of response parts. Static functions (LanguageModel.generateText(...)) read the model from context; identical methods exist on the yielded service value.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { LanguageModel } from "effect/ai"import { OpenAiLanguageModel } from "@effect/ai-openai"// 1) Plain text. `generateText` returns text + usage + finishReason.// Here: draft a concise performance-review summary from a manager's notes.const draftReviewSummary = Effect.fn("draftReviewSummary")(function*(notes: string) { const response = yield* LanguageModel.generateText({ prompt: `Summarize this engineer's annual performance in two sentences, ` + `neutral tone, suitable for a review packet:\n${notes}` }) yield* Effect.log(`out tokens: ${response.usage.outputTokens.total}`) return response.text})// 2) Schema-validated object. The model's JSON is DECODED through this schema,// so `value` is a real, validated `RaiseRecommendation` — or a typed AiError.const RaiseRecommendation = Schema.Struct({ employeeId: Schema.String, rating: Schema.Literals(["below", "meets", "exceeds"]), proposedIncreasePct: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), rationale: Schema.String})const recommendRaise = Effect.fn("recommendRaise")(function*(reviewNotes: string) { const response = yield* LanguageModel.generateObject({ objectName: "raise_recommendation", prompt: `From these review notes, propose a merit increase within band:\n${reviewNotes}`, schema: RaiseRecommendation }) return response.value // typeof RaiseRecommendation.Type, fully decoded})// Provide a concrete provider at the edge. `.model(...)` returns a Model// (a Layer) carrying the OpenAI client requirement — swap this one line to// switch providers, no business-logic changes.const program = draftReviewSummary("…").pipe( Effect.provide(OpenAiLanguageModel.model("gpt-5.2")))
An empty reply is a failure unless you allow it. By default generateObject fails with a StructuredOutputError when the model returns no text. Pass allowEmpty: true when "nothing to extract" is a legitimate answer: empty or whitespace-only text then yields Option.none(), and valid output Option.some(value); nonempty text that does not decode still fails. Only the literal true types value as Option<A> (LanguageModel.ExtractObjectValue computes it); a widened boolean types it as A | Option<A>. Chat.generateObject accepts the same option.
Self-contained source · Type-checked
ts
import { Effect, Option, Schema } from "effect"import { LanguageModel } from "effect/ai"const Escalation = Schema.Struct({ employeeId: Schema.String, reason: Schema.String })// Most review notes contain no escalation; an empty reply means "none", not an error.const findEscalation = Effect.fn("findEscalation")(function*(notes: string) { const response = yield* LanguageModel.generateObject({ objectName: "escalation", prompt: `If these notes require an HR escalation, describe it; otherwise reply with nothing:\n${notes}`, schema: Escalation, allowEmpty: true }) return Option.map(response.value, (escalation) => escalation.reason) // Option<string>})
Streaming yields typed parts; filter for the deltas you need:
Self-contained source · Type-checked
ts
import { Stream } from "effect"import { LanguageModel, type Response } from "effect/ai"import { OpenAiLanguageModel } from "@effect/ai-openai"const summaryTokens = LanguageModel.streamText({ prompt: "Draft talking points for a promotion case as a bulleted list."}).pipe( // Each chunk is a Response part: text-start, text-delta, finish, tool-call… Stream.filter((part): part is Response.TextDeltaPart => part.type === "text-delta"), Stream.map((part) => part.delta), Stream.provide(OpenAiLanguageModel.model("gpt-5.2")))
Tip: Because a model is just a Layer of requirements, you can wrap several in an ExecutionPlan — try a cheap model up to N times, then fall back to a stronger one — and apply it with Effect.withExecutionPlan. Use plan.captureRequirements to fold both providers' client requirements into your service Layer.
Self-contained source · Type-checked
ts
import { Effect, ExecutionPlan } from "effect"import { LanguageModel } from "effect/ai"import { OpenAiLanguageModel } from "@effect/ai-openai"import { AnthropicLanguageModel } from "@effect/ai-anthropic"const ReviewPlan = ExecutionPlan.make( { provide: OpenAiLanguageModel.model("gpt-5.2"), attempts: 3 }, { provide: AnthropicLanguageModel.model("claude-opus-4-6"), attempts: 2 })const draft = LanguageModel.generateText({ prompt: "Summarize this review cycle." }) .pipe(Effect.withExecutionPlan(ReviewPlan))
Tool-call resolution: concurrency and manual dispatch
When the toolkit you pass carries handlers, generateText, generateObject, and streamText resolve the model's tool calls during the call: parameters are decoded, handlers run, and the results come back in response.toolResults. Two options on every generation call govern that step.
Option
Default
Rule
concurrency
"unbounded"
Set a number whenever a handler touches a rate-limited or stateful dependency, because one model turn may request many tool calls and they all start at once by default.
disableToolCallResolution
false
Pass true when the application must run its own gates (authorization, approval, idempotency claim) before any handler executes. The tools are still advertised to the model; no handler runs.
With disableToolCallResolution: true under the default strict validation, user-tool params stay in their JSON encoding, typed as Schema.Json (a malformed call still fails with InvalidOutputError). Decode with Schema.toCodecJson(tool.parametersSchema) before passing arguments to typed authorization or policy code. No handler result is produced, and handler errors and handler services drop out of the call's error and requirement types. Dispatch a call yourself through the toolkit's handle(name, jsonParams, toolCallId?, parseOptions?), which decodes the JSON parameters, runs the handler, and returns a Stream of { result, encodedResult, isFailure, failureOrigin, preliminary } values: preliminary results first, then the final one. Pass the original JSON to handle, not the decoded domain value: a Schema.Date parameter, for example, travels as an ISO string, and an omitted optional parameter you construct yourself is null rather than undefined. The optional SchemaAST.ParseOptions tune the parameter decode; { onExcessProperty: "error" } rejects arguments the schema does not declare. With failureMode: "error" a parameter failure fails the returned Effect and a handler failure fails the stream instead of producing a final value.
For an application-owned validation loop, combine disableToolCallResolution: true with toolCallValidation: "deferred". Model-generated calls then carry unknown parameters and may name undeclared tools, even without a toolkit. Validate the name and decode/normalize the arguments before authorization or dispatch. Strict validation remains the default; provider-executed calls remain validated in deferred mode too. Anthropic, OpenAI, and OpenAI-compatible providers support this option. Deferring validation is not permission to execute arbitrary names or arguments.
Every failure is tagged with the phase that produced it, a Tool.FailureOrigin: "parameters" (arguments did not decode), "handler" (the handler failed), or "result" (the handler's output failed to validate or encode). A returned failure carries it as failureOrigin; a raised one carries it as the Toolkit.FailureOrigin annotation on its Cause, read with Context.get(Cause.annotations(cause), Toolkit.FailureOrigin). Use it to tell "the model sent bad arguments" from "the tool broke" without parsing messages.
Fragment · Type-checked
ts
import { Effect, Schema, Stream } from "effect"import { LanguageModel, Tool, Toolkit } from "effect/ai"class RaiseGateDenied extends Schema.TaggedError<RaiseGateDenied>()("RaiseGateDenied", { toolCallId: Schema.String, reason: Schema.String}) {}const SubmitRaise = Tool.make("SubmitRaise", { description: "Submit a merit increase for HRBP approval", parameters: Schema.Struct({ employeeId: Schema.String, increasePct: Schema.Finite }), success: Schema.Struct({ requestId: Schema.String })})const RaiseToolkit = Toolkit.make(SubmitRaise)// Application policy: actor, tenant, band limits, idempotency claim.declare const authorizeRaise: ( toolCallId: string, params: { readonly employeeId: string; readonly increasePct: number }) => Effect.Effect<void, RaiseGateDenied>const proposeAndSubmit = Effect.fn("proposeAndSubmit")(function*(notes: string) { const toolkit = yield* RaiseToolkit // handlers come from RaiseToolkit.toLayer(...) const response = yield* LanguageModel.generateText({ prompt: `Propose a merit increase from these notes:\n${notes}`, toolkit, disableToolCallResolution: true // the model proposes; nothing executes yet }) const requestIds: Array<string> = [] for (const call of response.toolCalls) { const params = yield* Schema.decodeUnknownEffect( Schema.toCodecJson(SubmitRaise.parametersSchema) )(call.params) yield* authorizeRaise(call.id, params) // Run `handle` and drain its stream in the same Effect: the handler is a // child fiber of this call, so interrupting the request interrupts it too. const results = yield* toolkit.handle(call.name, call.params, call.id) const final = yield* Stream.runLast(results) // `result` is the success type, the declared failure type, or a // Tool.ExecutionFailure; `isFailure` is a plain boolean, so narrow structurally. if (final._tag === "Some" && "requestId" in final.value.result) { requestIds.push(final.value.result.requestId) } } return requestIds})
Note: When a response finishes with an incomplete reason (anything other than "stop", "tool-calls", or "pause" — for example "length"), automatic resolution does not start handlers. Each executable tool call instead receives a synthesized failed result of type "execution-interrupted" so the history stays well-formed for the next provider request.
Note: Calls to a client-executed tool are never resolved, even with resolution enabled: they appear in response.toolCalls without a result, and Chat.streamText stops its step loop there so the application can answer them.
LanguageModel.LanguageModel, EmbeddingModel.EmbeddingModel, Chat.Chat, and Reactivity.Reactivity each name both the Context key and the service interface; the older LanguageModel.Service / Chat.Service / EmbeddingModel.Service type aliases no longer exist. Each interface carries a [TypeId] brand. Build implementations with the module's constructor (LanguageModel.make, EmbeddingModel.make, Chat.empty / Chat.fromPrompt, Reactivity.make), because the constructor adds the brand; an object literal written by hand must include [LanguageModel.TypeId]: LanguageModel.TypeId (and the equivalent for the other modules) to type-check.
Reach for it when you need any LLM call — text, validated structured data, streaming, or tool use — without coupling to a vendor SDK. This is the default entry point.
A stateful conversation on top of LanguageModel. Owns a mutable history Ref; each turn automatically includes prior messages, and an agentic loop automatically appends tool results before the next turn.
Create with Chat.empty, Chat.fromPrompt (seed a system message), or Chat.fromJson/fromExport (rehydrate). Call session.generateText({ prompt }) per turn; history is threaded automatically. Inspect or persist via session.history (a Ref) and session.exportJson. Chat.makePersisted / Chat.layerPersisted support durable sessions.
Self-contained source · Type-checked
ts
import { Effect, Ref } from "effect"import { Chat, Prompt } from "effect/ai"import { OpenAiLanguageModel } from "@effect/ai-openai"// An HRBP assistant: a multi-turn helper for an HR business partner.const hrbpSession = Effect.gen(function*() { // Seed with a system message; history is maintained automatically. const session = yield* Chat.fromPrompt( Prompt.empty.pipe( Prompt.setSystem("You are an HRBP assistant. Stay within comp policy and be concise.") ) ) const first = yield* session.generateText({ prompt: "What's a typical merit increase for a strong-performing L4?" }) // The next turn sees the previous question AND answer — no manual context. const second = yield* session.generateText({ prompt: "And if their salary is already at band midpoint?" }) const history = yield* Ref.get(session.history) yield* Effect.log(`history has ${history.content.length} messages`) // Persist the whole conversation as JSON and rehydrate later. const json = yield* session.exportJson return { first: first.text, second: second.text, json }}).pipe(Effect.provide(OpenAiLanguageModel.model("gpt-5.2")))
For an agent, loop until the model stops calling tools — Chat folds each tool result back into history between turns. Give the loop a turn limit: a model that keeps requesting tools would otherwise spend tokens until something external stops it.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { Chat, Tool, Toolkit } from "effect/ai"class AgentTurnLimit extends Schema.TaggedError<AgentTurnLimit>()("AgentTurnLimit", { turns: Schema.Int}) {}const runHrbpAgent = <Tools extends Record<string, Tool.Any>>( question: string, tools: Toolkit.Toolkit<Tools>, maxTurns = 6) => Effect.gen(function*() { const session = yield* Chat.fromPrompt([ { role: "system", content: "Use tools to ground every comp answer in real band data." }, { role: "user", content: question } ]) for (let turn = 1; turn <= maxTurns; turn++) { const response = yield* session.generateText({ prompt: [], toolkit: tools, concurrency: 4 }) // Tool calls were executed and their results added to history for us. if (response.toolCalls.length === 0) return response.text // final answer } return yield* new AgentTurnLimit({ turns: maxTurns }) })
Streaming multi-round turns.session.streamText calls the model once by default. Its options (Chat.StreamTextOptions) add maxSteps: while a round ends with finish reason "tool-calls" and every call in it got a final result, the chat calls the model again with the updated history, up to maxSteps rounds in one stream. The loop also stops at a round that needs no tools, an incomplete finish, or a call left unanswered (a client-executed tool or an approval request). Each round ends with its own finish part, so sum usage over every finish you see, and history records each round in order, including the partial output of an interrupted one.
Fragment · Type-checked
ts
import { Effect, Stream } from "effect"import { Chat, type Response, type Tool, type Toolkit } from "effect/ai"declare const tools: Toolkit.Toolkit<Record<string, Tool.Any>>const streamAgentAnswer = (question: string) => Stream.unwrap(Effect.map(Chat.empty, (session) => session.streamText({ prompt: question, toolkit: tools, concurrency: 4, maxSteps: 5 }).pipe( Stream.filter((part): part is Response.TextDeltaPart => part.type === "text-delta"), Stream.map((part) => part.delta) )))
History rules.
Chat is in-process session state, not a store. Its history Ref has no tenant, version, or concurrency control; wrap it, or use Chat.makePersisted({ storeId }) / Chat.layerPersisted over a durable BackingPersistence layer (see Persistence), when several requests or processes can touch one conversation. A stored history that no longer decodes fails with a typed PersistenceError, not a defect.
Persisted chats depend on the backing key layout. Persistence stores are isolated under <storeId>:<key> keys. Histories that Chat.layerPersisted wrote on a KeyValueStore backing (Persistence.layerKvs / layerBackingKvs) under the earlier <storeId><key> layout are not read back and are not migrated or removed automatically; on Redis only store ids containing % or : are affected. Copy old keys to the new layout before upgrading if chat history must survive — see Persistence.
Exported history is a persisted format.exportJson keeps text parts, provider options, and files generated by the model when a response is folded back into the prompt, so a rehydrated session replays the same context. Prompt.FilePart bytes and URLs are encoded as tagged { _tag: "Uint8Array", base64 } and { _tag: "URL", href } objects that decode back to their original types. Tool results inside that history hold the JSON encoding of the schema chosen by their isFailure flag (see Tool), so a Schema.Date result is stored as an ISO string; review stored histories when a tool's success or failure schema changes.
Completed approvals stay in the response. When a non-streaming turn resolves a previously approved tool call, the finished result is retained in that response, so Chat records it and later turns do not execute the approved tool again.
Keep incomplete turns out of later prompts. If a turn fails, times out, or is interrupted mid-stream, persist that status and rebuild future context only from turns that reached a terminal finish part.
Reach for it when building a chatbot or agent that needs memory across turns, or needs save/restore of conversation state. For one-shot calls, plain LanguageModel is sufficient.
A single typed function the model can call. Bundles a name, a description (shown to the model), a parametersSchema the model fills in, and a successSchema for the handler's result. Parameters are validated on the way in; results on the way out. Both cross the boundary through the schema's JSON codec (Schema.toCodecJson): a Schema.Date parameter accepts the ISO string a model or MCP client sends, and a Schema.Date or Schema.BigInt result reaches the model, MCP clients, and Chat.exportJson as JSON. Provider-executed tools keep the provider's own payload.
Tool.make(name, { … }) defines user tools (handler required). Tool.providerDefined wraps server-side provider tools (web search, code interpreter — no handler needed). failureMode: "error" (default) routes handler failures to the effect's error channel; "return" feeds the error back to the model as a tool result. Annotate parameters with .annotate({ description }) for better model guidance.
toModelOutput: (result) => parts sends text and file parts (Prompt.ToolModelOutputPart, for example a rendered chart image) to the model in place of the encoded result, while the application still receives the typed result; Anthropic and OpenAI Responses send native content blocks, and OpenAI-compatible APIs and OpenRouter send text with a placeholder per file (Prompt.toolModelOutputToText). Tool.make and Tool.dynamic accept it. A tool whose parameters do not produce a JSON Schema object — Schema.Struct({}), say — fails with an UnsupportedSchemaError that names the tool; use Tool.EmptyParams instead.
Call .setNeedsApproval(true) for a sensitive tool, or pass a function of (params, { toolCallId, messages }) for dynamic approval. Toolkit handlers receive their own second context argument with the optional toolCallId and a preliminary(result) Effect for streaming progress; retain that ID when correlating approvals, audit records, and results.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { Tool } from "effect/ai"const EmployeeId = Schema.String.pipe(Schema.brand("EmployeeId"))// A tool that looks up an employee's CompBand. Name, description, an input// schema the model fills, an output schema for the handler result. Per-parameter// descriptions sharpen model behavior.const LookupCompBand = Tool.make("LookupCompBand", { description: "Look up the salary band (min/mid/max) for an employee's level", parameters: Schema.Struct({ employeeId: EmployeeId.annotate({ description: "e.g. 'emp-4821'" }), level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })).pipe( Schema.withDecodingDefault(Effect.succeed(4)) ).annotate({ description: "Job level; defaults to 4 if unknown" }) }), success: Schema.Struct({ level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite }), // "error" (default): handler failures go to the effect error channel. // "return": failures are returned to the model as a tool result instead. failureMode: "error"})
Declare failure when the model should see a domain error.Tool.make(name, { failure: BandNotFound, failureMode: "return" }) types the handler's error channel; failureMode: "error" keeps the same failure in the Effect error channel instead.
Tool.failureResultSchema(tool) is Schema.Union([AiError.AiError, tool.failureSchema, Tool.ExecutionFailure]). Use it, not the bare failure schema, when you decode stored failed results.
The codec is selected by isFailure, never guessed from the value. A tool with success: Schema.Number and failure: Schema.NumberFromString stores a failed 404 as "404".
Tool.FailureResult and Tool.Result include Tool.ExecutionFailure in both failure modes, so an exhaustive narrowing of a failed result has one more case. (Response.ToolResultPart(...) is typed as a Schema.Codec rather than a Schema.decodeTo; this only matters if you wrote that type out.)
Schema.Void encodes to null. A tool without a success schema (or with Schema.Void) has encodedResult: null, not undefined.
Parameter validation follows failureMode too. A call whose arguments do not decode produces ToolParameterValidationError (toolName and description only — the rejected arguments are no longer attached as toolParams). Under "error" the generation fails with that AiError; under "return" the error goes back to the model as a failed tool result so it can correct the call. Either way the handler does not run.
Note:Tool.dynamic(name, { parameters }) accepts a Schema or a raw JSON Schema for tools discovered at runtime (for example from an MCP server). After tool.setParameters(schema) the replacement schema is what gets advertised to the model. A tool annotated .annotate(Tool.Strict, true) needs an Effect Schema to be served over MCP: McpServer.toolkit / registerToolkit dies at registration on a strict dynamic tool whose parameters are raw JSON Schema, because the server could not enforce strictness on it. Annotate intent with Tool.Title, Tool.Readonly, Tool.Destructive, Tool.Idempotent, and Tool.OpenWorld; McpServer forwards them as MCP tool hints.
Migration: A Tool.dynamic tool without a success schema must return a JSON value, even when toModelOutput replaces what the model sees; returning a Date or another non-JSON value now fails with ToolResultEncodingError. Declare a success schema (for example Schema.Date), return JSON, or declare success: Schema.Void for a tool that returns undefined. Provider-defined tools keep their provider-defined type through setSuccess, setFailure, setParameters, setNeedsApproval, addDependency, annotate, and annotateMerge.
Tool.unsafeSecureJsonParse(text) is the JSON parser for untrusted tool text: it throws a SyntaxError for __proto__ keys and constructor.prototype shapes, including spellings hidden behind \u escapes.
Some tools run in the application that sent the request — a browser widget, a desktop host — not on the server. Declare them with execution: "client" on Tool.make or Tool.dynamic. The model is offered the tool and its calls are emitted, but LanguageModel never resolves them and the tool needs no handler in toLayer (calling it through toolkit.handle dies). The application answers each call with a tool-result message in its next request. Tool.isClientExecuted(tool) tests the mode and narrows the tool's type; Tool.Execution is "server" | "client", recorded as the tool's last type parameter so every combinator keeps it.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { Tool, Toolkit } from "effect/ai"// Runs in the HR partner's browser: shows a confirmation dialog and reports the choice.const ConfirmInUi = Tool.make("ConfirmInUi", { description: "Ask the HR partner to confirm an action in their browser", parameters: Schema.Struct({ message: Schema.String }), success: Schema.Struct({ confirmed: Schema.Boolean }), execution: "client"})const LookupBand = Tool.make("LookupBand", { parameters: Schema.Struct({ level: Schema.Int }), success: Schema.Struct({ mid: Schema.Finite })})const Tools = Toolkit.make(ConfirmInUi, LookupBand)// Only the server-executed tool needs a handler.const ToolsLayer = Tools.toLayer({ LookupBand: ({ level }) => Effect.succeed({ mid: 150_000 + level * 10_000 })})
Reach for it when the model needs to fetch data or call an API mid-generation. Define the contract here; group and implement with Toolkit.
A typed bundle of tools plus their handler implementations. Toolkit.make(...tools) groups any number of Tools; toolkit.toLayer(...) produces a Layer satisfying every handler. The framework decodes parameters, invokes the right handler, validates the result, and feeds it back to the model automatically.
Handlers are plain Effects and can yield other services. Toolkit.merge combines toolkits. A handler is interrupted when its result stream closes, including early termination, and the stream waits for that interruption to finish: a defect raised by the handler's interrupt finalizers fails the stream instead of being discarded. Preliminary results are buffered without limit unless you provide Toolkit.PreliminaryBuffer (a number or "unbounded"). Under failureMode: "error", a failing handler keeps every failure and its annotations in the cause.
Tool arguments stay out of traces by default.handle annotates the current span with gen_ai.tool.name and, when a call id is given, gen_ai.tool.call.id. Provide Layer.succeed(Toolkit.RecordToolArguments, true) to also record the arguments as JSON in gen_ai.tool.call.arguments; arguments carry user data, so enable it only where traces may hold it. McpServer reads the same setting for tools/call spans.
Migration: Tool spans no longer carry the tool and parameters attributes. Rename dashboards and queries to gen_ai.tool.name, and opt in with Toolkit.RecordToolArguments if you relied on recorded parameters.
Decoding tool calls needs the tools' parameter-schema services: Response.AllParts, Response.Part, and Response.StreamPart require them (exposed as Tool.ParametersDecodingServices<T>), including for toolkits with handlers. Called without a toolkit, they decode tool-call and tool-result parts for any tool name with unknown parameters and results. Provider-defined tools (e.g. OpenAiTool.WebSearch) can sit alongside user tools and run server-side, so they require no handler in toLayer.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"import { AiError, LanguageModel, Tool, Toolkit } from "effect/ai"import { OpenAiLanguageModel } from "@effect/ai-openai"// Kept self-contained here; a real module would reuse the Tool declared above.const LookupCompBand = Tool.make("LookupCompBand", { description: "Look up the salary band for a job level", parameters: Schema.Struct({ level: Schema.Int }), success: Schema.Struct({ level: Schema.Int, min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite })})const CompToolkit = Toolkit.make(LookupCompBand /*, GetEmployee, … */)// Implement every handler. Use the effectful toLayer factory only when// constructing the handlers themselves needs services.const CompToolkitLayer = CompToolkit.toLayer({ LookupCompBand: Effect.fn("LookupCompBand")(function*({ level }) { // In real code, yield* an Hris service and read the band table. return { level, min: 150_000, mid: 185_000, max: 220_000 } })})// Wire it into a model call. Set toolChoice: "required" to force a tool call.class CompAssistant extends Context.Service<CompAssistant, { answer: (q: string) => Effect.Effect<string, AiError.AiError>}>()("app/CompAssistant") { static layer = Layer.effect( CompAssistant, Effect.gen(function*() { const toolkit = yield* CompToolkit // resolves handlers from context // Capture OpenAiClient while constructing this service, so callers of // answer only see the declared AiError and no provider requirement. const model = yield* OpenAiLanguageModel.model("gpt-5.2").captureRequirements return CompAssistant.of({ answer: Effect.fn("answer")(function*(question: string) { const response = yield* LanguageModel.generateText({ prompt: question, toolkit, toolChoice: "auto" }) // Inspect what the model did: response.toolCalls / response.toolResults return response.text }, Effect.provide(model)) }) }) ).pipe(Layer.provide(CompToolkitLayer))}
Yielding a toolkit (yield* CompToolkit) resolves its handlers from context and returns a Toolkit.WithHandler with two members: tools and handle(name, params, toolCallId?). handle takes the parameters' JSON encoding, typed Schema.Json — what a provider or a stored tool call actually holds, with null rather than undefined for an omitted optional parameter — decodes it with the parameter schema's JSON codec, and returns an Effect of a result Stream. That is the entry point for manual dispatch and for tests that exercise one handler without a model.
Reach for it when exposing one or more tools to a model. Define tools with Tool, group here, implement handlers with toLayer, and pass the toolkit to generateText or Chat.
The provider-neutral representation of conversation input: an ordered list of Messages (system/user/assistant), each composed of typed Parts (text, file, reasoning, tool-call, tool-result).
RawInput means you can pass a plain string, an array of message objects, or a real Prompt — Prompt.make normalizes all three. Combinators: Prompt.empty, concat (append), setSystem (replace system message), fromMessages, and fromResponseParts (convert a model response into prompt history).
Self-contained source · Type-checked
ts
import { Prompt } from "effect/ai"// A string is the simplest prompt (becomes a single user message).const p0 = Prompt.make("Summarize this employee's review in one paragraph.")// Build structured, multi-message prompts and compose them.const system = Prompt.make([{ role: "system", content: "You are a compensation analyst." }])const user = Prompt.make([{ role: "user", content: "Is this raise within band?" }])const combined = Prompt.concat(system, user)// Replace whatever system message exists with a new one.const retargeted = Prompt.setSystem(combined, "You are a strict comp-policy reviewer.")
Reach for it when assembling prompts programmatically — injecting a system persona, stitching few-shot examples, or passing multi-part (text + file) input. For trivial calls, pass a string directly.
The typed vocabulary of model output. A non-streaming call returns a GenerateTextResponse whose content is an array of Parts; streaming yields a sequence of StreamParts. Convenience getters avoid manual part parsing.
Output is a tagged stream of parts: text-start / text-delta / text-end, reasoning-*, tool-call, tool-result, and a terminal finish carrying finish reason and token Usage. Accessors: .text, .reasoningText, .toolCalls, .toolResults, .finishReason, and .usage (with nested inputTokens/outputTokens breakdowns). A tool-result part's encodedResult (and the result of a prompt tool-result part) holds the JSON encoding for locally handled tools and the provider's own payload for provider-executed ones.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { LanguageModel, type Response } from "effect/ai"const inspect = Effect.gen(function*() { const res = yield* LanguageModel.generateText({ prompt: "Draft a one-line raise rationale." }) res.text // concatenated text parts res.finishReason // "stop" | "length" | "tool-calls" | … res.usage.inputTokens.total res.usage.outputTokens.total // When streaming, branch on the part tag: const onPart = (part: Response.StreamPart<{}>) => { if (part.type === "text-delta") return part.delta if (part.type === "finish") return `done: ${part.reason}` return "" } return onPart})
Reach for it when you need more than the final string — token accounting, finish reasons, reasoning traces, or precise streaming part handling.
A provider-agnostic service for turning text into vectors. embed(input) returns one embedding; embedMany(inputs) returns a batch with usage metadata. The single-input path is backed by a RequestResolver, so concurrent embed calls are automatically batched into one provider request.
Write against EmbeddingModel.EmbeddingModel; provide a provider Layer (e.g. OpenAiEmbeddingModel.model("text-embedding-3-small", { dimensions: 1536 })). Results preserve input order; embedMany([]) short-circuits without calling the provider. The configured vector size is available via the EmbeddingModel.Dimensions service. Concurrent embed calls share one embedMany call only when the optional batchKey(context) passed to EmbeddingModel.make returns equal keys; the batch runs with the first caller's context, so context that batchKey does not return (per-call FetchHttpClient.RequestInit, say) is not isolated. The OpenAI providers key batches by configuration overrides and client transforms.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { EmbeddingModel } from "effect/ai"import { OpenAiEmbeddingModel } from "@effect/ai-openai"// Embed job descriptions so you can match roles, detect duplicate reqs, or// power semantic search over the org's open positions.const embedJobDescriptions = Effect.gen(function*() { const model = yield* EmbeddingModel.EmbeddingModel // Auto-batched: these two run concurrently but hit the provider once. const [backend, frontend] = yield* Effect.all( [ model.embed("Senior Backend Engineer — distributed systems, Go, on-call"), model.embed("Senior Frontend Engineer — React, design systems, a11y") ], { concurrency: "unbounded" } ) // Or batch explicitly; response.embeddings keeps input order. const batch = yield* model.embedMany([ "Staff Data Scientist", "Engineering Manager", "Product Designer" ]) return { backend: backend.vector, frontend: frontend.vector, count: batch.embeddings.length }}).pipe( Effect.provide( OpenAiEmbeddingModel.model("text-embedding-3-small", { dimensions: 1536 }) ))
Note: A vector is only comparable with vectors from the same space. Store the provider, model name, dimensions, and your own normalization/schema version beside every embedding, and when any of them changes, build a fresh, separately versioned index from new embeddings.
Reach for it when building semantic search, role-matching, deduplication, or RAG retrieval — anything requiring text-to-vector conversion with automatic batching.
A decision definition is plain data: one input Schema plus named questions whose answers come from a closed set. Decision.make({ input, decisions }) builds it; nothing calls a model until DecisionModel.decide answers every decision in the definition in one provider call.
Three kinds of question:
Constructor
Asks
Answer
Decision.classify({ instructions, criteria })
Which label fits; criteria maps each label to a description.
{ label, probabilities, confidence? } — label is the provider's pick and need not be the most probable label.
Decision.rate({ instructions, criteria })
Where the input sits on an ordered scale; criteria lists levels lowest first.
{ rating, label, probabilities, confidence? } — rating is the probability-weighted position in [0, levels - 1] and can fall between two levels; label is the most probable level (the first one on a tie).
Decision.probability({ instructions, criteria? })
How likely a statement about the input holds; criteria (an optional { false, true } pair of descriptions) documents both outcomes but can be omitted.
{ probability } — the probability of true.
Answer keys and label types are inferred from the definition. The constructors validate eagerly and throw: classify needs at least two labels, rate at least two distinct levels, and make at least one decision. Define them at module level so a malformed definition fails at startup, not mid-request. criteria on a probability decision is optional — code that inspects a definition at runtime should read it as decision.criteria?.true, not assume it is present.
Instructions and descriptions accept Decision.Description: a string, JSON object, or JSON array. Classification descriptions may also be null when the label needs no explanation. Decision.rate accepts strings or { label, description } entries, but its returned Rate.criteria always contains objects: strings normalize to { label: value, description: value }. Code inspecting a definition must read .label rather than treating each level as a string. TypeSafe, Cloudflare, and OpenRouter forward structured instructions, descriptions, and score legends; provider behavior remains distinct from core answer validation.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Decision } from "effect/ai"// The input schema is the contract: `decide` encodes the value with// Schema.toCodecJson and sends the JSON as the decision state.export const RaiseRequest = Schema.Struct({ employeeId: Schema.String, level: Schema.Int, requestedIncreasePct: Schema.Finite, justification: Schema.String})// Three judgments about one raise request, answered together.export const RaiseRequestTriage = Decision.make({ input: RaiseRequest, decisions: { basis: Decision.classify({ instructions: "What the manager's justification mainly rests on", criteria: { performance: "Documented results or scope beyond the current level", market: "Pay below market for the role, or a competing offer", retention: "Flight risk or a critical skill without a backup", other: "None of the above" } }), evidence: Decision.rate({ instructions: "How well the justification is supported by specifics", criteria: ["unsupported", "anecdotal", "specific", "documented"] }), needsHrbpReview: Decision.probability({ instructions: "The request needs an HR business partner's review before approval", criteria: { false: "A routine request within merit-cycle policy", true: "An exception, an out-of-band amount, or sensitive circumstances" } }) }})
Reach for it when a question has a fixed answer space — routing, triage, policy checks, quality ratings — and you want the answer as a label or number your code can threshold, not as prose.
The provider-neutral service that answers a Decision definition. DecisionModel.decide(definition, { input }) encodes the input with Schema.toCodecJson (an explicit undefined field becomes null; an absent one stays absent), sends that state and every decision to the provider in one request, validates the reply, and returns { answers, usage }. It requires DecisionModel.DecisionModel plus the input schema's encoding services, and fails only with AiError.
Images are input fields. Declare a Decision.Image field in the input schema — its value is a DecisionModel.Image ({ mediaType, data } with base64, bytes, or a URL) — and refer to it by its path in instructions. decide replaces each image with a reference string in the encoded state and sends the images separately, once each. Decision.locate({ image: "photo", instructions }) answers with one bounding box around a target in an image field; Decision.make checks the path against the input's required image fields, and the answer is a box even when the target is absent, so pair it with a probability decision. Providers opt in with supportsImages: true and supportsLocate: true; others reject images or locate decisions with InvalidUserInputError before any network call.
Migration:DecideOptions.images is gone. Move images into the input schema as Decision.Image fields: DecisionModel.decide(Triage, { input: { report, screenshot } }). Decision.Any and DecisionModel.ProviderAnswer gained Locate variants, so exhaustive switches over them need that case, and a custom provider receives images as { reference, path, image }.
decide is all-or-nothing and also returns the response id, the answering modelId, and provider metadata. DecisionModel.decideSettled(definition, { input }) keeps valid answers instead: it returns outcomes, one Result per decision whose failure is an Unanswered with reason Missing, Refused, NoDistribution, or Invalid; provider failures still fail the effect. With decide, a refusal of any decision fails with ContentPolicyError.
The reply is validated before your code sees it; the provider is not trusted to follow the contract:
every decision is answered with its own kind, and a classify label must be one of its criteria keys;
each distribution covers every label or level and sums to 1 within 1e-6; confidence and probability lie in [0, 1]; a rating lies in [0, levels - 1];
a violation fails with reason InvalidOutputError, and an input that cannot be encoded fails with InvalidUserInputError before any provider call.
Validation proves shape, not calibration: whether a 0.3 means 30% depends on the provider. Choose thresholds from labeled historical cases, and treat them as application policy.
Fragment · Type-checked
ts
import { Effect, Layer, Schema } from "effect"import { Decision, DecisionModel } from "effect/ai"import { TypeSafeDecisionModel } from "@effect/ai-typesafe"// Kept self-contained here; a real module would import the definition above.const RaiseRequest = Schema.Struct({ employeeId: Schema.String, requestedIncreasePct: Schema.Finite, justification: Schema.String})const RaiseRequestTriage = Decision.make({ input: RaiseRequest, decisions: { evidence: Decision.rate({ instructions: "How well the justification is supported by specifics", criteria: ["unsupported", "anecdotal", "specific", "documented"] }), needsHrbpReview: Decision.probability({ instructions: "The request needs an HR business partner's review before approval", criteria: { false: "Routine, within policy", true: "Exception or sensitive" } }) }})type Route = "hrbp-review" | "return-to-manager" | "auto-approve"// Both answers come from one provider call; the thresholds are HR policy.const routeRaiseRequest = Effect.fn("routeRaiseRequest")(function*( request: typeof RaiseRequest.Type) { const { answers } = yield* DecisionModel.decide(RaiseRequestTriage, { input: request }) const route: Route = answers.needsHrbpReview.probability >= 0.3 ? "hrbp-review" : answers.evidence.rating < 1.5 ? "return-to-manager" : "auto-approve" return route})declare const request: typeof RaiseRequest.Type// Production: a provider's `.model(...)` is a Model Layer, like LanguageModel's.// It still requires TypeSafeClient (see Provider packages below).const routed = routeRaiseRequest(request).pipe( Effect.provide(TypeSafeDecisionModel.model("jev-latest")))// Tests: a scripted provider. The core validates its answers exactly as it// does a real provider's, and derives the rating label from the distribution.const ScriptedDecisions = Layer.effect( DecisionModel.DecisionModel, DecisionModel.make({ decide: () => Effect.succeed({ answers: { evidence: { _tag: "Rate", rating: 2.4, probabilities: { unsupported: 0.05, anecdotal: 0.1, specific: 0.25, documented: 0.6 } }, needsHrbpReview: { _tag: "Probability", probability: 0.1 } }, usage: { inputTokens: undefined, outputTokens: undefined } }) }))const routedInTest = routeRaiseRequest(request).pipe(Effect.provide(ScriptedDecisions))
DecisionModel.make({ decide, probabilityPrecision?, supportsImages?, supportsLocate? }) is also how to adapt an unsupported provider: decide receives { state, decisions, images? } and returns answers tagged "Classify", "Rate", "Probability" (or "Locate" when supportsLocate: true), optional probabilities, refusal answers, and token usage; the service it builds implements both decide and decideSettled. Returned answers and their probability records have null prototypes, so compare fields rather than deep-equality against an object literal.
A provider that rounds each probability to a fixed number of decimal places can return a distribution whose sum drifts slightly from 1. probabilityPrecision tells make how many decimal places the provider rounds to, so it accepts drift up to half a unit of the last place per label and rescales the distribution to sum to 1 instead of failing validation; a larger drift still fails with InvalidOutputError. The OpenRouter and TypeSafe providers both set probabilityPrecision: 2.
DecisionModel or generateObject?
Need
Use
A label, a level, or a likelihood from a fixed set, with a probability distribution to threshold on
DecisionModel
Several such judgments over the same input, in one call and one validated response
DecisionModel with several named decisions
Free-form fields, a rationale, nested data, a system prompt or conversation history, or tool calls
LanguageModel.generateObject / generateText
A provider that has no decisions API
LanguageModel.generateObject with a Schema.Literals field
A confidence field in a generateObject schema is text the model wrote about itself; a DecisionModel answer is a range-checked probability, or a distribution the core checked for completeness and normalization. The trade is expressiveness: a decision has only its per-question instructions and criteria, no prompt, history, or tools.
Reach for it when routing, triage, or scoring must be a number your code can threshold and audit. Keep LanguageModel for anything that needs words, structure, or tools.
The provider-agnostic handle every provider's .model(...) returns. A Model is a Layer that supplies AI services (LanguageModel, EmbeddingModel/Dimensions, or DecisionModel) and records two context values: Model.ProviderName and Model.ModelName.
Model.make(provider, name, layer) wraps any Layer producing a LanguageModel into a labeled, providable handle — useful for adapters (an in-house gateway, a self-hosted model) not covered by the provider packages. Use model.captureRequirements to fold the provider's client requirement into a service Layer; read Model.ProviderName/ModelName to log or branch on which model ran.
Fragment · Type-checked
ts
import { Effect, Layer } from "effect"import { LanguageModel, Model } from "effect/ai"declare const gatewayLayer: Layer.Layer<LanguageModel.LanguageModel>// Wrap any LanguageModel layer into a labeled, provider-agnostic handle.const inHouse = Model.make("acme-gateway", "review-drafter-v3", gatewayLayer)const program = Effect.gen(function*() { const provider = yield* Model.ProviderName // "acme-gateway" const name = yield* Model.ModelName // "review-drafter-v3" yield* Effect.log(`drafting review summary with ${provider}/${name}`) return yield* LanguageModel.generateText({ prompt: "Summarize this review." })}).pipe(Effect.provide(inHouse))
Reach for it when you need an unsupported provider, or want to read/log which provider+model handled a request.
A service for counting tokens and truncating a Prompt to a token budget. tokenize(input) returns the token array (use .length for a count); truncate(input, maxTokens) drops whole messages from the front until the prompt fits.
Tokenizer.make({ tokenize }) builds the service from a single tokenizing function — wrap a real provider tokenizer (e.g. tiktoken) or a cheap word-splitter for tests. truncate is implemented on top of tokenize by default.
truncate keeps the newest messages. It walks backward from the last message, re-tokenizes the whole retained suffix each time (so tokens the tokenizer charges between messages count against the budget), and stops at the first message that would overflow. It never splits a message, and it does not pin a leading system message — re-apply the system prompt with Prompt.setSystem after truncating when the persona must survive. Token counts from your tokenizer are an estimate for budgeting; the provider's reported usage is the reconciliation.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Tokenizer } from "effect/ai"// Estimate the size of a review packet before sending it to the model.const countTokens = Effect.gen(function*() { const tokenizer = yield* Tokenizer.Tokenizer const tokens = yield* tokenizer.tokenize("Q3 self-review and manager feedback…") return tokens.length})// A simple word-based tokenizer service (swap in a real BPE one for prod).const WordTokenizer = Tokenizer.make({ tokenize: (prompt) => Effect.succeed( prompt.content .flatMap((msg) => typeof msg.content === "string" ? msg.content.split(" ") : msg.content.flatMap((p) => (p.type === "text" ? p.text.split(" ") : [])) ) .map((_, i) => i) )})
Reach for it when you need to stay under a context window, estimate cost before a call, or trim long histories before sending.
A service that mints identifiers for AI artifacts, primarily tool-call IDs. Uses Effect's Random under the hood, so it is deterministic under a seeded test runtime.
IdGenerator.layer({ alphabet, prefix, separator, size }) produces IDs like tool_A1B2C3D4. The framework uses a sensible default; override to match a provider's expected ID format or to get reproducible IDs in tests via a custom Service.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { IdGenerator } from "effect/ai"const useIds = Effect.gen(function*() { const gen = yield* IdGenerator.IdGenerator return yield* gen.generateId() // e.g. "tool_A1B2C3D4"})// Configure the format, then provide it as a layer.const program = useIds.pipe( Effect.provide(IdGenerator.layer({ alphabet: "0123456789ABCDEF", prefix: "tool", separator: "_", size: 8 })))
Reach for it when you need stable, formatted, or deterministic tool-call IDs in tests, or a specific ID shape a provider expects.
Helpers that write standardized GenAI attributes onto OpenTelemetry spans, following the current OTel GenAI semantic conventions (provider name, model, temperature, token usage, etc.). AI calls are already traced; this enriches those spans.
addGenAIAnnotations(span, { provider, operation, request, response, usage }) stamps the correct attribute keys (it mutates the span). The provider is written as gen_ai.provider.name from provider: { name }; the older system option, gen_ai.system, and gen_ai.token.type were removed in 4.0.2. Provide a CurrentSpanTransformer to automatically annotate every AI span with custom logic. Pairs with @effect/opentelemetry for export.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Telemetry } from "effect/ai"// Stamp GenAI attributes on the span around a review-drafting call so cost and// token usage show up on your comp-tooling dashboards.const annotated = Effect.gen(function*() { const span = yield* Effect.currentSpan Telemetry.addGenAIAnnotations(span, { provider: { name: "openai" }, request: { model: "gpt-5.2", temperature: 0.7 }, usage: { inputTokens: 100, outputTokens: 50 } })})
Reach for it when running AI in production and needing spans/metrics aligned with GenAI OTel conventions for cost dashboards, latency, and token tracking.
The typed failure channel for all AI operations. Every provider call, tool invocation, and structured decode fails with an AiError carrying a structured reason, enabling LLM failures to be handled like any other Effect error.
One umbrella error (AiError, tag "AiError") wrapping a discriminated reason: RateLimitError, QuotaExhaustedError, AuthenticationError, ContentPolicyError, InvalidRequestError, InternalProviderError, NetworkError, InvalidResponseError (the provider's response or SSE stream did not decode), InvalidOutputError/StructuredOutputError (bad/unparseable model output), plus tool errors (ToolNotFoundError, ToolParameterValidationError, …). AiError.AiErrorReason is itself a Schema, so it can be embedded in domain error types.
Self-contained source · Type-checked
ts
import { Effect, Schedule, Schema } from "effect"import { AiError, LanguageModel } from "effect/ai"// Wrap provider failures in your own tagged error, reusing the reason schema.class ReviewServiceError extends Schema.TaggedError<ReviewServiceError>()("ReviewServiceError", { reason: AiError.AiErrorReason}) {}const draftSummary = LanguageModel.generateText({ prompt: "Summarize this employee's review."}).pipe( // Retry only transient rate-limit failures, and only a bounded number of // times: `upTo` caps both the recurrence count and the total backoff window. Effect.retry({ while: (error) => error.reason._tag === "RateLimitError", schedule: Schedule.exponential("200 millis").pipe( Schedule.upTo({ times: 3, duration: "10 seconds" }) ) }), // One absolute deadline for the call and all of its retries. Effect.timeout("30 seconds"), // Translate anything that still fails into our domain error. Effect.catchTag("AiError", (error) => Effect.fail(new ReviewServiceError({ reason: error.reason })) ))
Every reason class has an isRetryable getter, and AiError forwards it (error.isRetryable) together with error.retryAfter — the provider's requested delay when the reason is a RateLimitError that carried one.
reason._tag
isRetryable
What to do
RateLimitError
true
Back off; honor retryAfter when present.
InternalProviderError, NetworkError with reason: "TransportError"
Fix credentials, quota, input, or code; do not loop.
Retry only before output or side effects exist. Never retry after streamed text has reached the caller or after a mutating tool was dispatched; count every retry against the same token and time budget as the first attempt.
A fallback model is a different capability, not a retry. Re-validate tool, schema, and media support for it, and never use a fallback to get around a ContentPolicyError.
AuthenticationError has an optional description. On HTTP 401/403 the provider's own error text is passed through and appended to the kind-based hint, so logs say what was actually rejected. HTTP-derived reasons carry AiError.HttpContext — the optional response (AiError.HttpResponseDetails: status and headers) and body — but no request: AI errors and Response.ResponseMetadataPart never hold request headers or query parameters.
NetworkError records method and url, plus an optional cause holding the original HttpClientError unchanged and not redacted. NetworkError.fromHttpClientError sets it (all providers use it); NetworkError.fromRequestError does not. Log the cause as carefully as the request itself.
InvalidResponseError is not retryable: a response that fails the provider's schema will fail again. Model-generated output that fails validation stays a retryable InvalidOutputError.
Migration:AiError.HttpRequestDetails and Response.HttpRequestDetails are removed, and request is gone from AiError.HttpContext, NetworkError, and Response.ResponseMetadataPart; read error.reason.method / error.reason.url on a NetworkError. Exhaustive matches on AiErrorReason need an InvalidResponseError case, and consumers of serialized errors must accept it.
Reach for it when you need robust error handling — retry on rate limits, surface auth/quota problems, or translate provider failures into domain error types.
An optimization service for providers that support continuing from a prior response (e.g. OpenAI's Responses API previousResponseId). Records which prompt messages were sent with each response; a follow-up call can send only the new messages plus the prior response ID.
markParts(parts, responseId) records what produced a response; prepareUnsafe(prompt) returns an Option of { previousResponseId, prompt } — the untracked suffix after the last assistant turn — when the prefix is fully recognized. Provide it as a Layer; compatible providers use it transparently to shrink request payloads.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Chat, ResponseIdTracker } from "effect/ai"// Provide the tracker so a compatible provider reuses previousResponseId// instead of re-sending the entire HRBP conversation each turn.const withTracking = Effect.gen(function*() { const tracker = yield* ResponseIdTracker.make const chat = yield* Chat.fromPrompt("You are an HR policy assistant.") const provideTracker = Effect.provideService( ResponseIdTracker.ResponseIdTracker, tracker ) yield* chat.generateText({ prompt: "Summarize our promotion policy." }).pipe(provideTracker) return yield* chat.generateText({ prompt: "Now list the exceptions." }).pipe(provideTracker)})
Run the whole conversation with one compatible LanguageModel service. The same tracker instance must span the calls; constructing a tracker and returning it without providing ResponseIdTracker.ResponseIdTracker has no effect. OpenAI's WebSocket-mode integration (OpenAiClient.layerWebSocketMode / withWebSocketMode) installs a tracker; do not assume ordinary provider layers do.
Reach for it when running long multi-turn sessions against a provider that supports incremental continuation, to cut bandwidth and latency by not re-sending history.
The adapter enabling generateObject with Anthropic. toCodecAnthropic(schema) converts an Effect Schema.Codec into the JSON Schema subset Anthropic accepts and a matching codec to decode the model's reply back into the application type. The Anthropic provider wires this in automatically as its codecTransformer.
Schema rewriting is lossless where possible: tuples become numeric-key objects, records become [key, value] arrays, optional props become nullable required props (a prop that already accepts null keeps a single null branch), oneOf becomes anyOf. The returned codec decodes exactly the format it advertises, including optional records and tuples, and a root $ref is followed through chains of identified aliases. Unsupported shapes throw at conversion time. Call directly only when you need the raw JSON Schema for a custom Anthropic request.
Reach for it when you need Anthropic-compatible JSON Schema by hand. For normal use, call generateObject with the Anthropic provider — this runs automatically.
The OpenAI counterpart. toCodecOpenAI(schema) turns an Effect Schema.Codec into OpenAI's structured-output JSON Schema subset plus a decoding codec. The OpenAI provider uses it automatically for generateObject and for the parameters of strict tools (strict unless the tool sets Tool.Strict to false or the model config sets strictJsonSchema: false); non-strict tools are advertised with their standard JSON Schema, so records and optional properties keep their natural shape.
OpenAI-specific rewriting: allOf is flattened (OpenAI does not support it) and multiple regex filters are merged into one pattern. The same optional-property, optional record and tuple, and root-$ref rules as the Anthropic adapter apply. Unsupported schema kinds fail loudly at conversion. Use directly only to generate JSON Schema for a bespoke OpenAI call.
Reach for it when you need OpenAI-compatible JSON Schema directly. Otherwise, generateObject with the OpenAI provider already uses it.
Authenticates provider calls without a long-lived API key: the workload's own identity token (a projected Kubernetes service-account token, a cloud OIDC token) is exchanged at a token endpoint for a short-lived access token. WorkloadIdentity.make({ tokenUrl, identityToken, exchangeRequest, defaultExpiresIn? }) returns, in an Effect that requires an HttpClient, an HttpClient transform that sends Authorization: Bearer <access token> on every request. Use the core module only for a token endpoint the provider packages do not cover; for the providers below, use their module:
token-exchange grant with the inference scope at ${apiUrl}/oauth/token
Each provider module has make(options), whose transform goes in the client's transformClient option, and layer(options), which replaces the current HttpClient with an authenticated one. Leave the client's apiKey unset either way.
Lifetime.identityToken (an Effect of a Redacted string) runs again on every exchange, so a rotated token file is picked up. The access token is cached until 30 seconds before expiry or three quarters of its lifetime, whichever is later; concurrent requests share one exchange. There is no background refresh, the exchange is never retried, and a 401 drops only the token that request used, without replaying it. Anthropic accepts a token with a jti claim only once, so its identityToken must produce a fresh one each time.
Failures are HttpClientErrors (StatusCodeError, TransportError for transport failures and redirects, DecodeError for a bad token response, EncodeError for a failing or empty identity token), which the provider clients map to AiError. The literal identity token is redacted from errors; keep secrets out of failures raised by identityToken itself.
Scope the layer. The transform adds the access token to every request regardless of URL, so provide layer(...) only to the provider client, never to the application's shared HttpClient. The exchange uses the HttpClient captured at construction, must not follow redirects (redirects fail the exchange), and must not log request bodies. A token URL that is not https (or http on localhost, 127.0.0.1, ::1) is a defect.
WebSocket mode (OpenAI) resolves the access token when each socket connects and keeps it for the socket's lifetime.
Self-contained source · Type-checked
ts
import { AnthropicClient, AnthropicLanguageModel, AnthropicWorkloadIdentity } from "@effect/ai-anthropic"import { Effect, FileSystem, Layer, Redacted } from "effect"// Exchange the pod's projected token for an Anthropic access token.const AnthropicIdentity = AnthropicWorkloadIdentity.layer({ identityToken: Effect.gen(function*() { const fs = yield* FileSystem.FileSystem return Redacted.make(yield* fs.readFileString("/var/run/secrets/anthropic.com/token")) }), federationRuleId: "fdrl_...", organizationId: "00000000-0000-0000-0000-000000000000", serviceAccountId: "svac_..."})// No apiKey. Still requires an HttpClient and a FileSystem from the platform.const AnthropicLive = AnthropicLanguageModel.model("claude-opus-4-6").pipe( Layer.provide(AnthropicClient.layer({}).pipe(Layer.provide(AnthropicIdentity))))
Reach for it when a deployment's security policy forbids static provider keys and the platform can issue workload identity tokens.
Schemas for the Agent User Interaction (AG-UI) protocol, version AgUiSchema.protocolVersion ("1.0"): the RunAgentInput request body a frontend posts (threadId, runId, messages, tools, context, optional state, forwardedProps, resume), the conversation Message union (developer, system, user, assistant, tool, activity, reasoning), and the Event union an agent streams back (RUN_*, STEP_*, TEXT_MESSAGE_*, TOOL_CALL_*, REASONING_*, STATE_*, SUBAGENT_*, and more).
AgUiSchema.Message describes AG-UI wire messages. It does not replace Prompt.Message: convert a run's conversation with AgUi.toPrompt before calling a model.
Reach for it when decoding AG-UI input or emitting hand-written AG-UI events; most servers only touch it through AgUi and AgUiServer.
Pure conversions between effect/ai values and AG-UI; no I/O.
AgUi.toPrompt(input, { trustClientInstructions? }) turns a run's conversation into a Prompt: user and assistant text, assistant tool calls with parsed JSON arguments, tool messages as tool results (failed when they carry an error), and user media with inline data or a valid URL as file parts. Activity and reasoning messages, and tool messages that answer no earlier call, are dropped. By default system and developer messages and the input's context are dropped too, because the whole conversation comes from the browser; set trustClientInstructions: true only when the client is trusted to steer the model.
AgUi.fromStreamParts(stream) maps LanguageModel.streamText parts to events: each model round becomes a step (step-1, step-2, …), text and reasoning parts become message events, tool calls become TOOL_CALL_START / ARGS / END, final tool results become TOOL_CALL_RESULT (failed ones marked with { "effect/ai": { isFailure: true } } metadata). An error part is logged and becomes a RUN_ERROR with a generic message; preliminary results, approval requests, files, sources, and response metadata are dropped. It requires IdGenerator.
AgUi.withRunLifecycle({ threadId, runId }) wraps any event stream so the client sees RUN_STARTED first and exactly one RUN_FINISHED or RUN_ERROR last, closing any message, tool call, step, or subagent left open. A failing stream is logged, reported to the ErrorReporter, and ends with a RUN_ERROR without details; to send a specific error, emit a RUN_ERROR event instead of failing.
Reach for it when you serve AG-UI over a transport other than AgUiServer, or need to post-process the events.
Serves AG-UI runs over HTTP: clients POST a JSON RunAgentInput and read the run as Server-Sent Events (Cache-Control: no-cache, a keepalive comment every 15 seconds). An invalid body is answered with 400 before the stream opens.
AgUiServer.layerHttp({ path, agent }) or layerHttp({ path, run }) mounts one run handler on the current HttpRouter; it also needs the services HttpApiBuilder.layer needs (Etag.Generator, FileSystem, HttpPlatform, Path), which platform HTTP server layers provide. endpoint(name, path) with handler(run) or agentHandler(agent) adds the same route to an existing HttpApi.
AgUiServer.agent({ toolkit, system?, maxSteps? }) serves the current LanguageModel. The prompt is your system text followed by AgUi.toPrompt(input); the run's frontend tools are offered as client-executed tools next to your server toolkit, and a run whose tool names collide with a server tool gets 400. Rounds follow Chat.streamText with maxSteps (one round by default). RUN_FINISHED reports usage summed over every round and lists unanswered frontend calls as pendingToolCallIds; the frontend answers them with tool messages in its next run. Server tool handlers can read the run's input from AgUiServer.RunInput by declaring it in dependencies.
A run stream is wrapped with AgUi.withRunLifecycle, and an event that cannot be encoded as JSON becomes a sanitized RUN_ERROR.
Every field of the input — messages, tools, state, forwarded props — is client-controlled. Authenticate the route like any other HTTP endpoint, authorize inside server tool handlers, and bound maxSteps.
Self-contained source · Type-checked
ts
// @effect-diagnostics experimentalApiUsage:offimport { Effect, Schema } from "effect"import { AgUiServer, Tool, Toolkit } from "effect/ai"const LookupBand = Tool.make("LookupBand", { description: "Return the salary band midpoint for a job level", parameters: Schema.Struct({ level: Schema.Int }), success: Schema.Struct({ mid: Schema.Finite })})const CompTools = Toolkit.make(LookupBand)// POST /agent streams AG-UI events; frontend tools from the request are client-executed.export const AgentRoute = AgUiServer.layerHttp({ path: "/agent", agent: AgUiServer.agent({ toolkit: CompTools, system: "You are a compensation assistant. Use LookupBand for every band figure.", maxSteps: 4 })})// Provide with a LanguageModel, an HttpRouter, and the platform's HTTP services.export const CompToolsLive = CompTools.toLayer({ LookupBand: ({ level }) => Effect.succeed({ mid: 150_000 + level * 10_000 })})
Reach for it when a browser frontend that speaks AG-UI should drive an Effect agent with streaming text, tool calls, and frontend tools.
The modules above make a model call typed; they do not make it safe. These rules are the short form of Building a Production AI Capability, which works through each with code.
Concern
Rule
Mechanism on this page
Trust
Treat user text, retrieved text, prior model output, tool arguments, and tool results as untrusted; take actor, tenant, approval, idempotency key, and policy version only from trusted request context, never from model output.
Handler closes over trusted services; Schemas validate shape, not authority.
Tool execution
Bound tool concurrency and keep mutations behind your own gate.
Every agent loop has a turn limit and a typed exhaustion error.
Bounded for loop around Chat.generateText.
Budgets
Every limit is finite and checked before dispatch: estimate prompt tokens and reserve worst-case output before the call; treat returned usage as reconciliation.
Tokenizer, response.usage, Effect.timeout.
Retries
Classify by reason, bound the schedule, and stop once output or a side effect exists.
Testing checklist. Provide a scripted LanguageModel built with LanguageModel.make (it can record prompts and replay tool calls, failures, or a stream that never ends) and assert: a bounded multi-turn run succeeds; an unauthorized or unapproved call reaches zero handlers; a repeated call id produces one side effect; each budget fails at its exact edge; malformed tool arguments and unknown tool names fail closed; an interrupted stream leaves a recorded incomplete turn and runs its finalizers. Fakes prove policy, recorded HTTP fixtures prove adapter parsing, and a small separately authorized live suite proves only that the remote API still behaves as recorded.
Primitives live in effect/ai; concrete providers ship as satellite packages. Each exposes a Client.layerConfig(...) that reads its credentials from Config (requires an HttpClient) and one or more .model(name) constructors (each a Model Layer). Anthropic, OpenAI, and OpenRouter clients can also authenticate with workload identity instead of an API key. Every language-model provider produces the same LanguageModel service, and every decision provider the same DecisionModel service; switching providers is a one-line Layer change.
Provider upgrade checks. OpenAI treats unknown model names as reasoning models by default (fine-tunes follow their base model), selects the developer role, and merges explicit includes with automatic encrypted-reasoning includes. Set reasoningModel: false for a custom deployment that needs the system role and no automatic reasoning include. Responses streaming accepts a [DONE] sentinel; find_in_page web-search actions can omit both url and pattern, so do not assume either field exists. The regenerated Generated surface removes unreferenced Realtime WebSocket exports, renames multipart bodies to *Multipart / *FormData, and gives maps/free-form objects record types; recompile direct generated-client users rather than treating this patch upgrade as type-neutral. Anthropic fallback blocks survive in metadata.anthropic.fallback, with fallback model attribution in usage iterations. Cloudflare decisions support inline bytes, base64, and data URLs, but reject remote image URLs before dispatch. Truncation is reported as finishReason: "length" when OpenAI stops at max_output_tokens or Anthropic at model_context_window_exceeded. Every provider parses Retry-After as whole non-negative seconds or an HTTP date, so retryAfter is never negative or infinite. OpenAI-compatible and OpenRouter refusals finish with reason "content-filter" and carry the model's explanation as refusal in the finish part's provider metadata (metadata["openai-compat"] / metadata.openrouter); a refusal is not an AiError, so check the finish reason before trusting the text.
pkg @effect/ai-openai — OpenAI Responses API. OpenAiClient.layerConfig, OpenAiLanguageModel.model("gpt-5.2"), OpenAiEmbeddingModel.model(name, { dimensions }), provider-defined tools via OpenAiTool (e.g. OpenAiTool.WebSearch), and OpenAiTelemetry. A web search search action's sources can be URL sources ({ type: "url", url }) or API sources ({ type: "api", name }, such as oai-weather), so narrow each source on type before reading url or name; action itself is optional on a web-search call or result, and an incomplete call decodes as a failed tool result instead of failing to decode. A dynamic tool backed by raw JSON Schema keeps its tool-call parameters intact. Prompt caching can be steered explicitly: set options: { openai: { promptCacheBreakpoint: { mode: "explicit" } } } on a system message or a text part to mark the end of a reusable prefix (the provider documents this for GPT-5.6 or later and may reject it on earlier models). In websocket mode, a turn that gets back previous_response_not_found is retried once with the full prompt, keeping the socket open if it is still open, and a failing transformClient (for example a workload-identity exchange) fails the turn with an AiError rather than a defect.
pkg @effect/ai-anthropic — Anthropic Messages API. AnthropicClient.layerConfig, AnthropicLanguageModel.model("claude-opus-4-6"), AnthropicTool, and AnthropicTelemetry. Structured output bridged automatically through AnthropicStructuredOutput. Multiple system instructions are preserved across a conversation; the optional LanguageModel.supportsSystemMessagesInHistory flag on the provider controls whether mid-conversation system messages are forwarded (Anthropic sets this to true). Cached tokens are included in gen_ai.usage.input_tokens and reported separately as gen_ai.usage.cache_read.input_tokens and gen_ai.usage.cache_write.input_tokens; the former per-response cacheCreationInputTokens and cacheReadInputTokens options were removed in 4.0.2. A malformed 4xx response from an Anthropic-compatible gateway is mapped to the matching AiError reason by HTTP status (including a 429's retry delay) instead of failing as InvalidOutputError; a direct AnthropicClient.client.betaMessagesPost call fails with HttpClientError rather than SchemaError for these responses. A message response that omits usage.inference_geo — as some Anthropic-compatible gateways do — still decodes. output_config.effort accepts "low" through "xhigh" and "max". For a large catalog, annotate user tools with .annotate(AnthropicTool.DeferLoading, true) next to AnthropicTool.ToolSearchRegex_20251119() or ToolSearchBM25_20251119(), so a tool is loaded only when the model searches for it; Anthropic requires at least one non-deferred tool (normally the search tool), and the annotation has no effect on provider-defined tools. The TextEditor_20250429 and TextEditor_20250728 tools decode insert commands with TextEditorInsertTextCommand (insert_text); the earlier versions keep TextEditorInsertCommand (new_str). With native structured output, a generateObject turn that calls tools keeps its "tool-calls" finish reason.
Migration:AnthropicTool.ToolSearchRegexParameters has pattern (plus an optional limit) instead of query; rename the field in code that builds or reads regex tool-search inputs.
pkg @effect/ai-amazon-bedrock — Amazon Bedrock Runtime through the Converse and ConverseStream APIs, with no runtime dependency beyond effect. AmazonBedrockClient.layerConfig() reads AWS_REGION (default us-east-1) and either AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (plus AWS_SESSION_TOKEN for temporary keys), signed with SigV4, or a Bedrock API key in AWS_BEARER_TOKEN_BEDROCK, sent as a bearer token; AmazonBedrockClient.layer({ region, apiKey | credentials | accessKeyId + secretAccessKey }) takes them explicitly, in that order of precedence, and without any of them every request fails with an AuthenticationError of kind MissingKey. credentials is an Effect resolved before every request, where an AWS SDK provider chain plugs in; build the layer in Layer.unwrap around Effect.cachedWithTTL so it is not resolved per call. Besides an HttpClient, the client requires the Digest and Mac services of effect/crypto for signing (Digest.layerWebCrypto plus Mac.layerWebCrypto, which itself needs SecureRandom.layerWebCrypto, or one platform layer such as NodeCrypto.layer), even with an API key. AmazonBedrockLanguageModel.model(modelId, config?) or .layer({ model, config }) provides LanguageModel with provider name "amazon-bedrock"; AmazonBedrockLanguageModel.withConfigOverride sets per-call Converse fields such as inferenceConfig and additionalModelRequestFields (extended thinking). generateObject uses a forced tool by default; set structuredOutputs: true in the config to use Converse's native outputConfig.textFormat on models that support it. Prompt caching is opted into per message or part with options: { "amazon-bedrock": { cachePoint: { type: "default" } } }; reasoning blocks round-trip with their signature, and image and document file parts are sent as bytes. Bedrock exceptions map to AiError reasons, and a stream fails on an exception frame such as throttlingException. AmazonBedrockClient's client member is the authenticated HttpClient for Bedrock Runtime operations the service does not model; AmazonBedrockSchema holds the Converse wire schemas.
pkg @effect/ai-openrouter — OpenRouter's unified gateway to many models. OpenRouterClient.layerConfig (supports siteReferrer/siteTitle for attribution) and OpenRouterLanguageModel.model(name) — one key, hundreds of models. Its model is typed and reported with provider name "openrouter" (it was "openai"; update explicit AiModel.Model<"openai", ...> annotations or provider comparisons). It also offers OpenRouterDecisionModel.model(name), a DecisionModel over OpenRouter's alpha Decisions API; it requires full label and level distributions, and accepts only a string, object, or array as the encoded input (other JSON values fail with InvalidUserInputError). Streams that end before a tool call's parameters are complete (for example at the token limit) fail with ToolParameterValidationError instead of dropping the call, empty trailing call fragments are ignored, and a response with tool calls but no finish reason finishes with "tool-calls". The regenerated Generated client follows the current OpenRouter specification: some intermediate schema exports are gone (derive their types from the request or response schema that contains them), and hand-built fixtures need newly required fields.
pkg @effect/ai-typesafe — A DecisionModel-only provider for TypeSafe's System One API; it has no LanguageModel. TypeSafeClient.layerConfig() reads TYPESAFE_API_KEY by default (pass apiKey / apiUrl Configs to override), and TypeSafeDecisionModel.model("jev-latest") provides the service; versioned identifiers such as "jev-1.13.0" also work. The client does not retry, and a rate-limit error carries the provider's retry delay when one is sent, so apply the retry rules yourself.
pkg @effect/ai-openai-compat — Any OpenAI-compatible endpoint (local LLMs, Together, Groq, vLLM…). Same OpenAiClient/OpenAiLanguageModel/OpenAiEmbeddingModel API — point apiUrl at your server. Tool toModelOutput files are sent as text placeholders, and concurrent embed calls with different configuration overrides or client transforms are batched separately. System instructions use the developer role only for OpenAI reasoning model ids (o plus a digit such as o3, gpt-5*, codex-*, computer-use*); everything else, including provider-prefixed ids such as openai/gpt-oss-120b, gets system. PDF file parts are sent as Chat Completions file content parts from bytes, base64, data URLs, or a configured file ID; a PDF URL fails with InvalidUserInputError before dispatch. Optional response fields that a server sends as null decode, and the affected OpenAiClient response types include null.
Its provider augmentation key is "openai-compat", not "openai": use it for error metadata, prompt part options, and response part metadata (including extraContent thought signatures). Migrate custom code that reads or writes those provider-specific fields; the package no longer shares augmentation keys with @effect/ai-openai. Chat Completions does not support the removed store / conversation options. Assistant reasoning is replayed together with text and tool calls, including parts that carry item ids.
OpenAI decisions — OpenAiDecisionModel.model("gpt-6-luna") from @effect/ai-openai provides DecisionModel over the Decisions API; OpenAiClient.createDecisions is the lower-level call. Refusals are reported per decision: decide fails with ContentPolicyError, and decideSettled returns a Refused outcome for just that decision (OpenAiContentPolicyMetadata and metadata.openai.refusedDecisions are gone). Images are labelled with their reference. Images must be inline bytes, base64, or data URLs; remote image URLs fail with InvalidUserInputError before dispatch. The provider tolerates two-decimal probability rounding.
pkg @effect/ai-cloudflare — Cloudflare Workers AI decision provider. CloudflareClient.layerConfig() reads CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN; CloudflareDecisionModel.layer({ model: "clef-flash" }) (or "clef" for the larger model) provides DecisionModel. No LanguageModel — decisions only. Limits: 64 questions per request, 2–255 classification choices, 2–10 rating levels. Rate-limit errors carry Retry-After when provided; the client validates answers and rescales small probability drift from four-decimal rounding. Set gatewayId (or CLOUDFLARE_AI_GATEWAY_ID) to route through Cloudflare AI Gateway via the cf-aig-gateway-id header.
Self-contained source · Type-checked
ts
// Swapping providers is a one-line change at the edge — comp logic is untouched.import { Config, Layer } from "effect"import { FetchHttpClient } from "effect/http"import { AmazonBedrockClient, AmazonBedrockLanguageModel } from "@effect/ai-amazon-bedrock"import { AnthropicClient, AnthropicLanguageModel } from "@effect/ai-anthropic"import { OpenRouterClient, OpenRouterLanguageModel } from "@effect/ai-openrouter"import { Digest, Mac, SecureRandom } from "effect/crypto"import { TypeSafeClient, TypeSafeDecisionModel } from "@effect/ai-typesafe"const AnthropicLive = AnthropicLanguageModel.model("claude-opus-4-6").pipe( Layer.provide( AnthropicClient.layerConfig({ apiKey: Config.Redacted("ANTHROPIC_API_KEY") }) .pipe(Layer.provide(FetchHttpClient.layer)) ))const OpenRouterLive = OpenRouterLanguageModel.model("openai/gpt-5.2").pipe( Layer.provide( OpenRouterClient.layerConfig({ apiKey: Config.Redacted("OPENROUTER_API_KEY"), siteTitle: Config.succeed("Comp Planner") }).pipe(Layer.provide(FetchHttpClient.layer)) ))// Bedrock reads AWS_REGION plus AWS keys or AWS_BEARER_TOKEN_BEDROCK, and signs// requests with the effect/crypto Digest and Mac services.const BedrockLive = AmazonBedrockLanguageModel.model("us.anthropic.claude-sonnet-4-5-20250929-v1:0").pipe( Layer.provide(AmazonBedrockClient.layerConfig()), Layer.provide([ FetchHttpClient.layer, Digest.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)) ]))// A DecisionModel provider is wired the same way; it reads TYPESAFE_API_KEY.const TypeSafeDecisionsLive = TypeSafeDecisionModel.model("jev-latest").pipe( Layer.provide(TypeSafeClient.layerConfig().pipe(Layer.provide(FetchHttpClient.layer))))
Note: Configure a provider client from Config → write comp logic against LanguageModel → call generateText for a review summary, generateObject with a Schema for a validated RaiseRecommendation, and pass a Toolkit (e.g. LookupCompBand) for tool calls → provide a concrete .model(...) Layer at the edge. Same four moves whether you're on OpenAI, Anthropic, Amazon Bedrock, OpenRouter, or a local model.
effect/ai ships a Model Context Protocol implementation: the wire schemas, the protocol adapters for every supported MCP revision, McpServer, which exposes your Effect services as tools, resources, prompts, and Agent Skills over stdio or streamable HTTP, an experimental McpClient for calling other MCP servers, and McpTest for testing a server in memory. Tools reuse the same Tool and Toolkit definitions as AI & Language Models. For an end-to-end walkthrough, read the MCP deep dive.
The complete Model Context Protocol (MCP) wire format as Effect Schemas and Rpc definitions: requests/results, resources and resource templates, prompts, completions, capabilities, and JSON-RPC error codes. The typed contract McpServer is built on.
Commonly used helpers: McpSchema.param(name, schema) declares typed parameters inside resource URI templates; Role, Annotations, and error types are also referenced directly. The heavier protocol machinery (Initialize, ListResources, CallTool, notifications) is consumed by the server runtime and by McpClient.
The Skills extension adds McpSchema.Skill (a skills/list / skills/get entry: the SKILL.md URI, its frontmatter, and either a manifest of SkillResource entries — uri, sha256:digest, size — or "dynamic") and McpSchema.SkillFrontmatter, the Agent Skills frontmatter fields (name, description, optional license, compatibility, string-valued metadata, allowed-tools, plus any extra keys).
JSON-valued fields — _meta, structuredContent, capability records, and similar — are checked only one level deep when decoding and are typed as unknown or Readonly<Record<string, unknown>>, so narrow them before use. McpServer still rejects a tool result that is not JSON when it serializes a 2026-07-28 response. JSON-RPC errors on the wire carry only code, message, and optional data.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { McpSchema } from "effect/ai"// A typed URI-template parameter — e.g. the employee id in an HRIS resource.const employeeIdParam = McpSchema.param("employeeId", Schema.String)// Error codes and typed errors are provided too, e.g. for custom handlers.McpSchema.INVALID_PARAMS_ERROR_CODE // -32602
Reach for it when building or extending an MCP server and needing the protocol's typed building blocks — especially param for resource/prompt templates.
The versioned protocol adapter registry used by McpServer. It ships five adapters — McpProtocol.v2024_11_05, v2025_03_26, v2025_06_18, v2025_11_25, and v2026_07_28 — each binding the matching client/server RPC groups and transport rules. The 2025-11-25 adapter adds sampling with tools, form- and URL-based elicitation (including identified object schemas), and McpSchema.Icon metadata (source URI, MIME type, sizes, light/dark theme) for server info, resources, resource templates, prompts, and tools. Server transports require a non-empty protocols list so negotiation is explicit rather than silently assuming whichever MCP revision a client sends.
2026-07-28 is stateless. It drops initialize and protocol-level sessions: each request carries its own protocol version and client metadata, a client can call server/discover to read the server's identity, capabilities, and instructions, and change notifications are delivered through subscriptions/listen when the transport can push. It works over both stdio and Streamable HTTP, and it can share a protocols list with the session-based revisions, so one server can serve old and new clients; a server accepts at most one stateless revision. Adapters now describe their transport rules through a runtime descriptor (McpProtocol.StatefulRuntimeDescriptor / StatelessRuntimeDescriptor) instead of the former transport field, which matters only if you wrote your own adapter.
The 2025-06-18 adapter rejects JSON-RPC batches on its transport. The MCP-Protocol-Version header is validated only on requests after initialization: an initialize request negotiates from the version offered in its body and reports the selected version in the response, so a fresh client whose default header is not registered is no longer rejected with 400 before negotiation can happen. List every adapter you intentionally support; initialization selects the requested version and the server uses the first adapter as its fallback/default. A stdio server answers a ping sent before initialize with an empty result rather than rejecting it, even when a stateless protocol such as 2026-07-28 is listed first among several protocols.
Streamable HTTP is strict at the boundary. If a request carries Origin, layerHttp returns 403 unless that exact origin appears in allowedOrigins. POST requires Content-Type: application/json (otherwise 415) and an Accept header that includes both application/json and text/event-stream with positive quality (otherwise 406).
Reach for it when constructing an MCP transport or deciding which protocol revisions a server is willing to negotiate.
A batteries-included framework for building MCP servers — the protocol that lets editors and AI clients (Claude Desktop, IDEs) discover tools, resources, and prompts. Handles JSON-RPC plumbing; capabilities are registered as Layers and a transport is chosen.
McpServer.toolkit(toolkit) exposes a Toolkit as MCP tools; McpServer.resource\uri/${param}`({...})exposes resources/templates (with auto-completion);McpServer.prompt({...})exposes parameterized prompts, with an optional human-readabletitlebeside thename(also accepted byregisterPrompt). Each of these is a registration Layer that requires the McpServerservice. Merge them and pass them to the transport as itsregistrationsoption, so they are registered before the server reads its first request. Transports:layerStdio(desktop clients),layerHttp(mount on anHttpRouter; pass allowSessionTermination: trueto enable DELETE on the session path, which ends the session and interrupts its active requests — later requests on that session id return404), and layerover a caller-providedRpcServer.Protocol. Every server constructor (layer, layerStdio, layerHttp, run) accepts an optional instructionsstring, returned in the initialization and discovery responses to tell a client how to use the server. Launch withLayer.launch+NodeRuntime.runMain`.
Migration: In 4.0 the transport was provided to the registrations (Registrations.pipe(Layer.provide(McpServer.layerStdio({ ... })))). Pass them as registrations instead. Services that tool, resource, and prompt handlers read are now request-level, and only layerHttp / layerHttpRequestScoped called with registrations turn them into HttpRouter requirements; see Request-level dependencies.
Self-contained source · Type-checked
ts
import { Effect, Layer, Logger, Schema } from "effect"import { NodeRuntime, NodeStdio } from "@effect/platform-node"import { McpProtocol, McpSchema, McpServer } from "effect/ai"const employeeIdParam = McpSchema.param("employeeId", Schema.String)// A resource template: hris://employee/<employeeId>, with id completion.const EmployeeCard = McpServer.resource`hris://employee/${employeeIdParam}`({ name: "Employee Card", completion: { employeeId: (_) => Effect.succeed(["emp-4821", "emp-5099"]) }, content: Effect.fn(function*(_uri, employeeId) { return `Employee ${employeeId}: level 4, base 185000, rating "exceeds"` })})// A parameterized prompt the client can invoke.const RaisePrompt = McpServer.prompt({ name: "RaiseRationale", title: "Raise rationale", description: "Draft a within-band raise rationale for an employee", parameters: { employeeId: Schema.String }, completion: { employeeId: () => Effect.succeed(["emp-4821", "emp-5099"]) }, content: ({ employeeId }) => Effect.succeed(`Write a merit-increase rationale for ${employeeId}, staying within band.`)})// Pass the merged registrations to the stdio server, and launch.const ServerLayer = McpServer.layerStdio({ name: "Comp Server", version: "1.0.0", instructions: "Read employee cards before drafting; never propose an out-of-band raise.", protocols: [McpProtocol.v2025_06_18], registrations: Layer.mergeAll(EmployeeCard, RaisePrompt)}).pipe( Layer.provide(NodeStdio.layer), Layer.provide(Layer.succeed(Logger.LogToStderr)(true)))Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)
Tip: Define a Toolkit once — say your CompToolkit with LookupCompBand — and you can both call it from a LanguageModeland expose it to external clients via McpServer.toolkit(CompToolkit). Same handlers, two surfaces.
What an MCP client sees from a toolkit tool.
Handler outcome
Wire result
Logged and reported to ErrorReporter
Success
isError: false; the result's JSON encoding (the same encoding the advertised outputSchema describes, so a Schema.Date is an ISO string) as JSON text, plus structuredContentonly when it is a JSON object (never null or an array, which MCP forbids there). A result that is undefined, such as a Schema.Void tool's, has empty content and no structuredContent
no
Arguments fail the parameter schema (a Tool.Strict tool also rejects undeclared properties)
Protocols 2024-11-05, 2025-03-26, 2025-06-18: a JSON-RPC InvalidParams error listing every missing or invalid field, and every unknown key for a strict tool, in one response. Protocols 2025-11-25 and 2026-07-28: an isError: true result carrying that same combined validation message, so the calling model can correct itself
no
Declared failure, failureMode: "error", value is an Error instance
isError: true with that error's message — an empty message falls back to the failure's encoded value, so a bare tagged error is still legible
no
Declared failure, failureMode: "error", any other value
isError: true with the failure's JSON encoding (its schema's JSON codec, so bigint, Map, or Option values survive) as text
no
Declared failure, failureMode: "return"
isError: true with the failure payload's JSON encoding as text
no
An undeclared failure or AiError, a defect, or a result that fails its success schema or cannot be serialized
Protocols 2025-11-25 and 2026-07-28: isError: true with a fixed internal-error message. Earlier protocols: a JSON-RPC -32603 Internal error (not -32602 Invalid params). Either way, details never reach the client
yes
A failed call never carries structuredContent. Declared failures are part of the tool's contract, so the server sends them to the client and does not log or report them; everything else is logged at error level and handed to the configured ErrorReporters, so provide one when you need alerting on tool faults (see Observability). Both failure modes produce isError: true: choose "error" when the client should read a short message, and "return" when it should receive the structured failure payload. Either way the declared failure is visible to the client, so keep secrets and internal detail out of it.
Arguments are decoded with the parameter schema's JSON codec, so a Schema.Date parameter accepts the ISO string a client sends, and the advertised inputSchema describes that encoding. Tool input schemas follow Tool.Strict: a strict tool advertises additionalProperties: false and the server rejects extra arguments, while a non-strict tool advertises additionalProperties: true and ignores them. A top-level $ref in a parameter schema is inlined (following chains of identified aliases), and an identified success output schema is likewise normalized to an object root, because MCP requires an object at the root. Calling McpServer.toolkit with a tool whose parameter schema is not an object schema fails fast with a clear, named error instead of a dispatch-time failure. In a protocol that omits string structuredContent, a result whose single text block is already the exact JSON encoding of that string is returned as plain text rather than duplicated.
Server identity can carry icons.layer, layerStdio, layerHttp, and run accept icons: ReadonlyArray<McpSchema.Icon> (src, optional mimeType, sizes, theme). The McpSchema.Resource, ResourceTemplate, Prompt, and Tool schemas have the same optional field for entries registered through the lower-level McpServer registry service.
Resource reads report their MIME type. A resource registered with mimeType whose handler returns a string or Uint8Array carries that mimeType in its resources/read contents, not only in resources/list, so MCP Apps hosts can render text/html;profile=mcp-app UI resources.
Lists are a single page.tools/list, resources/list, resources/templates/list, and prompts/list return everything in one page and never issue a cursor; a request that supplies a cursor (even "") fails with InvalidParams.
Prompt and resource callbacks receive decoded values.McpServer.prompt / registerPrompt pass content the decoded type of each parameters schema, and resource templates resolve over both stdio and Streamable HTTP.
A non-recursive tool schema root is sent once.tools/list inlines it without also publishing it under $defs, so a custom toJsonSchema$ref into the root's own definition (such as #/$defs/Note/properties/title when Note is the tool schema) no longer resolves; point such references at the inline schema instead.
Each layerStdio builds its own protocol. Several stdio servers can sit in one layer graph as long as each is given its own Stdio; they still share the memoized McpServer registry. When stdin closes, the server lets accepted requests finish, ends open subscriptions/listen streams, and exits with code 0 under the default teardown (as NodeRuntime.runMain uses) rather than the 130 of an external interrupt.
Effect RPC control messages are off. MCP servers use the JSON-RPC serialization with controlMessages: false, so @effect/rpc/* notifications from an MCP client neither stop a stdio server nor make it write @effect/rpc/Pong to stdout.
Tool annotation titles survive tools/list. On the 2025-06-18 and 2025-11-25 protocol revisions, a tool's annotation title is reported in tools/list responses alongside its top-level title and behavioral hints.
Server extensions are advertised, not implemented.layer, layerStdio, layerHttp, and run accept extensions, a record keyed vendor/name with JSON settings, reported in the server capabilities of initialize and server/discover. 2026-07-28 discovery lists only object-valued settings. Behavior behind an extension is your code; Effect ships no extension helpers.
Progress belongs to its request. A progress notification queued by a handler is dropped once its request completes, is cancelled, or its client disconnects, so a late progress never reaches a client after the result; progress sent outside any request is delivered as before.
Stateful clients only hear about changes after they initialize. List-change notifications for registrations made before a session client's initialize was handled are not sent to it, over stdio, HTTP sessions, and custom transports.
Cache hints for stateless clients.layer, layerStdio, layerHttp, and layerHttpRequestScoped accept cacheHints, which set how long 2026-07-28 clients may treat discovery and list results as fresh: cacheHints: { tools: { ttl: "1 minute", cacheScope: "private" } }. The keys are discover, tools, resources, resourceTemplates, prompts, and skills (for skills/list, skills/get, and resources/directory/read); omitted keys and every resources/read result keep { ttlMs: 0, cacheScope: "private" }, and earlier revisions ignore the option. ttl is any Duration.Input, sent as whole milliseconds rounded down; a non-finite or negative ttl, or a scope other than "private", fails the Layer with IllegalArgumentError. These are hints only — the server caches nothing and still applies visibility and per-call checks — but a positive ttl lets a client keep showing a list after registrations or per-request visibility change, and a client shared between users can reuse one user's list for another.
Use McpServer.layerHttpRequestScoped on serverless hosts where execution must belong to an HTTP request. Each POST owns its server fibers, timers, and queue consumers until its response body completes. It accepts only stateless adapters such as McpProtocol.v2026_07_28; an untyped session-era adapter fails Layer construction with IllegalArgumentError. Tools, resources, prompts, completions, InputRequired round trips, and the request's own progress/log notifications work. Sessions, legacy reverse requests (elicit), broadcast list changes, subscriptions, and DELETE session termination do not: discovery reports listChanged: false, subscriptions/listen is method-not-found, and DELETE returns 405. The same origin and media-type admission rules as layerHttp apply. This is an execution-lifetime boundary, not an authorization or request-size limit.
Keep layerHttp for long-lived hosts with session-era clients or subscriptions. It shares one scoped server across POSTs; allowSubscriptions: false disables stateless subscriptions without disabling request-local progress/logs or legacy protocols. Request-scoped configuration intentionally has neither allowSubscriptions nor allowSessionTermination.
Resource templates require their parameter schemas' decoding services, plus the encoding services of parameters that have a completion handler, when they are registered; prompts likewise require parameter decoding services and the encoding services of completed parameters. Provide those schema services when composing the registration Layer. A schema that transforms using a service does not become service-free merely because it is embedded in a URI template or prompt. Services that the content and completion handlers themselves read are request-level instead (next section).
Request-level dependencies, middleware, and visibility
Some services exist only per request — above all, the caller. Every service a handler reads is a request-level dependency: a tool declares it with dependencies (or Tool.addDependency), and resource, prompt, and completion handlers declare it simply by reading it. The registration Layer carries it as an McpServer.McpRequest<"Requires", S> requirement, and only MCP middleware or the transport can discharge that marker. Layer.provide(Layer.succeed(S, value)) does not, so a construction-time value can never stand in for the per-request one by accident; an undischarged marker is a compile error. Parameter-decoding and result-encoding services stay ordinary registration-time requirements.
The transport discharges what it supplies (McpServer.ProvidedServices): every transport supplies Scope, the HTTP transports supply HttpServerRequest, and McpServerClient is supplied only when every adapter in a literal protocols tuple is session-based. Mixing in v2026_07_28, or widening the tuple to ProtocolAdapter[], leaves McpServerClient for middleware to provide.
layerHttp and layerHttpRequestScoped turn every other marker into an HttpRouter.Request requirement, so an HttpRouter.middleware<{ provides: Principal }> provided to the transport Layer satisfies a tool that declares dependencies: [Principal] — and its own 401 responses keep working. On stdio and custom transports, use MCP middleware.
McpServer.middleware<{ provides: S }>()(fn) creates MCP middleware: fn(effect, { method, target, payload, requestContext, headers, sessionId }) wraps each tools/call, resources/read, prompts/get, and completion/complete, and provides S with Effect.provideService. headers are empty on stdio, custom transports, and in-process calls. Provide mw.layer to the registrations it should wrap, or use mw.layerGlobal (or { global: true }) for every request on the server; global middleware runs outside local middleware, and middleware provided both ways runs once. A middleware that itself needs S per request gets it from one combined outside it: a.combine(b) runs b outside a. A low-level McpServer.McpServer.addTool registration only sees local middleware when it passes services, so wrap such tools with global middleware.
Skills are covered too. Middleware also wraps skills/get (its target is the skill's SKILL.md URI); skills/list and resources/directory/read are list requests, checked once per skill. A hidden skill is left out of both lists and skills/get fails as not registered; its files are ordinary resources under their own URIs.
Middleware failures are protocol errors. Fail with an McpSchema.McpErrorBase value — a Schema.Error spreading McpErrorBase.fields, typically with a code from -32000 to -32019 — and the client receives a JSON-RPC error with that code, message, and data, never a tool result. Any numeric code is sent as is, so pick custom codes from the implementation-defined range. Defects are logged, reported to the ErrorReporter, and sent as InternalError. Middleware never runs for initialize.
Request services win. A service a registration captured with Layer.provide is only a default that the request's own context overrides, on every transport. To read construction-time services in a resource or prompt, read them in Layer.unwrap and close over them.
McpServer.visibility(check) is middleware whose check returns a boolean per request: a hidden registration is left out of list results, and calling, reading, getting, or completing it fails exactly as if it were not registered — on 2026-07-28 HTTP a hidden tool is reported as unknown before its x-mcp-header parameters are checked, so a header mismatch cannot reveal it. On list requests the middleware outside the innermost visibility runs once per registration, with an undefinedpayload, and a failing check fails the whole list rather than hiding anything. No list_changed notification is sent when visibility changes. Unlike EnabledWhen, visibility runs your middleware and so can depend on the authenticated caller.
McpSchema.McpRequestContext is provided to every tool handler, resource content, and prompt content: clientId, protocolVersion, clientCapabilities, optional clientInfo and requestMetadata, and, on a continued 2026-07-28 call, inputResponses and requestState. Read it with yield* McpSchema.McpRequestContext or McpSchema.McpRequestContext.useSync(f); McpServer.clientCapabilities reads just the capabilities. A toolkit tool declares it with dependencies: [McpSchema.McpRequestContext], and McpServer.toolkit leaves it out of the Layer's requirements because each call supplies it. Everything in it is self-reported by the client.
McpSchema.McpServerClient exists only for initialized session-era clients. It is what server-to-client requests need; 2026-07-28 requests never have it.
McpSchema.EnabledWhen is an annotation holding a predicate over { protocolVersion, capabilities, clientInfo }: .annotate(McpSchema.EnabledWhen, predicate) on a Tool, or annotations: Context.make(McpSchema.EnabledWhen, predicate) on addTool, prompt, and registerResource. A false predicate removes the entry from that client's list, and a direct call fails as not found. It trims the catalog per client; it does not authorize.
McpServer.elicit({ message, schema }) returns Effect<S["Type"], McpSchema.ElicitationDeclined, McpServerClient | S["DecodingServices"]>. It sends a form-mode elicitation/create built from schema to the current session client, then decodes the accepted content with schema. A decline fails with ElicitationDeclined, and so does a client or revision without form elicitation (the reason is in cause); a cancel interrupts the handler. Session eras only, so hide the tool from 2026-07-28 clients. A tool that declares McpServerClient compiles into a server only when the transport's literal protocols are all session-based, because only then does the transport supply it; with a stateless adapter in the list, read the client with Effect.serviceOption(McpSchema.McpServerClient) instead, as the deep dive's dual-era gate does:
McpServer.McpServer.addTool and McpSchema.InputRequired are the stateless way to ask for input. A toolkit handler must return the tool's success type, so a tool that pauses for input is registered on the McpServer.McpServer service with a hand-written McpSchema.Tool descriptor (inputSchema must have an object root). Its handle(payload) receives the raw arguments and returns CallToolResult | InputRequired, failing only with McpSchema.InternalError | McpSchema.InvalidParams and requiring only McpRequestContext. new McpSchema.InputRequired({ inputRequests, requestState }) needs at least one of the two; each keyed request is elicitation/create, sampling/createMessage, or roots/list. The client calls again with the same arguments, the answers in inputResponses under your keys, and requestState echoed unchanged. A missing client capability fails the call with protocol error -32021 and data.requiredCapabilities; a session-era client that receives InputRequired gets a protocol error; InvalidParams on a continued call becomes JSON-RPC -32602. requestState returns from the client, so seal it (HMAC, expiry, caller binding) before trusting it.
Authenticate by wrapping the HTTP layer.layerHttp does not authenticate. Provide typed route middleware to it — McpServer.layerHttp({ ..., registrations }).pipe(Layer.provide(BearerAuth.layer)), where BearerAuth = HttpRouter.middleware<{ provides: Principal }>()(...) — and its routes are wrapped, because router.add applies the route middleware found where a route is registered; routes merged beside it (a public metadata route) are not. Declare Principal as a tool dependency (or read it in a resource or prompt handler): layerHttp turns that request-level requirement into the HttpRouter requirement BearerAuth.layer satisfies, so a composition that forgets the middleware does not compile. A low-level addTool handler may require only McpRequestContext, so it reads the principal with Effect.serviceOption and fails closed.
McpServer.skill({ uri, files, annotations? }) (a registration Layer) and McpServer.registerSkill(options) (its Effect form) publish an Agent Skill under the MCP Skills extension (SEP-2640). uri addresses the skill's SKILL.md, normally skill://<path>/SKILL.md; its last directory segment is the skill's name and must equal the frontmatter name. files (McpServer.SkillOptions) maps paths relative to the skill root to McpServer.SkillFile values — a string, a Uint8Array, or { content, mimeType? } (otherwise the MIME type comes from the extension) — and must include SKILL.md.
What clients get. Every file is a resource served verbatim; the bytes are copied at registration. skills/list and skills/get return each skill with its parsed frontmatter and a manifest of every file's SHA-256 digest and size, and resources/directory/read browses the skill namespace. The server declares the io.modelcontextprotocol/skills extension once a skill is registered, on every supported protocol revision.
Validation at build time. The Layer fails with IllegalArgumentError for a name that does not match the URI, a SKILL.md without YAML frontmatter, frontmatter that is not a valid McpSchema.SkillFrontmatter (for example a non-string metadata value), a file path that leaves the skill, more than 512 files or 16 MiB, a skill directory that contains or lies inside another skill's, or a file URI already registered as a resource. Registering a resource at a skill file's URI afterwards is a defect.
Quote ambiguous YAML. Clients may parse frontmatter as YAML 1.1, which turns yes or 1.0 into a boolean or number; quote such strings.
Digests use crypto.subtle, so the runtime must provide WebCrypto.
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { McpProtocol, McpServer } from "effect/ai"const MeritCycleSkill = McpServer.skill({ uri: "skill://comp/merit-cycle/SKILL.md", files: { "SKILL.md": `---name: merit-cycledescription: Draft and review merit proposals with the comp tools---Read references/bands.md before proposing any increase.`, "references/bands.md": "Proposals above the band maximum need an HRBP exception.\n" }})export const SkillsServer = McpServer.layerHttp({ name: "Comp Server", version: "1.0.0", path: "/mcp", protocols: [McpProtocol.v2026_07_28, McpProtocol.v2025_11_25], registrations: Layer.mergeAll(MeritCycleSkill)})
A skill tells an agent how to use your tools; it grants nothing. Hosts must ignore allowed-tools and similar permission-widening frontmatter unless the user approved it, and your handlers still authorize every call.
Every request runs in a server span that follows the OpenTelemetry MCP semantic conventions; RpcServer tracing is off for MCP.
Names.{method} {target} for tools/call and prompts/get (for example tools/call comp_get_salary_band), otherwise the bare method. Resource URIs stay out of span names.
Attributes.mcp.method.name, mcp.protocol.version, jsonrpc.request.id, mcp.session.id (HTTP sessions), network.transport (tcp or pipe), gen_ai.operation.name: "execute_tool" and gen_ai.tool.name for tool calls, gen_ai.prompt.name, and mcp.resource.uri for resource reads and subscriptions. Tool arguments are recorded as gen_ai.tool.call.arguments only when Toolkit.RecordToolArguments is true.
Parenting. A W3C traceparent in params._meta becomes the span's parent, so a client's trace continues into the server; the transport span (the HTTP server span) is then linked rather than parenting it. _meta claims other than traceparent are ignored.
Status. A tool result with isError: true sets error.type: "tool_error". A JSON-RPC error sets rpc.status_code; request errors (parse error, invalid request, method not found, invalid params, resource not found) leave the span successful, while server errors also set error.type to the code.
Migration: MCP spans are no longer named McpServer.* and no longer carry rpc.* attributes other than rpc.status_code. Update dashboards, sampling rules, and alerts to the names and attributes above.
For the full architecture — protocol eras, catalog design, OAuth resource-server middleware, sealed requestState, a dual-era confirmation gate, idempotency, and in-process tests — read Exposing an Effect Application over MCP.
Reach for it when you want capabilities usable from Claude Desktop, an IDE, or any MCP client — without writing JSON-RPC by hand.
A scoped client for calling another MCP server over stdio or Streamable HTTP, on the 2025-11-25 or 2026-07-28 protocol revision. The transport fixes the revision: pass one protocol adapter; the client does not negotiate. It covers discovery (listTools, listPrompts, listResources), callTool, getPrompt, readResource, the Skills extension, and adapting the remote tools to a Toolkit. client.capabilities holds the server's advertised McpSchema.ServerCapabilities. Resource templates, completion, logging, subscriptions, roots, sampling, elicitation, OAuth, and retries are not implemented: server requests other than ping get method-not-found, and a 2026-07-28input_required result fails with reason UnsupportedError.
Layers own the connection.McpClient.layerHttp({ name, version, protocol, url, headers? }) needs an HttpClient; a session-era HTTP session is closed with DELETE when the scope ends. McpClient.layerStdio({ name, version, protocol, command }) spawns the server through ChildProcessSpawner (for example NodeServices.layer); on close it shuts stdin, waits five seconds, then sends SIGTERM and, five seconds later, SIGKILL. Without a Layer, provide a McpClient.Transport from McpClient.http / McpClient.stdio to McpClient.make inside Effect.scoped, and keep every use inside that scope.
callTool takes a discovered descriptor, not a name, because on 2026-07-28 HTTP its x-mcp-header annotations decide which arguments are mirrored into headers. Without schema it returns the whole McpSchema.CallToolResult, including isError: true results — the caller decides. With schema it decodes structuredContent (the schema's decoding services become requirements) and a tool-reported error fails with reason ToolError, which keeps the result. Remote input schemas are metadata only; arguments are not validated against them.
Deadlines and limits. Initialization and each complete discovery scan share one deadline (timeout, default 60 seconds). callTool, getPrompt, readResource, getSkill, and readSkillResource are unbounded unless given { timeout }. Discovery follows cursors and fails with LimitError after a repeated cursor or the page and item limits — 100 and 10,000 by default, set for the client with discoveryLimits: { maxPages, maxItems } and per call with { limits } (nonnegative safe integers, otherwise ConfigurationError); a missing server capability makes a list empty and a retrieval fail with UnsupportedError. Messages over maxMessageBytes (16 MiB by default) are rejected both ways. The client never retries, so a TimeoutError says nothing about whether the server completed the call, and it creates no spans.
McpClient.toolkit(client, prefix?) snapshots the remote tools as a Toolkit.WithHandler that LanguageModel accepts, non-strict, with McpClientError as each tool's failureMode: "error" failure. Results become text; binary content and tool-reported errors fail the handler. Build a new toolkit to see server changes. Treat these tools like any externally sourced tool: they run code you do not control.
McpClient.toolkit(client, options) configures that binding. tools binds an approved snapshot of descriptors instead of discovering, so a server cannot add or change a tool until you re-approve it. resultMode: "complete" returns the whole CallToolResult and sends its content to the model as text and file parts; failureMode: "return" hands McpClientError failures (transport errors included, and ToolError with the failed result) back to the model. timeout bounds each call. trustAnnotations: true copies the server's hints into Tool.Readonly / Destructive / Idempotent / OpenWorld / Title but never sets approval. transformTool(tool, descriptor) derives each tool before binding — setNeedsApproval, annotate, addDependency — keeping its name, schemas, and failure mode. Each tool is a McpClient.RemoteTool<ResultMode, FailureMode, Requirements> annotated with its McpClient.ToolDescriptor, which is server-provided and untrusted.
Skills. Pass extensions: { skills: true } to declare the extension; without it the skill methods fail with ConfigurationError. listSkills() returns every McpSchema.Skill (none when the server does not declare the extension; an invalid entry fails the listing unless onInvalidSkill collects it), getSkill({ uri }) fetches one by its SKILL.md URI, and readResourceDirectory({ uri }) lists a skill directory when the server declares directoryRead. Read skill files with readSkillResource({ skill, uri }), not readResource: it reads only files in the skill's manifest (or directory, for a "dynamic" skill) and fails with ValidationError unless the bytes match the listed digest and size and a SKILL.md's frontmatter equals the listed one. Only name and description are checked on received frontmatter; decode with McpSchema.SkillFrontmatter for the rest, and never let allowed-tools widen permissions without user approval.
Fragment · Type-checked
ts
// @effect-diagnostics experimentalApiUsage:offimport { Effect, Layer, Schema } from "effect"import { McpClient, McpProtocol, type McpSchema } from "effect/ai"import { FetchHttpClient } from "effect/http"const ReportsMcp = McpClient.layerHttp({ name: "comp-assistant", version: "1.0.0", protocol: McpProtocol.v2026_07_28, url: "https://reports.acme.example/mcp", headers: { authorization: "Bearer <service token>" }}).pipe(Layer.provide(FetchHttpClient.layer))const Headcount = Schema.Struct({ count: Schema.Number })// A reviewed snapshot of the server's tools; anything else stays unbound.declare const approvedTools: ReadonlyArray<McpSchema.Tool>export const reportsToolkit = Effect.gen(function*() { const client = yield* McpClient.McpClient return yield* McpClient.toolkit(client, { prefix: "reports__", tools: approvedTools, timeout: "10 seconds", // Every remote write needs a human decision before it runs. transformTool: (tool, descriptor) => descriptor.annotations?.readOnlyHint === true ? tool : tool.setNeedsApproval(true) })}).pipe(Effect.provide(ReportsMcp))export const headcount = (orgUnit: string) => Effect.gen(function*() { const client = yield* McpClient.McpClient const tools = yield* client.listTools() const tool = tools.find((t) => t.name === "headcount") if (tool === undefined) return yield* Effect.die("reports server has no headcount tool") // Decodes structuredContent; a tool-reported error fails with reason ToolError. return yield* client.callTool({ tool, arguments: { orgUnit }, schema: Headcount }, { timeout: "5 seconds" }) }).pipe(Effect.provide(ReportsMcp))
Static credentials fit in headers; for rotating tokens, wrap the HttpClient with HttpClient.mapRequestEffect.
Reach for it when your Effect program must consume tools, prompts, or resources that another process publishes over MCP.
Every McpClient failure is one McpClientError (_tag: "McpClientError") whose reason says what happened: TransportError, ProtocolError (JSON-RPC code, data), HttpError (status, wwwAuthenticate, retryAfter, and any JSON-RPC error in the body), ClosedError (sessionExpired), TimeoutError (operation), LimitError, UnsupportedError, ValidationError, ConfigurationError, and ToolError (the tool's result). The error's message and cause come from its reason. isMcpClientError and isMcpClientErrorReason are the guards.
Reach for it when recovering from specific remote-MCP failures: Effect.catchReason / catchReasons select reasons, Effect.catchTag("McpClientError", ...) handles them all.
McpTest.makeClient(registrations, { protocols, protocolVersion?, clientInfo?, clientCapabilities? }) builds McpServer.layer over an in-memory RpcServer.Protocol, performs the handshake for the selected revision (the first adapter's by default), and returns a typed client in the surrounding Scope. Requests travel through the same JSON-RPC encoding, routing, middleware, visibility, and response encoding as stdio and HTTP, so results and errors match what a wire client sees: ping, listTools, callTool, listResources, listResourceTemplates, readResource, subscribe/unsubscribe, listPrompts, getPrompt, complete, and setLevel fail with McpSchema.McpError. Server notifications are queued on client.notifications in wire form; server-to-client requests (elicitation, sampling, roots) are rejected with method-not-found, so test elicit over a real session transport.
The transport discharges McpRequestContext (and McpServerClient when every adapter is session-based); every other request-level dependency must be met by test middleware, exactly as in production — providing the service directly does not compile.
Reach for it when testing registrations, middleware, visibility, and the wire shape of results without opening a socket; reach for HttpRouter.toWebHandler when the HTTP admission rules themselves are under test.
Note: A Workflow is the durable orchestration — deterministic glue code. The side-effecting steps inside it are Activities: a completed Exit is journaled, and later replay returns that result instead of deliberately re-running the step. Activity delivery is still at least once until the result is durably recorded, so external writes need an idempotency token, transaction, or outbox. DurableClock gives you sleeps that survive restarts; DurableDeferred gives you a wait-point an external system can complete later; DurableQueue hands work to background workers durably. The WorkflowEngine executes, persists, suspends, and resumes everything. WorkflowProxy/WorkflowProxyServer derive a typed RPC or HTTP surface so callers can start and resume runs without importing the handler.
Warning: A workflow body is replayed from the journal after every suspension or crash. So the body itself must be deterministic — same inputs, same sequence of steps. Never read the clock, generate randomness, or perform a side effect directly in the workflow. Wrap every non-deterministic or effectful step in an Activity (or a durable primitive), and make external effects idempotent. A crash after the external system commits but before the Activity result is persisted can cause that Activity to be delivered again.
Workflow.make(tag, options) records a stable tag, a payload Schema, optional success/error Schemas, and an idempotencyKey function that turns a payload into a string. The engine derives a deterministic execution id from a length-prefixed encoding of the tag and the idempotency key (so a tag/key pair can't be confused with a different pair that happens to concatenate to the same string): starting the same logical work twice yields the same run, not two.
workflow.toLayer(execute) registers the body with the engine and returns a Layer. The body receives the decoded payload and execution id and returns an Effect. Drive runs with workflow.execute(payload) (await result), execute(payload, { discard: true }) (fire-and-forget, returns execution id), poll(id), interrupt(id), and resume(id).
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { Activity, DurableClock, Workflow } from "effect/workflow"// Typed, recoverable failure — a normal Schema tagged error.class BudgetExceeded extends Schema.TaggedError<BudgetExceeded>()("BudgetExceeded", { employeeId: Schema.String}) {}// 1. The contract: a merit raise to apply, a confirmation string out, BudgetExceeded as the typed failure.export const ApproveMeritIncrease = Workflow.make("ApproveMeritIncrease", { payload: { employeeId: Schema.String, cycleId: Schema.String, // BigDecimal-as-string keeps currency exact over the wire. newBaseSalary: Schema.String }, success: Schema.String, error: BudgetExceeded, // Deterministic execution id: re-submitting the same employee + cycle is a no-op, not a double-raise. idempotencyKey: ({ employeeId, cycleId }) => `${cycleId}:${employeeId}`})// 2. The implementation: deterministic glue around journaled activities + a durable wait.export const ApproveMeritIncreaseLayer = ApproveMeritIncrease.toLayer( Effect.fn("ApproveMeritIncrease")(function*(payload, executionId) { // Each side effect lives in an Activity. Its recorded result is replayed, // while an interrupted delivery may run again before that result is recorded. const reservation = yield* Activity.make({ name: "ReserveMeritBudget", success: Schema.String, // a budget reservation id error: BudgetExceeded, execute: Effect.gen(function*() { const idempotencyKey = yield* Activity.idempotencyKey("ReserveMeritBudget") return yield* reserveBudget( payload.cycleId, payload.employeeId, payload.newBaseSalary, idempotencyKey ) }) }) // Survive a restart while we wait out the HRBP review SLA window. yield* DurableClock.sleep({ name: "HrbpReviewSla", duration: "2 days" }) yield* Activity.make({ name: "WriteSalaryToHris", execute: Effect.gen(function*() { const idempotencyKey = yield* Activity.idempotencyKey("WriteSalaryToHris") yield* writeSalary(payload.employeeId, payload.newBaseSalary, idempotencyKey) }) }) return `merit increase for ${payload.employeeId} applied (${reservation})` }))declare const reserveBudget: ( cycleId: string, employeeId: string, amount: string, idempotencyKey: string) => Effect.Effect<string, BudgetExceeded>declare const writeSalary: ( employeeId: string, amount: string, idempotencyKey: string) => Effect.Effect<void>
Tip:Workflow.withCompensation(effect, (value, cause) => cleanup) registers a saga-style rollback that runs only if the whole workflow fails. Workflow.addFinalizer provides unconditional cleanup. Compensation applies to top-level effects in the body, not steps nested inside an Activity. Two annotations change failure handling — attach them with workflow.annotate(...): Workflow.CaptureDefects (default true: a defect becomes the run's recorded failure instead of crashing the attempt) and Workflow.SuspendOnFailure (default false: when true, any failure parks the run as Suspended so an operator can fix the cause and call workflow.resume(executionId)).
The execution terminates in failure afterstep succeeded. Built on addFinalizer, so it shares its rules.
Saga-style undo of a committed top-level step.
Scope finalizers under Workflow.provideScope(effect) / Workflow.scope
The workflow scope closes on this owner — including when the attempt is abandoned for replay.
Process-local resources: a socket, a lock handle, a temp file.
Fragment · Type-checked
ts
import { Effect, Exit, Schema } from "effect"import { Activity, DurableDeferred, Workflow } from "effect/workflow"const HrbpDecision = DurableDeferred.make("HrbpDecision", { success: Schema.Literals(["approved", "rejected"])})export const EquityGrant = Workflow.make("EquityGrant", { payload: { grantId: Schema.String }, success: Schema.String, idempotencyKey: ({ grantId }) => grantId})export const EquityGrantLayer = EquityGrant.toLayer( Effect.fn("EquityGrant")(function*({ grantId }) { // Terminal-state work: runs when the EXECUTION completes, on whichever owner finishes it. yield* Workflow.addFinalizer((exit) => publishGrantClosed(grantId, Exit.isSuccess(exit) ? "applied" : "abandoned-or-failed") ) // Saga step: if the run later fails, release the shares that were reserved. const reservationId = yield* Activity.make({ name: "ReserveShares", success: Schema.String, execute: reserveShares(grantId) }).pipe( Workflow.withCompensation((reservation) => releaseShares(reservation)) ) // Owner-local resource: closed with the workflow scope on THIS process. yield* Effect.acquireRelease(openAuditSocket(grantId), (socket) => socket.close).pipe( Workflow.provideScope ) const decision = yield* DurableDeferred.await(HrbpDecision) return `${grantId}: ${decision} (${reservationId})` }))declare const publishGrantClosed: (grantId: string, status: string) => Effect.Effect<void>declare const reserveShares: (grantId: string) => Effect.Effect<string>declare const releaseShares: (reservationId: string) => Effect.Effect<void>declare const openAuditSocket: ( grantId: string) => Effect.Effect<{ readonly close: Effect.Effect<void> }>
Never release a process-local resource from addFinalizer. If the owner is lost the finalizer is skipped here, and when it eventually runs it may be on another machine.
Compensation is not an atomic rollback. It is an ordinary effect that can fail, be interrupted, or run more than once; make it idempotent and record its own outcome.
Registration happens on every pass through the body.addFinalizer, withCompensation, and scope finalizers are registered by running code, and the body runs again after each suspension. Each replay starts with a fresh workflow scope in both engines, so only the final run's compensations run. An addFinalizer callback registered in a run that later suspended still runs once when the execution finishes, but it observes Exit.void, not the execution's final exit — so a workflow that suspends once and then fails runs its compensation once and its addFinalizer callback twice (once with the failure, once with a success exit). Make finalizers idempotent and decide from the exit only in the final run's registration. Compensation still remains at-least-once across crashes.
interruptUnsafe during a running activity compensates once. A completed step's compensation is not run a second time; in WorkflowEngine.layerMemory, interruptUnsafe completes running and suspended workflows with an interrupted exit without needing an external wake, and an interrupt sent while a cluster run is still saving its Suspended reply is not lost.
Safe interruption matches across engines. In layerMemory, a workflow that finishes without suspending completes normally rather than being interrupted and running compensation.
Finalizers wait for the body's cleanup.Workflow.intoResult (which wraps every run) lets the handler's own interruption cleanup finish before workflow finalizers and compensation run, even when the interrupt lands right after startup. In layerMemory, resuming an execution whose previous run ended in a defect starts a fresh execution scope, and concurrent wakes set up one run at a time, so addFinalizer callbacks are not fired early by a resume.
An interrupted child surfaces as a defect in the parent. When a child workflow that the parent awaits is interrupted, the parent's child.execute(...) dies with a defect (<Child>.execute: execution "<id>" was interrupted) instead of being interrupted, so the parent can recover with Effect.catchDefect or Effect.exit and complete; with ClusterWorkflowEngine the interrupt also wakes a suspended parent.
An Effect.onExit in the body cannot observe a workflow interrupt. Interruption is deposited through the engine; use addFinalizer when terminal-state logic must see it.
Cancellation is not rollback. Distinguish five events and decide the state and side effects of each: the caller stops waiting (the run continues); the run receives an interrupt via workflow.interrupt(id) (terminal, finalizers and compensation run); the run suspends on a clock, deferred, queue, or child (nothing is lost, no cleanup runs); the owner is lost and the attempt is abandoned (replay elsewhere); and cancel races completion (whichever is recorded first wins, so the canceller must read the final status rather than assume).
Detached children and failure-suspended recovery
child.execute(payload, { discard: true }) returns the execution id without waiting, but the child remains linked: its completion wakes the parent and parent interruption interrupts it. Opt into { discard: true, detached: true } only for deliberately independent work. A detached child neither wakes its parent on completion nor gets interrupted with it; the cluster engine still records the parent for observability. Do not later await that detached execution from a workflow: executing the same payload joins it, but its completion will not wake the awaiting parent. Detachment is available only with discard: true, not as a generic background-fiber switch.
Workflow.SuspendOnFailure is an operator-recovery boundary, not a retry schedule. An execution's own failure suspension carries Workflow.Suspended.failed: true and does not retry the failed activity until explicitly resumed. Interrupting that execution completes it as interrupted without re-running the failed activity; inherited child failures do not set the parent's failed marker. Ordinary durable waits still resume automatically when their dependency completes.
WorkflowEngine.execute wakes waiting callers promptly when a final result is available; another suspension does not spend a suspendedRetrySchedule step. In ClusterWorkflowEngine, early wakes apply only to callers on the execution's owning runner; remote callers still depend on that schedule. Losing DurableDeferred.raceAll branches release their durable waits, so a late losing clock/deferred completion does not replay the continuing workflow. On replay under a new cluster owner, a deferred completion that is stored but not yet processed is read from the unprocessed request, so raceAll picks the same winner. If shutdown interrupts an activity inside a raceAll whose other branches are parked, the run replays on the next runner instead of being stored as Suspended forever. A child workflow waking its still-running parent during a forced shard release no longer stalls the release; the parent resumes under the next owner. Include parallel activity suspension plus deferred completion in recovery tests: callbacks must not lose their wake while another activity is running.
With ClusterWorkflowEngine, a run can be interrupted for a purely transient reason: its runner is shutting down, or the shard moved. The engine classifies that interrupt as an abandoned attempt:
nothing about the attempt is persisted — no result, no failure, no suspension record;
addFinalizer callbacks and compensations do not run, and a parent workflow is not resumed;
owner-local scope finalizers still run, so process resources are released; scopes from earlier runs that suspended are kept through the suspension and released when the execution completes or the owner tears down;
the execution is replayed from its journal by the next owner, where completed activities return their recorded results.
The practical consequence is the same rule as for a crash: an activity that was in flight may execute again, so the idempotency token still matters. Interrupt finalization in the in-memory engine matches the cluster engine's rules, including that an interrupt survives a replay, so tests against WorkflowEngine.layerMemory exercise the same finalization rules — but the in-memory engine has no owners to lose, so it cannot produce an abandoned attempt.
Reach for it when you have a multi-step business process that must survive restarts, suppress replay after completed steps are recorded, and be resumable and idempotent by a stable key.
Activity.make({ name, success, error, execute }) wraps an Effect so the engine runs it, persists its Exit, and — on later replay after that persistence succeeds — returns the stored result instead of re-executing. An Activityis an Effect (use yield*), so it composes like any other. Before the Exit is durably recorded, an interrupted or redelivered Activity may execute again.
The activity is the boundary between deterministic replayable glue and side-effecting work. Everything non-deterministic — external writes, clock reads, randomness — belongs inside one. The name is the journal key; it must be stable and unique within the workflow.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { Activity } from "effect/workflow"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {}) {}const PostSalaryChange = Effect.gen(function*() { // Activity.CurrentAttempt is a Context.Reference holding the retry attempt (starts at 1). const attempt = yield* Activity.CurrentAttempt const idempotencyKey = yield* Activity.idempotencyKey("WriteSalaryToHris") yield* Effect.log(`writing salary change to HRIS, attempt ${attempt}`) return yield* callHrisApi(idempotencyKey)}).pipe( // Activity.retry bumps CurrentAttempt on each attempt; same options as Effect.retry minus `schedule`. Activity.retry({ times: 5 }))const WriteSalaryActivity = Activity.make({ name: "WriteSalaryToHris", success: Schema.String, // the HRIS record revision id error: HrisUnavailable, execute: PostSalaryChange})declare const callHrisApi: (idempotencyKey: string) => Effect.Effect<string, HrisUnavailable>
The default interruptRetryPolicy is bounded and filters for interruption causes. If you replace it, its input is Cause<unknown>: retain an explicit Cause.hasInterrupts predicate and a finite attempt bound unless retrying typed failures and defects is intentional.
Under ClusterWorkflowEngine, resetting an activity's underlying cluster request so a retried attempt can re-execute is itself retried (bounded, exponential backoff) if that reset fails transiently — a transient failure to apply the reset no longer stalls the workflow run.
Tip:Activity.idempotencyKey(name) derives a deterministic hash from the current execution id and the name (optionally folding in the attempt) — useful as a dedup token to pass to external systems so retried writes cannot post twice. Activity.raceAll(name, [a, b, c]) runs several activities as a durable, success-biased race: the first success wins, or the collected failure wins only if every activity fails. The chosen result is journaled across restarts.
Scope the idempotency key to the logical operation.Activity.idempotencyKey(name) hashes the execution id and the name, so every retry and every replay of that activity sends the same token — right when all attempts are one logical operation, such as one payroll write. Pass { includeAttempt: true } only when each attempt is meant to create a distinct external resource. Never mint a fresh random key inside the activity: a replay would produce a different one and defeat the dedup.
Child workflows started from an activity. An activity may execute child workflows, including several in parallel (Effect.all([...], { concurrency })). All children are dispatched before the parent suspends, the activity's resources are released while it waits durably, and the parent resumes when the children complete — including when they complete while the parent is still cleaning up. (Suspension waits for running activities to finish or suspend; an activity whose start was interrupted does not leave that count raised, so it cannot block a later suspension.)
For SQL-backed workflow storage, an activity can opt into the engine's storage transaction with .annotate(ClusterSchema.WithTransaction, true) (the default is false). With SqlMessageStorage, database effects that use the supplied SqlClient then commit with the activity result. This is a backend-specific local transaction boundary: it does not make an external HTTP/API write atomic, so those calls still need an idempotency token or an outbox.
Reach for it when a step inside a workflow touches the outside world or is otherwise non-deterministic, and its completed result must be remembered. Design the effect for at-least-once delivery with an idempotency token or transactional boundary.
DurableClock.sleep({ name, duration }) pauses a workflow for a duration that may be minutes, hours, or days with no fiber kept alive. A normal Effect.sleep holds a fiber; if the process dies, the sleep is gone. A durable sleep schedules a wake-up in the engine and suspends the workflow. When the timer fires (even on a different machine after a redeploy), the engine resumes the run. Internally it uses an in-memory activity for short durations (≤ 60-second threshold by default) and a scheduled DurableDeferred wake-up for longer ones.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { Activity, DurableClock, Workflow } from "effect/workflow"export const EquityGrantApproval = Workflow.make("EquityGrantApproval", { payload: { employeeId: Schema.String, shares: Schema.Natural }, idempotencyKey: ({ employeeId }) => employeeId})export const EquityGrantApprovalLayer = EquityGrantApproval.toLayer( Effect.fn("EquityGrantApproval")(function*({ employeeId, shares }) { yield* Activity.make({ name: "NotifyHrbp", execute: notifyHrbp(employeeId, shares) }) // The engine resumes us here 5 days later if no one has acted — surviving any number of restarts. yield* DurableClock.sleep({ name: "vp-approval-sla", duration: "5 days" }) yield* Activity.make({ name: "EscalateToVp", execute: escalateToVp(employeeId) }) }))declare const notifyHrbp: (id: string, shares: number) => Effect.Effect<void>declare const escalateToVp: (id: string) => Effect.Effect<void>
Warning: Give every sleep a stable, unique name within the workflow — it's the journal key for that wake-up. Two sleeps sharing a name will collide on replay.
inMemoryThreshold decides which kind of sleep you get. A duration at or below the threshold (default 60 seconds) runs as an ordinary Effect.sleep inside a journaled activity named DurableClock/<name>: cheap, but if the owner dies mid-sleep the activity starts over, so the wait restarts from zero. A longer duration schedules a durable wake-up and suspends the run. Pass inMemoryThreshold: 0 to force the durable path for every non-zero sleep (an explicit 0 is honored), or raise it when short waits dominate and restart precision does not matter. A zero duration returns immediately. The default comes from the DurableClock.InMemoryThreshold reference (60 seconds unless provided), so Effect.provideService(DurableClock.InMemoryThreshold, Duration.zero) makes every sleep without an explicit option durable; the Cloudflare workflow engine provides exactly that, because a Durable Object may be evicted mid-sleep (see Cluster & Sharding).
Reach for it when a workflow must wait a meaningful amount of time (minutes to months) without pinning a fiber while staying crash-proof.
DurableDeferred.make(name, { success, error }) defines a durable, named wait-point. Inside a workflow, DurableDeferred.await(deferred) blocks by suspending the run until a result is recorded. Outside the workflow, complete it with a token via DurableDeferred.succeed, fail, or done.
The token is a branded string identifying the workflow name, execution id, and deferred name. Obtain one inside the run with DurableDeferred.token(deferred), or derive one externally via tokenFromExecutionId / tokenFromPayload. The resolved value lives in storage and survives restarts; the completer can be a completely different program.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { Activity, DurableDeferred, Workflow } from "effect/workflow"// A wait-point for the VP's sign-off on an equity grant.const VpSignOff = DurableDeferred.make("VpSignOff", { success: Schema.Literals(["approved", "rejected"])})// Inside the workflow body: capture a token to hand out, then suspend until the VP decides.const awaitVpSignOff = Effect.gen(function*() { const token = yield* DurableDeferred.token(VpSignOff) yield* Activity.make({ name: "NotifyVp", execute: Effect.gen(function*() { const idempotencyKey = yield* Activity.idempotencyKey("NotifyVp") yield* notifyVp(token, idempotencyKey) }) }) return yield* DurableDeferred.await(VpSignOff) // suspends the run until completed})// Elsewhere — e.g. an HTTP handler when the VP clicks "Approve" in the comp tool:const resolveSignOff = (token: DurableDeferred.Token) => DurableDeferred.succeed(VpSignOff, { token, value: "approved" })declare const notifyVp: ( token: DurableDeferred.Token, idempotencyKey: string) => Effect.Effect<void>
Tip:DurableDeferred.into(effect, deferred) runs an effect and records its Exit into the deferred, resuming waiters — the plumbing behind queues and races. DurableDeferred.raceAll({ name, success, error, effects }) is success-biased: it persists the first success, or the collected failure only after all effects fail. A completion can wake an active parked workflow immediately, and replay observes the recorded result. Under ClusterWorkflowEngine, a completion that arrives before the new owner's first local run has registered its wait is retained and seen by that later await; waking a suspended run retries its resume (through sharding.reset's expectedReplyId check) until the run's own reply is durably persisted, rather than acknowledging the deferred completion early, and a stale concurrent resume cannot use a now-outdated expected reply id to clear a newer completed reply out from under it. With WorkflowEngine.layerMemory, completing a deferred from a finalizer of the workflow that awaits it (including into inside raceAll) does not deadlock. Because intorecords an Exit, its requirements include the deferred's success and error schema encoding services as well as the decoding ones; a schema that needs a service to encode must have it provided where into runs.
Reach for it when a workflow must pause until an out-of-band signal arrives — an external approval, a third-party webhook.
DurableQueue.make({ name, payload, success, error, idempotencyKey }) defines a durable task queue. A workflow calls DurableQueue.process(queue, payload) to enqueue and suspend. A worker built with DurableQueue.worker(queue, handler) (a Layer) or makeWorker drains it.
process encodes the payload, offers it to a persisted queue, attaches a DurableDeferred token, and suspends the workflow. A worker takes the item, runs the handler, and records the handler's Exit through that token so the original run continues with the success or error. The worker supports configurable concurrency and can run in a separate deployment from the workflows that feed it.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { DurableQueue } from "effect/workflow"const StatementQueue = DurableQueue.make({ name: "EquityStatements", payload: { grantId: Schema.String }, success: Schema.String, // the rendered statement url idempotencyKey: ({ grantId }) => grantId})// Producer side, inside a workflow: enqueue and suspend until a worker finishes.const renderStatement = (grantId: string) => DurableQueue.process(StatementQueue, { grantId })// Consumer side: a layer that runs 4 workers draining the queue.const StatementWorker = DurableQueue.worker( StatementQueue, ({ grantId }) => renderEquityStatement(grantId), { concurrency: 4 })declare const renderEquityStatement: (grantId: string) => Effect.Effect<string>
Reach for it when a workflow needs to offload a unit of work to a pool of durable background workers and wait for the typed result.
WorkflowEngine is the service that registers workflow handlers, runs executions, journals activity results, stores durable-deferred completions, schedules clocks, polls status, and suspends/resumes runs. WorkflowInstance is the per-run state threaded through a single execution.
Everything else is a definition; the engine executes and persists. Its methods are called indirectly via workflow.execute, Activity.make, etc. Choose the engine layer to provide: WorkflowEngine.layerMemory is in-process and ephemeral (tests and local dev); for production provide a persistent engine such as ClusterWorkflowEngine from the cluster package.
Self-contained source · Type-checked
ts
import { Effect, Exit, Layer, Option, Schema } from "effect"import { Workflow, WorkflowEngine } from "effect/workflow"const ProrateBonus = Workflow.make("ProrateBonus", { payload: { employeeId: Schema.String, monthsWorked: Schema.Natural.check(Schema.isLessThanOrEqualTo(12)) }, success: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), idempotencyKey: ({ employeeId }) => employeeId})const ProrateBonusLayer = ProrateBonus.toLayer( ({ monthsWorked }) => Effect.succeed(Math.round((monthsWorked / 12) * 100) / 100))const program = Effect.gen(function*() { // Fire-and-forget: get the deterministic execution id back. const id = yield* ProrateBonus.execute({ employeeId: "emp_42", monthsWorked: 6 }, { discard: true }) // Await a result (idempotent — same key => same run). const result = yield* ProrateBonus.execute({ employeeId: "emp_42", monthsWorked: 6 }) // Inspect a run's status. const status = yield* ProrateBonus.poll(id) if (Option.isSome(status) && status.value._tag === "Complete") { yield* Effect.log(Exit.isSuccess(status.value.exit) ? "done" : "failed") } return result // 0.5}).pipe( // Register the workflow, then back it with the in-memory engine. Effect.provide(ProrateBonusLayer.pipe(Layer.provideMerge(WorkflowEngine.layerMemory))))
Note: A workflow Result is either Complete (carrying an Exit) or Suspended (the run is parked on a clock, deferred, or queue). That's how poll distinguishes "finished" from "waiting on something."
What layerMemory proves, and what it does not. It proves the contract, the control flow, replay determinism within one process, and interrupt/compensation ordering. It does not prove durability, redelivery after a kill, behavior under two owners, or compatibility of stored bytes with a new deployment. Those need the production engine and storage — see Recovery testing and operations.
With ClusterWorkflowEngine, each execution is a cluster entity with a fixed ten-second idle time, so a suspended or finished run releases its runner slot quickly and is rebuilt from storage on its next message; see Cluster & Sharding. That engine also retries transient PersistenceErrors from inside a running workflow (activity sends and reply reads, deferred completions, clock scheduling, child starts) instead of recording them as the workflow's defect.
On Cloudflare,CloudflareCluster.layer (or CloudflareWorkflowEngine.layer alone) from the experimental @effect/platform-cloudflare provides the engine: each execution is its own SQLite-backed Durable Object driven by one alarm, and the workflow, activity, deferred, and queue APIs are unchanged. See Running on Cloudflare Durable Objects.
Reach for it when wiring the app: layerMemory for tests/dev, a persistent engine for production, provided under your workflow layers.
WorkflowProxy.toRpcGroup(workflows) produces an RpcGroup; WorkflowProxy.toHttpApiGroup(name, workflows) produces an HttpApiGroup of POST endpoints. For each workflow you get three operations: execute, discard (fire-and-forget), and resume-by-execution-id.
A caller can start or resume a run over the wire without importing the workflow's handler or the engine. The contract is generated from the workflow definitions.
Operation
RPC tag (toRpcGroup, optional { prefix })
HTTP endpoint (toHttpApiGroup)
Success
Execute and await
<Tag>
POST /<tag> (the tag lower-cased)
the workflow's success
Start without waiting
<Tag>Discard
POST /<tag>/discard
the execution id (Schema.String) — keep it to poll, interrupt, or resume later
Resume a suspended run
<Tag>Resume
POST /<tag>/resume
— (payload { executionId })
The workflow's annotations are merged onto all three generated operations, and the execute operation carries the workflow's error schema.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Workflow, WorkflowProxy } from "effect/workflow"const ApproveMeritIncrease = Workflow.make("ApproveMeritIncrease", { payload: { employeeId: Schema.String, cycleId: Schema.String, newBaseSalary: Schema.String }, idempotencyKey: ({ employeeId, cycleId }) => `${cycleId}:${employeeId}`})const compWorkflows = [ApproveMeritIncrease] as const// One RpcGroup describing execute / discard / resume for every workflow.export class CompWorkflowRpcs extends WorkflowProxy.toRpcGroup(compWorkflows) {}
Reach for it when something outside the workflow host needs to start or resume runs over RPC or HTTP with full types.
WorkflowProxyServer.layerRpcHandlers(workflows) implements the RPC group produced by toRpcGroup; WorkflowProxyServer.layerHttpApi(api, groupName, workflows) implements the HTTP group from toHttpApiGroup. Each routes execute/discard/resume requests to the matching workflow operation, keeping the engine and handlers on the server side.
Mount under RpcServer.layer (or HTTP API builder) and wire calls land on real workflow executions.
Self-contained source · Type-checked
ts
import { Layer, Schema } from "effect"import { RpcServer } from "effect/rpc"import { Workflow, WorkflowProxy, WorkflowProxyServer } from "effect/workflow"const ApproveMeritIncrease = Workflow.make("ApproveMeritIncrease", { payload: { employeeId: Schema.String, cycleId: Schema.String, newBaseSalary: Schema.String }, idempotencyKey: ({ employeeId, cycleId }) => `${cycleId}:${employeeId}`})const compWorkflows = [ApproveMeritIncrease] as constclass CompWorkflowRpcs extends WorkflowProxy.toRpcGroup(compWorkflows) {}// Serve the generated RPCs by routing them to the workflows.const ApiLayer = RpcServer.layer(CompWorkflowRpcs).pipe( Layer.provide(WorkflowProxyServer.layerRpcHandlers(compWorkflows)))
Reach for it when you've derived a workflow RPC/HTTP surface and need to mount the handlers that actually run the executions.
A journal outlives the code that wrote it. Every name and schema a run has touched is a compatibility contract for as long as that run can still replay.
Identity
Where it is stored
Changing it while runs are in flight
Workflow tag and idempotencyKey output
Execution id (a hash of both)
Orphans live executions and lets the same business intent start a second run.
Activityname
Journal key for the recorded Exit
Replay finds no record and executes the activity again.
Old records fail to decode unless the new schema still accepts them.
Order and presence of steps in the body
Implicit: replay walks the same sequence
Reordering or removing a step changes which journal entries a replay consumes.
Rules that keep upgrades boring:
Renaming an import is not a migration. Only the string tags and names are persisted; keep them frozen and treat a new name as a new workflow.
Reusing a tag across conflicting definitions is caught, not silent. Under ClusterWorkflowEngine, registering two workflow definitions that share a tag but disagree (for example on payload/success/error schemas) logs a warning instead of letting the mismatch surface only as a confusing decode failure later.
Add, do not mutate. Evolve schemas so that old encoded values still decode (new optional fields, widened unions). For an incompatible change, introduce ApproveMeritIncreaseV2 with its own tag and let the old tag drain.
Inventory before rollout. Know how many executions are running or suspended per workflow tag and how long the longest durable wait is; that is how long the old handler must stay registered.
Pick one rollout strategy deliberately: drain old runs first; route by version; dual-read; migrate stored records with a verified tool; or start a new identity. "Deploy and hope" is the only wrong one.
Do not read mutable ambient configuration in the body. A feature flag or limit that changes between the original run and a replay changes the path. Capture it once in an Activity (its recorded value is what replays see) or pass it in the payload.
Validate before interpreting. Stored bytes are input: decode with the schema, check the version and tenant you expect, and park records you cannot decode for an operator instead of retrying them forever.
The engine's guarantees are only as good as the backend and the deployment. Test the failure windows on the real storage, and label every claim by its evidence: proved by the library, depends on the adapter, depends on the deployment, or design guidance.
Kill or fault the worker…
What must hold afterwards
before the activity's external effect
The activity runs once on replay.
after the external system accepted the write, before the Exit was recorded
The activity runs again with the same idempotency token; the sink deduplicates.
after the Exit was recorded, before the next step
Replay returns the recorded result; the external effect does not repeat.
during a DurableClock sleep, DurableDeferred.await, or queue wait
The run is Suspended in storage and resumes on another owner at the right time.
during compensation
Compensation runs again; it is idempotent.
while an old owner is paused past its lease (a long GC or VM pause)
The old owner's late write is rejected by the sink's idempotency/version check — the engine does not supply a fencing token.
with storage unavailable
New work is refused or waits; nothing is acknowledged that was not persisted.
with old and new code on the same store
Old runs replay on new code (or stay on old workers); fixtures of old journal bytes decode.
with a corrupt or undecodable record
The record is quarantined and visible to an operator; it does not become a hot retry loop.
Run these in three separate lanes: a deterministic lane (WorkflowEngine.layerMemory, TestClock) for control flow and compensation order; an adapter lane against the production storage with real kill-and-restart; and an artifact lane that exercises the built deployable. A kill bypasses every finalizer, so restart behavior must never depend on cleanup having run.
Operate it as a product surface. Monitor suspended executions by age, activity attempt counts, replay failures, and dead-lettered queue items. Operator actions — inspect, interrupt, resume, redrive, release from quarantine — change business state, so authenticate, authorize, and audit them like any other write path. A backup that has never been restored is not a recovery plan; rehearse a restore and replay in-flight executions against it.
Tip: A complete durable workflow app: one or more Workflow.make definitions, each .toLayer(...) with a deterministic body composed of Activity/DurableClock/DurableDeferred/DurableQueue steps; a WorkflowEngine layer (memory in dev, cluster in prod) provided under them; and — if external callers need access — a WorkflowProxy contract served by WorkflowProxyServer. Keep bodies deterministic, journal every side effect.
Effect Cluster provides entities: stateful, addressable actors keyed by id, distributed across machines and reachable through typed RPC clients. A message to dept-eng is routed to the owning shard, the entity is spun up on demand, kept warm, and passivated when idle. Pair with durable message storage for at-least-once delivery that survives restarts.
Note: The spine: Entity defines an addressable actor and its RPC protocol. Sharding routes every message. Runner/Runners host shards and talk to each other. MessageStorage makes delivery durable. Singleton, Snowflake, EntityProxy, ClusterCron, ShardingConfig hang off those four. Define entities, merge their layers, provide a cluster layer.
Official example: Effect's release-matched ai-docs cluster example defines and runs a distributed entity.
Warning: The entire cluster surface lives under effect/cluster. APIs may shift between minor versions. Pin your version and re-check signatures when you upgrade. Transport entrypoints (NodeClusterSocket, NodeClusterHttp) come from @effect/platform-node; @effect/platform-bun and @effect/platform-deno ship the matching BunCluster* / DenoCluster* modules. The experimental @effect/platform-cloudflare runs the same entities and workflows on Cloudflare Durable Objects instead of runners (see Running on Cloudflare Durable Objects).
Note: The socket and HTTP/WebSocket runner transports serialize runner-to-runner traffic with SchemaBinary by default (serialization: "binary"); "ndjson" (newline-delimited JSON) is the interoperable alternative when you need a text wire format. Every runner and every client-only node of one cluster must agree on this setting. See Transport options.
An Entity gives a stable type name and an RPC protocol to a family of values addressed by id. Entity.make("Department", [RecordRaise, GetBudget]) declares a kind called Department, keyed by string id, with those RPCs. The cluster picks a shard for each id and routes requests to the owning runner.
Mental model. A sharded, stateful actor whose interface is an RpcGroup. Each live instance processes a mailbox sequentially (no locks needed), holds state in a plain Ref. Idle long enough and it is passivated — stopped, state dropped — then transparently recreated on the next message. Address an instance by id; the runtime materializes it.
Define the protocol with Rpc.make, register handlers with entity.toLayer(...), get a typed client with entity.client. The handler builder is a normal Effect.gen that can allocate per-instance state and close over it.
Self-contained source · Type-checked
ts
import { BigDecimal, Effect, Ref, Schema } from "effect"import { ClusterSchema, Entity } from "effect/cluster"import { Rpc } from "effect/rpc"// 1. Define the protocol — two RPCs, each a plain Rpc.make. A department owns// its slice of the merit budget; you draw it down by recording raises.const RecordRaise = Rpc.make("RecordRaise", { payload: { employeeId: Schema.String, amount: Schema.BigDecimal }, success: Schema.BigDecimal // remaining budget after the raise}) // Annotate an RPC as Persisted so the message is durably stored before // delivery (at-least-once). A recorded raise must survive a node crash, so // without this it would be volatile and only sent over the network. .annotate(ClusterSchema.Persisted, true)const GetBudget = Rpc.make("GetBudget", { success: Schema.BigDecimal})// 2. The entity is just a named bundle of RPCs.const Department = Entity.make("Department", [RecordRaise, GetBudget])// 3. Register handlers as a Layer. The builder runs once per live instance,// so the Ref is this department's private, in-memory merit budget.const DepartmentLayer = Department.toLayer( Effect.gen(function*() { const budget = yield* Ref.make(BigDecimal.fromBigInt(250_000n)) return Department.of({ RecordRaise: ({ payload }) => Ref.updateAndGet(budget, (b) => BigDecimal.subtract(b, payload.amount)), // Rpc.fork opts a single handler out of the default sequential // execution so budget reads can run concurrently with writes. GetBudget: () => Ref.get(budget).pipe(Rpc.fork) }) }), // Passivation: if idle this long, stop the instance and recreate on demand. { maxIdleTime: "5 minutes" })
entity.client yields a function from id to a typed RPC client. Calling departments("dept-eng") gives the exact methods of the protocol — payloads and results checked against Schemas.
Tip:toLayer is the idiomatic path. For actor purists who want to own the message loop, toLayerQueue hands a Queue.Dequeue of request envelopes plus a Replier (succeed/fail/failCause/complete). Same delivery guarantees, lower-level control.
Note:toLayer takes maxIdleTime (passivation; the ShardingConfig.entityMaxIdleTime default is one minute), concurrency (defaults to sequential per instance), mailboxCapacity, mailboxMetrics (per-entity mailbox gauge; see ClusterMetrics), a defectRetryPolicy, disableFatalDefects, and spanAttributes. By default a handler defect is fatal to the instance: the runtime logs it, waits according to defectRetryPolicy, rebuilds the instance, and re-delivers the requests that were in flight — so handlers must tolerate redelivery. The backoff is tracked per entity instance (one defecting id does not slow down its siblings) and resets once a request completes. When your defectRetryPolicy ends, the default schedule (500 ms growing 1.5× per attempt, capped at 10 seconds) takes over, so restarts never stop; the same policy retries a failing handler build. With disableFatalDefects: true only the failing call reports the defect and the instance keeps running — use that when a request may defect repeatedly. An interrupt that arrives for a request while its instance is being rebuilt is kept and applied to the rebuilt instance, so the request is interrupted rather than replayed again and the sender is not stalled (server-uninterruptible requests ignore it). Inside a handler read Entity.CurrentAddress (this entity's type/id/shard) and call Entity.keepAlive(true) to pin an instance alive while it holds a resource. keepAlive delegates to an Entity.KeepAliveHandler service ((enabled: boolean) => Effect<void>) when the runtime provides one, as the Cloudflare runtime does; otherwise it uses the runner's own keep-alive mechanism. For tests without transport, Entity.makeTestClient(entity, layer) builds an in-memory client. It honors the entity layer's disableFatalDefects setting: without it, one handler defect also fails the other calls pending on that entity id in the test.
Note: Handlers resolve services from the context in which the entity is registered — what you provide to the entity.toLayer(...) layer wins. Services that were only present when Sharding itself was constructed remain a fallback, not an override.
Reach for it when you have per-key state that you want distributed across machines while keeping each key's logic single-threaded and addressable.
The routing brain of the cluster; every entity client implicitly depends on it. Sharding decides which shard owns a given entity id, tracks shards belonging to the local runner, sends each message to a local handler or across the wire to the owning runner. Also registers entities and singletons, mints runner-local snowflake ids, and polls durable storage for persisted work.
Mental model. Entity ids are hashed into a fixed number of shards per group; shards are spread across healthy runners using a consistent hash ring weighted per runner. When you send to dept-eng, Sharding computes its ShardId, looks up the owning runner, and routes. When runners join or leave, shards are reassigned and entities migrate — client code never changes. You almost never call Sharding methods directly; provide its layer and let Entity and Singleton drive it.
Fragment · Type-checked
ts
import { Layer } from "effect"import { NodeClusterSocket } from "@effect/platform-node"import type { SqlClient } from "effect/sql"import { Sharding } from "effect/cluster"declare const SqlClientLayer: Layer.Layer<SqlClient.SqlClient>// The transport entrypoint wires Sharding to a socket runner, SQL-backed// message + runner storage, ping-based health, and env-driven config.// You provide a SqlClient; you get a full cluster node.const ClusterLayer = NodeClusterSocket.layer().pipe( Layer.provide(SqlClientLayer))// Your entity layers depend on Sharding; provide the cluster layer to satisfy// that dependency and you have a running runner.declare const DepartmentLayer: Layer.Layer<never, never, Sharding.Sharding>const RunnerProgram = DepartmentLayer.pipe(Layer.provide(ClusterLayer))
Service interface: registerEntity and registerSingleton (called under the hood by Entity.toLayer / Singleton.make), makeClient (called by entity.client), getShardId, hasShardId, getSnowflake, isShutdown, getRegistrationEvents (stream of registration events — handy to await startup), pollStorage to force a durable read.
A local send that is waiting for an entity type to register is bounded: once the shared runner-registration deadline elapses, it fails with an Entity type ... not registered defect instead of waiting forever, and a send to a still-unregistered dynamic entity type fails immediately once that deadline has passed.
Tip: A process whose ShardingConfig.runnerAddress is None joins as a client: it can send messages but hosts no shards. Use the layerClientOnly variants on transport modules.
NodeClusterSocket.layer(options?) and NodeClusterHttp.layer({ transport, ...options }) (and the Bun and Deno equivalents) take the same option set. Every runner and every client-only node of one cluster must agree on the serialization.
Option
Default
Meaning
transport (NodeClusterHttp only, required)
—
"http" or "websocket" between runners.
serialization
"binary"
"binary" = RpcSerialization.layerSchemaBinary (schema-derived frames); "ndjson" = newline-delimited JSON. This is the runner wire format, so it is a deployment-wide choice.
serializationMaxBufferSize
16 MiB
Largest frame ("binary") or buffered line ("ndjson") a runner accepts; "unbounded" removes the limit. Raise it deliberately — it bounds memory per connection.
clientOnly
false
true builds a node that sends but hosts no shards and opens no server.
storage
"sql"
"sql" = SqlMessageStorage + SqlRunnerStorage (requires a SqlClient); "local" = no message persistence and in-memory runner storage (single process only); "byo" = you provide MessageStorage and RunnerStorage.
runnerHealth
"ping"
"k8s" reads pod readiness instead (runnerHealthK8s: { namespace, labelSelector }).
shardingConfig
—
Partial ShardingConfig merged over the environment-derived values.
Fragment · Type-checked
ts
import { Layer } from "effect"import { NodeClusterSocket } from "@effect/platform-node"import type { SqlClient } from "effect/sql"declare const SqlClientLayer: Layer.Layer<SqlClient.SqlClient>// Pin to "ndjson" when a deployment needs a text wire format instead of the// binary default — every runner and client-only node must agree.const TextWireCluster = NodeClusterSocket.layer({ serialization: "ndjson", serializationMaxBufferSize: 8 * 1024 * 1024, shardingConfig: { maxResidentEntities: 5_000 }}).pipe(Layer.provide(SqlClientLayer))
Deployment warning: the RPC request envelope that carries runner traffic gained an optional discard field (a discarded call now completes when the receiver acknowledges it), which changes the "binary" (SchemaBinary) frame fingerprint. Runners and client-only nodes on binary serialization cannot be mixed across that change; upgrade them together, and rehearse any rolling upgrade on a mixed-version pair first.
For what the serialization layers do on the wire, see RPC.
Shard assignment comes from HashRing (the stable effect/HashRing module): one ring per shard group, each runner added with its weight. An eligible runner sitting at the first ring position is not skipped once other runners have reached their allocation quota.
A persisted call never fails just because ownership is moving. The caller keeps waiting on message storage; only a shutdown of the caller's own runner ends the wait, and it does so by interruption (see EntityProxy).
Teardown bookkeeping is bounded. Whether an interrupt is "transient" is decided from live teardown state — entity, shard, singleton, entity type, or node shutdown — rather than from a growing set of fiber ids, so mass passivation does not leak memory.
Handoff drains before release. Shutdown stops acquiring new shards and hands them off one at a time after their entities and singletons stop. The wait is bounded; on timeout, releaseAll attempts to release remaining locks. Interrupts and stream acknowledgements still reach work draining on the previous owner. Volatile requests arriving during handoff wait at most shardLockExpiration; persisted outgoing requests are stored even while a locally assigned shard is still waiting for its lock.
Shutdown abandons callers instead of waiting them out. A workflow or other durable caller waiting on a persisted request that has not started is abandoned during runner shutdown, so the request replays under the next owner instead of holding shutdown for entityTerminationTimeout. With preemptiveShutdown: false, entities drain before the runner is marked as shutting down, so such a caller still waits for entityTerminationTimeout.
A runner that lost a shard does not write its reply. Before storing the final reply of a persisted request, the runner refreshes its shard locks and checks that the shard is still among them; if not, the request is left for the shard's new owner.
Stalled forced releases are visible. A forced shard release still pending after shardLockExpiration logs a warning naming the shards and the pending entity types and singletons, repeated every max(shardLockExpiration, 30 seconds); the shardsReleasing gauge in ClusterMetrics counts shards still being released. Teardown and lock release must still finish before the shard is reacquired.
Batch shard handoff during scale-up with runnerJoinDebounce. By default (0) every runner join republishes assignments immediately, so a surge deployment can move a shard once per join. Set ShardingConfig.runnerJoinDebounce to add joining runners only after the healthy runner set has stayed unchanged for that duration (at most four times the duration after the first pending join). Runners that already hold shards and leave or become unhealthy are still published immediately. While joins are pending, runners take no new shards, so a shard can stay unlocked briefly.
Persisted messages are read as soon as their entity type registers, rather than at the next entityMessagePollInterval.
Process death skips finalizers. Entity finalizers and Entity.keepAlive scopes run on graceful passivation and shutdown only; recovery after a kill relies on runner health checks, shard-lock release or expiry (shardLockExpiration defaults to 35 seconds), and redelivery of persisted messages — never on cleanup code having run.
Reach for it when building cluster tooling or custom routing. Otherwise, provide its layer.
CloudflareCluster.layer from the experimental @effect/platform-cloudflare package provides Sharding, WorkflowEngine, and PersistedQueueFactory without runners, shard locks, or an external database. Each entity id is its own Durable Object, which persists the entity's mailbox and replies in its own SQLite storage. Entity, Rpc, ClusterSchema, Workflow, Activity, DurableDeferred, and DurableQueue definitions stay the same; only the cluster layer changes.
Fragment · Type-checked
ts
// @effect-diagnostics experimentalApiUsage:offimport { CloudflareCluster } from "@effect/platform-cloudflare"import { Effect, Layer, Schema } from "effect"import { ClusterSchema, Entity } from "effect/cluster"import { Rpc } from "effect/rpc"// The four same-Worker Durable Object namespace bindings from wrangler.jsonc.type Namespace = CloudflareCluster.LayerOptions["entityNamespace"]declare const env: { readonly CLUSTER_ENTITY: Namespace readonly CLUSTER_WORKFLOW: Namespace readonly CLUSTER_QUEUE: Namespace readonly CLUSTER_SINGLETON: Namespace}const Counter = Entity.make("Counter", [ Rpc.make("Increment", { success: Schema.Number })]).annotateRpcs(ClusterSchema.Persisted, true)const CounterLayer = Counter.toLayer(Effect.gen(function*() { // The entity's own SQLite storage; rows commit with its mailbox. const sql = yield* CloudflareCluster.DurableObjectSqlClient.orDie yield* sql`CREATE TABLE IF NOT EXISTS hits (id INTEGER PRIMARY KEY)`.pipe(Effect.orDie) return Counter.of({ Increment: () => Effect.gen(function*() { yield* sql`INSERT INTO hits DEFAULT VALUES` const rows = yield* sql<{ readonly n: number }>`SELECT count(*) AS n FROM hits` return rows[0]?.n ?? 0 }).pipe(Effect.orDie) })}))const ClusterLayer = CounterLayer.pipe( Layer.provideMerge(CloudflareCluster.layer({ entities: [Counter], // every entity type this Worker serves entityNamespace: env.CLUSTER_ENTITY, workflowNamespace: env.CLUSTER_WORKFLOW, queueNamespace: env.CLUSTER_QUEUE, singletonNamespace: env.CLUSTER_SINGLETON })))
Deployment shape. The Worker entry module re-exports the four classes from @effect/platform-cloudflare/CloudflareDurableObjects (ClusterEntity, ClusterWorkflow, ClusterDurableQueue, ClusterSingleton), and wrangler.jsonc binds each as a SQLite-backed class. These objects only accept calls through the same-Worker bindings and reject a direct fetch, so do not route public traffic to them. When the layer is built asynchronously, register it with CloudflareDurableObjects.setInitializer(env => ...); every cold object waits for it, and it must finish within 15 seconds and tolerate running more than once per isolate. AlchemyCloudflareCluster.make (subpath import, optional @alchemy.run/cloudflare peer) replaces the class exports, bindings, and initializer when you deploy with Alchemy.
Routing and delivery.Entity.client encodes (type, id) into a Durable Object name and calls getByName; an entity type missing from entities fails in the Worker before any object is contacted. Persisted requests are stored before they run, deduplicated by primary key, and replayed after an eviction or deploy by an alarm. Non-persisted RPCs are best effort and can be lost when the object hibernates or crashes.
Different defaults. Handler defects are always request-local (as if disableFatalDefects were true), and maxIdleTime and mailboxCapacity are accepted but ignored: hibernation owns idle objects and the mailbox holds at most 4096 requests. concurrency, defectRetryPolicy, and spanAttributes apply. Entity.keepAlive pins an object through an alarm re-armed every keepAliveHeartbeat (default 30 seconds), which is also how a kept-alive entity comes back after a restart.
Singletons and ClusterCron run only when woken. Nothing starts them on deploy: a Worker Cron Trigger calls env.CLUSTER_SINGLETON.getByName("Singleton/<name>").wake(), which runs the singleton effect once, so do not write it as a forever loop. For a ClusterCron, wake the seed singleton named by CloudflareCluster.clusterCronSingletonName(name); later runs schedule themselves.
DurableObjectSqlClient is a separate tag from SqlClient.SqlClient, so a Worker-wide database (D1, say) stays reachable inside handlers. Tables named cluster_* are reserved, a row is capped at 2 MB, and a withTransaction holds the object's input gate closed, so keep timers and I/O out of the transaction.
Out of scope. Shards, shard locks, runners, and MessageStorage/RunnerStorage/RunnerHealth as replaceable services do not apply; the layer provides no MessageStorage, so MessageRetention cannot be used. Sharding.getSnowflake dies (request ids are UUIDv7), and PersistedQueue.layerCleanup fails. The workflow engine makes DurableClock.sleep durable unless you pass an explicit inMemoryThreshold (see Workflows & Durable Execution).
Run an effect on exactly one node in the cluster, regardless of cluster size. Singleton.make(name, effect) returns a Layer that registers a background effect with Sharding. The runner owning the singleton's shard starts it; if ownership moves (node dies, rebalance) the fiber is interrupted on the old node and restarted on the new owner.
Mental model. A leader-elected fiber without writing the election. The singleton's name hashes to a shard; whoever owns that shard runs it. One owner at a time, automatic failover, zero coordination code.
Self-contained source · Type-checked
ts
import { Effect, Schedule } from "effect"import { Singleton } from "effect/cluster"// This loop runs on exactly one runner cluster-wide. It is the single source of// truth for whether comp is frozen; if that runner dies, another picks it up.const CompFreezeCoordinator = Singleton.make( "comp-freeze-coordinator", Effect.log("checking comp-freeze flag and broadcasting to departments...").pipe( // ... read the freeze flag, fan out to each Department entity ... Effect.repeat(Schedule.spaced("30 seconds")), Effect.forever ), { shardGroup: "default" })
Warning: Failures from the effect are converted to defects — handle expected errors inside the effect if it should keep running. An effect that simply completes is held until ownership moves or the layer closes (wrap long-running work in Effect.forever). Registering the same name in the same shard group twice dies at registration.
Reach for it when you need a cluster-wide daemon that runs exactly once with failover, without standing up external coordination.
Metadata describing one process that can host shards. A Runner is a Schema.Class bundling a RunnerAddress, the shard groups it participates in, and a relative weight used when distributing shards.
Mental model. A row in the cluster's membership table. Each runner's address is added to its groups' hash rings with weight as its slice size — a higher weight earns proportionally more shards. Structurally compared and hashed by address + weight; serializes to/from JSON for exchange between nodes.
Self-contained source · Type-checked
ts
import { Runner, RunnerAddress } from "effect/cluster"// A runner that hosts the "default" and "merit-cycle" groups, weighted 2x so it// carries twice as many shards during the busy review season.const self = Runner.make({ address: RunnerAddress.make("10.0.0.4", 34431), groups: ["default", "merit-cycle"], weight: 2})
Reach for it when building custom membership or storage backends. Standard deployments get Runner values constructed by the transport layer from ShardingConfig.
The node-to-node communication service. Where Shardingdecides where a message goes, Runnersdelivers it. Can ping a runner, send a request or control envelope to a remote runner, notify a runner that work is waiting, and mark a runner address unavailable. Persisted notifications recover replies from storage; discarded volatile messages complete after delivery instead of waiting for an entity reply.
Mental model. The RPC transport between cluster members, expressed as its own RpcGroup (Runners.Rpcs). When a department lives on another machine, Sharding asks Runners to forward the envelope; the remote RunnerServer feeds it back into its own Sharding. Implementations: layerNoop (single-process, no networking), and the RPC-backed one driven by transport modules.
Note: Configure Runners by choosing a transport layer. SingleRunner.layer and TestRunner.layer use Runners.layerNoop; SocketRunner / HttpRunner (via NodeClusterSocket / NodeClusterHttp) wire the RPC-backed version over real socket or HTTP/WebSocket. The pluggable seam is Runners.RpcClientProtocol. The platform transport layers choose the RPC serialization for that protocol (SchemaBinary by default, NDJSON on request — see Transport options).
Reach for it when implementing a new cluster transport. Otherwise, pick a runner layer.
The durability boundary. MessageStorage is the pluggable backend that makes mailboxes recoverable. Saves requests, control envelopes, and replies; finds unprocessed messages for shards a runner owns; deduplicates requests by primary key; tracks reply handlers waiting on responses. Upgrades delivery from best-effort to at-least-once that survives a crash.
Mental model. When an RPC is annotated ClusterSchema.Persisted, the message is written to storage before being accepted; a restarted runner reads back its shards' unprocessed messages and resumes. Replies are stored too — a duplicate request (same primary key) returns the already-computed reply instead of re-running the handler. The contract is encoded (strings and bytes) so any database can back it.
noop / layerNoop — No persistence. Volatile delivery only. Fine when every RPC is non-persisted.
MemoryDriver / layerMemory — In-memory store for tests and single-process dev. Durable within the process lifetime; the engine behind TestRunner.
SqlMessageStorage — Production choice: encodes envelopes and reply chunks into SQL tables, with migrations and dedup. Pairs with any @effect/sql-* client.
The save path returns a SaveResult tagged enum — Success or Duplicate (carrying the existing reply) — for raise-request dedup.
A persisted transactional reply is a commit boundary, not just a handler return. With ClusterSchema.WithTransaction, successful handler writes and the success reply commit together. Typed failures and non-fatal defects are saved after rollback, so a duplicate can recover the failure reply too. Terminal replies are published only after commit or clean rollback; a transaction failure recovers a committed reply or retries the request. A failed success-reply save inside the request transaction is not retried there (a retry could autocommit the reply outside the aborted transaction, for example after a MySQL deadlock); the failed transaction replays the request instead. When a reply save commits but still reports an error (the COMMIT acknowledgement was lost), the runner finds the stored reply and lets the caller read it without replaying the request. A discarded persisted send made from inside the transaction wakes the receiving runner only after the commit, since the message is invisible to it before then. This also applies to local in-memory reply publication inside an outer transaction. Local persisted clients read replies back from storage, so a reply that arrived before handler registration is not lost. External HTTP calls and other non-transactional side effects remain outside this SQL boundary.
Reads are bounded and claim only what they return.unprocessedMessages(shardIds, { limit?, addresses? }) reads at most limit messages (the runner passes ShardingConfig.unprocessedMessageBatchSize) and can be restricted to specific entity addresses. Only the returned messages are claimed; everything else stays eligible for a later poll, which is what lets a runner at its residency cap keep serving resident entities without starving the rest. The in-memory driver applies the same ten-minute claim window as SQL, and resetAddress / resetAddresses / resetShards make claimed messages eligible again immediately.
Fresh local replies skip storage reads. A fresh persisted request owned by the local runner is answered from a reply handler registered before the request is saved. Duplicates and streams still read their replies from storage, and a dropped reply handler falls back to storage immediately.
Custom backends.MessageStorage.makeEncoded(encoded) lifts an Encoded driver (strings and bytes) into the typed service. The driver contract's reset operation is the batched resetAddresses(addresses), so a hand-written driver must implement that form. A custom registerReplyHandler must register its handler as soon as the effect starts; the fresh-reply path above depends on it. The contract also includes deleteProcessed({ entityType, completedBefore, limit }), used by MessageRetention: delete, atomically, up to limit requests of that entity type whose WithExit reply id is timestamped before completedBefore (Unix milliseconds), with every message and reply sharing their request id, and return the count; rows locked by another transaction may be left for a later call. noop implements it as a no-op that returns 0. SqlMessageStorage.makeEncoded({ prefix? }) returns the SQL Encoded driver on its own (after running migrations) when you want to wrap or compose it; SqlMessageStorage.makeEncodedStorage({ prefix? }) does the same without migrations or startup SQL.
Without MessageStorage (noop/layerNoop), completed request ids are not retained. Redelivering a request id that already completed re-runs it instead of failing with AlreadyProcessingMessage — that dedup guarantee needs real storage.
Reach for it when you mark RPCs Persisted. Pick SqlMessageStorage in production, layerMemory in tests.
Bounds the storage of a persisted entity. MessageStorage keeps every persisted request and its replies so that duplicates get the stored answer and interrupted work can resume; for a long-lived entity type that table only grows. MessageRetention.make({ entity, retention, interval?, shardGroup? }) returns a Layer<never, never, Sharding | MessageStorage> that registers a singleton (named effect/cluster/MessageRetention/<entity type>) which deletes the entity type's completed requests once their final reply is older than retention.
Self-contained source · Type-checked
ts
import { Effect, Layer, Schema } from "effect"import { ClusterSchema, Entity, MessageRetention } from "effect/cluster"import { Rpc } from "effect/rpc"const PayslipMailer = Entity.make("PayslipMailer", [ Rpc.make("Send", { payload: { payslipId: Schema.String }, primaryKey: ({ payslipId }) => payslipId })]).annotateRpcs(ClusterSchema.Persisted, true)// Keep a sent payslip's request and reply for 30 days, so retries and// duplicate deliveries inside that window still return the stored reply.const PayslipMailerLive = Layer.mergeAll( PayslipMailer.toLayer({ Send: () => Effect.void }), MessageRetention.make({ entity: PayslipMailer, retention: "30 days" }))
What a run deletes. Every interval (default one minute) the singleton deletes, in batches of 1000 until a batch comes back short, each request whose WithExit reply is older than retention, together with its acknowledgements, interrupts, and replies. Running requests, and requests reset with MessageStorage.clearReplies, are kept. A failed run is logged as a warning and retried at the next interval.
Deleting forgets the dedup key. A request sent again with the same primary key after deletion is a new request and runs the handler again. Choose a retention longer than any client retry window and any reader of stored replies.
Not for workflows or ClusterCron. Their entities rely on stored replies to know which steps already ran; deleting them would re-run work.
Deploy it everywhere. The singleton runs in shardGroup (default "default"), not the entity's shard group; include the layer on every runner that can own that group so the cleanup survives shard moves.
SQL storage.SqlMessageStorage adds a retention index through its migrations. On MySQL the delete needs MySQL 8.0.1+ or MariaDB 10.6+ (SKIP LOCKED) and binlog_formatROW or MIXED; otherwise every run fails and is logged. When the delete runs inside a caller's transaction on MySQL before 8.0.20 or on MariaDB, that transaction must be READ COMMITTED or it can deadlock with a concurrent reply.
Needs a real MessageStorage. With noop storage nothing is retained, so there is nothing to delete; the Cloudflare runtime does not provide MessageStorage (see Running on Cloudflare Durable Objects).
Reach for it when a persisted entity type handles an unbounded stream of distinct requests and you can name how long a duplicate must still be recognised.
Distributed unique ids. A Snowflake is a branded bigint packed from a millisecond timestamp, a 10-bit machine id, and a 12-bit per-machine sequence. Globally unique and roughly time-sortable without a central coordinator.
Mental model. Twitter's Snowflake scheme, Effect-native. High bits are time (since a 2025 epoch), middle bits identify the runner, low bits are a per-millisecond counter. Sort by the bigint to sort by creation time. The generator is Clock-backed, never moves time backward (absorbs clock drift), and rolls into the next millisecond if 4096 ids in one millisecond are exhausted.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Snowflake } from "effect/cluster"const program = Effect.gen(function*() { const gen = yield* Snowflake.makeGenerator const raiseEventId = gen.nextUnsafe() // a branded, sortable bigint // Decode it back into its parts whenever you need them — e.g. to learn which // runner stamped a raise event and exactly when. const { timestamp, machineId, sequence } = Snowflake.toParts(raiseEventId) const when = Snowflake.dateTime(raiseEventId) // DateTime.Utc of creation yield* Effect.log(`raise event ${raiseEventId} from machine ${machineId} at ${when}`)})// Provide it as a service with Snowflake.layerGenerator.
Schemas: SnowflakeFromBigInt (branded bigint) and SnowflakeFromString (decodes/encodes via string, for JSON-safe transport).
Reach for it when you need ids that are unique across machines, sortable by time, and cheap to generate — for domain ids where a centralized sequence would be a bottleneck.
A bridge that exposes a clustered entity to the outside world as a normal RPC service or HTTP API. EntityProxy.toRpcGroup(entity) derives an RpcGroup; EntityProxy.toHttpApiGroup(name, entity) derives an HttpApiGroup. Each entity RPC becomes a public operation whose payload gains an entityId, plus a fire-and-forget ...Discard variant.
Normal derived RPC and HTTP request operations include EntityNotAssignedToRunner in their typed error channel. The fire-and-forget ...Discard variants deliberately do not expose that error, so use a normal request whenever assignment acknowledgement matters.
What EntityNotAssignedToRunner means now. Treat it as genuine non-assignment — typically a volatile send that reached a runner which does not own the shard. For a persisted message, the transient states of a rebalance no longer surface as errors:
Situation while a caller awaits a persisted reply
Caller observes
The entity moves to another runner, or is shut down before replying
Nothing — the caller keeps waiting and receives the reply from message storage once the next owner has processed the request.
The local runner (the one hosting the caller) is shutting down
The call is interrupted, not failed: the request is already durable and will be served by the next owner. Do not map this interrupt to a domain error or a retry.
The runner is at maxResidentEntities
The send succeeds; the message waits in storage for a free slot.
Volatile sends have no storage to fall back on, so they still fail fast: EntityNotAssignedToRunner, RunnerUnavailable, or MailboxFull.
Mental model. The entity protocol is internal — it assumes the caller is inside the cluster. EntityProxy wraps it so an external client can hit a plain HTTP endpoint or RPC method. The generated handler (from EntityProxyServer) reads entityId, grabs the entity client, and forwards the call.
Self-contained source · Type-checked
ts
import { Layer, Schema } from "effect"import { ClusterSchema, Entity, EntityProxy, EntityProxyServer } from "effect/cluster"import { Rpc, RpcServer } from "effect/rpc"const Department = Entity.make("Department", [ Rpc.make("RecordRaise", { payload: { id: Schema.String, employeeId: Schema.String, amount: Schema.BigDecimal }, primaryKey: ({ id }) => id, success: Schema.BigDecimal })]).annotateRpcs(ClusterSchema.Persisted, true)// Derive a public RpcGroup from the entity...class DepartmentRpcs extends EntityProxy.toRpcGroup(Department) {}// ...and serve it: the proxy handlers forward each call to the department client.const ServerLayer = RpcServer.layer(DepartmentRpcs).pipe( Layer.provide(EntityProxyServer.layerRpcHandlers(Department)))
Reach for it when you have entities behind the cluster wall and need to expose them to external callers over HTTP or RPC without hand-writing a forwarding controller per method.
Distributed scheduled jobs. ClusterCron.make turns a Cron.Cron schedule into a Layer that coordinates one recurring job across the whole cluster rather than independently on every node.
Mental model. Singleton + Entity in combination. A singleton schedules the first run; each run is delivered as a persisted entity message whose DeliverAt time is the next cron tick, and the handler schedules the one after it. Persistence, single ownership, and message deduplication keep scheduling cluster-wide and failover-safe, but handler execution has at-least-once delivery semantics around crashes. Make the job effect idempotent or transactional. skipIfOlderThan stops it from stampeding through missed runs after downtime.
Self-contained source · Type-checked
ts
import { Cron, Effect } from "effect"import { ClusterCron } from "effect/cluster"// Kick off the quarterly merit-review cycle at 09:00 on the first day of Jan,// Apr, Jul, and Oct — coordinated cluster-wide and delivered durably.// Cron.parseUnsafe throws on a malformed expression; use Cron.parse for a Result.const QuarterlyReviewKickoff = ClusterCron.make({ name: "quarterly-review-kickoff", cron: Cron.parseUnsafe("0 9 1 1,4,7,10 *"), // ... replace this log with the work that creates the MeritCycle and fans out tasks. execute: Effect.log("opening the merit-review cycle: seeding budgets, notifying managers..."), skipIfOlderThan: "6 hours"})
Read the scheduled time from ClusterCron.CurrentScheduledTime inside execute; it is available in both modes.
calculateNextRunFromPrevious: true runs one chain per job. Every run is processed by a single executor entity for the cron job, so a restart does not start a second chain: runs never overlap and missed runs catch up in order. A failing run is retried until it succeeds or is older than skipIfOlderThan, and blocks later runs while it is retried.
Failures scheduling the first run are logged and retried, so a transient error at startup does not leave the cron stopped.
Migration: with calculateNextRunFromPrevious: true, Entity.CurrentAddress inside execute no longer identifies the scheduled time (every run shares the executor address); read ClusterCron.CurrentScheduledTime instead.
Reach for it when you want durable, deduplicated, failover-safe cron scheduling in a multi-node deployment and can make the scheduled effect safe for at-least-once delivery.
The configuration service for how this runner participates: its address, which shard groups it joins, how many shards per group, lock timing, mailbox and passivation limits, poll intervals, and health-check cadence.
Mental model. One config object per process, provided as a layer. Most important field: runnerAddress — Some means "I host shards"; None means client-only node. runnerListenAddress is the local bind address, defaulting to runnerAddress; from the environment it resolves to None unless listenHost is set, even when listenPort is valid — supply listenHost to configure a distinct listen address. Other fields tune behavior: shardsPerGroup (granularity of distribution), entityMaxIdleTime (default passivation), entityMailboxCapacity, *Interval timings, and shard-lock settings for SQL-coordinated ownership.
Self-contained source · Type-checked
ts
import { ShardingConfig } from "effect/cluster"// Programmatic config — sensible for tests / explicit setups.const ConfigLayer = ShardingConfig.layer({ shardsPerGroup: 300, entityMaxIdleTime: "10 minutes", entityMailboxCapacity: 4096})// Or load it from the environment (RUNNER_ADDRESS, SHARDS_PER_GROUP, ...).const FromEnv = ShardingConfig.layerFromEnv()
Tip:layerDefaults gives stock config; layerFromEnv reads a Config description for env-var-driven containers. Transport entrypoints default to layerFromEnv internally.
Note:runnerHealthCheckInterval (default one minute) paces the checks that remove unhealthy runners from shard assignments. They run on one runner, the host of the runner-health singleton, which therefore cannot detect its own crash: that runner leaves assignments only when runner storage stops listing it — for SqlRunnerStorage, once its last heartbeat is older than shardLockExpiration. Lowering the interval speeds up detection of other runners' crashes only; to bound the singleton host's case, lower shardLockExpiration, at the cost of less tolerance for slow lock storage.
Every limit below is per runner. Environment names are the constant-case form of the field (MAX_RESIDENT_ENTITIES, ENTITY_MAILBOX_CAPACITY, …).
Field
Default
What happens at the limit
maxResidentEntities
10_000
No new entity is spawned. The storage read loop stops admitting messages for new addresses (they stay in storage until a slot frees up) and keeps serving resident ones; a volatile send to a new address fails with MailboxFull; a persisted send still succeeds. "unbounded" restores the old behavior and can only be set programmatically — the environment form accepts positive integers only.
unprocessedMessageBatchSize
1024
Upper bound on messages read from storage in one poll; a full batch that delivered work triggers an immediate follow-up read instead of waiting for the poll interval.
entityMailboxCapacity
4096
A request to a resident entity whose mailbox is full fails with MailboxFull (volatile) or stays in storage for redelivery (persisted).
entityMaxIdleTime
1 minute
Idle instances are passivated, which frees a residency slot.
entityTerminationTimeout
15 seconds
Longest wait for an entity to terminate during shutdown or rebalance (chosen to fit inside Kubernetes' default grace period).
runnerJoinDebounce
0 (off)
Joining runners wait until the healthy runner set has been quiet for this long before receiving shards (see Rebalance and shutdown behavior).
entityMailboxMetrics
false
Enables the per-entity entityMailboxSize gauge; the per-type entityMailboxSizeMax gauge is always on.
Size maxResidentEntities from memory, not from traffic. It is a safety valve against an activation storm (for example a cold start draining a large backlog); when it engages, persisted work is delayed rather than lost, so alert on the entities gauge from ClusterMetrics approaching the cap and on storage backlog age.
Reach for it when tuning cluster behavior, setting a runner's address/groups, or flipping a node into client-only mode.
Note: Merge your entity layers, provide a cluster layer (bundles Sharding + Runners + storage + config), and launch. Swap NodeClusterSocket.layer() for TestRunner.layer to run the same entities single-process in a test.
Fragment · Type-checked
ts
import { Layer } from "effect"import { NodeClusterSocket, NodeRuntime } from "@effect/platform-node"import type { SqlClient } from "effect/sql"import { Sharding } from "effect/cluster"declare const SqlClientLayer: Layer.Layer<SqlClient.SqlClient>declare const DepartmentLayer: Layer.Layer<never, never, Sharding.Sharding>// Production: a real socket runner backed by SQL storage.const ClusterLayer = NodeClusterSocket.layer().pipe(Layer.provide(SqlClientLayer))const AppLayer = Layer.mergeAll(DepartmentLayer).pipe(Layer.provide(ClusterLayer))Layer.launch(AppLayer).pipe(NodeRuntime.runMain)
The supporting cast. Smaller modules the headline acts lean on — addresses and ids, transport variants, durable backends, errors, metrics, and wire envelopes. Rarely imported directly, but knowing them makes type errors legible.
The full routing target for one entity instance: entityType + entityId + shardId, bundled as a Schema.Class. Used by messages, persisted envelopes, and entity managers. Read the current one inside a handler via Entity.CurrentAddress.
A branded string — the routing key sharding hashes to pick a shard. EntityId.make("dept-eng") brands a raw string. The "which instance" half of an address.
A branded string naming a family of entities (e.g., the "Department" in Entity.make("Department", ...)). Distinguishes one kind of actor from another before any id is considered.
A host + portSchema.Class identifying how to reach a runner, with structural equality, hashing, and a stable primary key. RunnerAddress.make("10.0.0.4", 34431).
The address of a shard inside a group: a string group + numeric id, rendered as group:id at storage/routing boundaries. Entity ids hash into these; runners own sets of them.
The runtime address of a registered singleton: its name paired with the ShardId chosen from that name and shard group. Used in registration events and local fiber tracking.
Server side of the runner protocol: receives ping/notify/request/stream/envelope messages from other runners and forwards them into local Sharding. layer is the full server; layerClientOnly for nodes that send but do not serve.
A volatile (non-Persisted) request that is interruptible is bound to the calling runner's connection: when that caller disconnects, the entity handler is interrupted and its mailbox slot is released, instead of running on for nobody. Persisted requests and Uninterruptible RPCs are unaffected and still run to completion, so a caller that reconnects must not assume a volatile call it lost was abandoned before its side effects.
Decides whether a runner should be treated as alive, so Sharding knows when to move its shards. layerNoop (always alive), layerPing (heartbeat-based), and layerK8s (reads pod readiness).
A single-process cluster layer: Sharding + no-op runner comms + no-op health + SQL message storage + env config, with SQL or in-memory runner storage. For embedded or small single-node deployments that still want durable entities. Requires a SqlClient and a Digest.Digest service (for example NodeCrypto.layerDigest or Digest.layerWebCrypto).
Runs runner RPCs over a raw socket transport on a provided SocketServer. layer serves and provides clients; layerClientOnly dials without hosting shards. The engine under NodeClusterSocket.
Connects runner RPCs to HTTP and WebSocket transports — client protocol layers for dialing runner addresses, effects to serve handlers, and route layers for an HttpRouter. The engine under NodeClusterHttp. Client URLs are built from the runner address plus the configured path, inserting a / only when the path lacks one, so a slash-prefixed path such as /cluster/rpc is used as written (earlier builds produced a doubled slash).
The smallest useful cluster runtime for tests: Sharding over in-memory message + runner storage, no-op transport, always-healthy checks. Exercise entity registration, routing, and mailbox persistence with no RPC servers or database — just provide TestRunner.layer.
A thin HTTP client for the in-cluster Kubernetes API, using the mounted service-account token. Backs the K8s-aware health check and pod helpers (list pods, create pod) for runners that manage their own infrastructure.
Type-only Kubernetes declarations used by the cluster helpers: the transitive closure of Pod (spec, containers, volumes, affinity, status, metadata), vendored from kubernetes-types 1.30 so the kubernetes-types dependency could be dropped. K8sHttpClient.makeCreatePod takes a K8sTypes.Pod. It carries no runtime code and is not a general Kubernetes client model — import it when you construct a pod spec for the cluster helpers, not as a substitute for a full Kubernetes SDK.
The production MessageStorage: encodes envelopes and reply chunks into SQL tables, redelivers unprocessed messages after restart, deduplicates by primary key, and replays reply chunks until acknowledged. Ships migrations and an optional table prefix (layerWith({ prefix }); default cluster). Provide via layer with any @effect/sql-* client; the layer also requires Digest.Digest (from effect/crypto/Digest), used to hash deduplication keys longer than the 255-character message_id column. The platform cluster entrypoints supply it. makeEncoded({ prefix? }) exposes the SQL MessageStorage.Encoded driver by itself for custom storage composition, and makeEncodedStorage({ prefix? }) builds the same driver without migrations or startup SQL.
Migration:SqlMessageStorage and SingleRunner require Digest.Digest instead of the removed Crypto.Crypto service. Shorter keys are still stored as plaintext and hashed keys keep the SHA-256 hex form, so existing rows stay compatible.
Supported dialects include SQL Server: claims and duplicate checks use valid T-SQL, and its tables use filtered unique indexes and NVARCHAR(MAX); reply and delete statements force the request-id lookup indexes, and a migration creates any that an earlier name-only check skipped because a same-named index existed on another table. Another migration adds the index that MessageRetention deletes through. On SQLite drivers that return numbers (including Cloudflare Durable Objects), message ids are read without precision loss. Changing the prefix after deployment points the runtime at a different set of tables, including the migration history.
For separate deployment and runtime database roles, run SqlMessageStorage.layerMigrations({ prefix }) using the schema-owner connection, then provide layerStorage({ prefix }) using the runtime connection. layerStorage performs no DDL or startup schema checks; migrations must already have succeeded. layer, layerWith, make, and makeEncoded still migrate first. Migration failures become defects. On PostgreSQL select the schema through search_path, not a schema-qualified prefix (which produces an invalid index name).
SQL-backed runner registration and shard-ownership: records runners, health flags, machine ids, and shard locks so multiple processes coordinate who owns each shard. Uses advisory locks on Postgres/MySQL when enabled. On PGlite (detected through SqlClient.driver), it uses lock-table rows and does not reserve PGlite's only connection.
SqlRunnerStorage likewise separates layerMigrations({ prefix }) from layerStorage({ prefix }): use an owner connection to migrate before starting the DML-only runtime. Keep prefixes identical in deployment and runtime. The normal layer / layerWith and make constructors still run migrations.
Note: PostgreSQL advisory shard locks are namespaced by the SqlRunnerStorage table prefix. Changing the prefix on a running deployment points lock keys at a different namespace; stop the whole cluster before rolling out such a change, since mixing lock schemes can allow split ownership.
Note: Advisory locks live on a reserved connection. While lock storage is unhealthy, the liveness probe runs on the shared pool instead of that reserved connection, so a hung reserved connection cannot stall shard-lock recovery, and failed probes are logged as warnings instead of being swallowed. With shardLockDisableAdvisory (row-based locks instead of advisory locks), acquisition, refresh, and bulk release all take their row locks in a consistent order to avoid lock-order deadlocks. A frozen runner loses its advisory locks after shardLockExpiration: on PostgreSQL 14+ the lock connection sets idle_session_timeout, and on MySQL it sets wait_timeout; both settings are restored before the connection returns to the pool. Lock refresh only confirms locks held by the current lock session, so after the lock connection is replaced, shards held by the previous session are reported lost rather than silently reacquired. On Vitess, releasing all shards no longer leaves stale lock holders behind. Locks are leases, not fencing: a paused former owner can still issue a write after takeover, so protect external writes with idempotency keys or a version check in the sink.
The typed service contract for runner registration and shard-lock state (which runners exist, their machine ids, which locks they hold). layerMemory for single-process/tests; SqlRunnerStorage implements it for real clusters.
Annotations that add cluster behavior to RPCs and entities without touching payload/result schemas: Persisted (durable delivery), WithTransaction, Uninterruptible (true, "client", or "server"), ShardGroup (route ids to a group), ClientTracingEnabled, and Dynamic (compute server-side annotations from the decoded request). Attach with .annotate / .annotateRpcs. A WithTransaction value computed through Dynamic is kept when the entity re-runs a request, after a handler defect or after an interrupt that a server-uninterruptible persisted request ignores.
ClusterSchema.Abandon is different: it is not something you attach. It marks the interruption a runner raises when it abandons a persisted request that must continue under another owner (shutdown, shard loss). ClusterWorkflowEngine recognizes that mark and treats the interrupt as an abandoned run attempt — see Workflows & Durable Execution. Application code should let such an interrupt propagate rather than catching it.
ClusterSchema.InterruptOnTermination opts an RPC into interruption as soon as entity termination starts, instead of waiting for normal draining. Persisted requests resume under the next owner without storing an interrupt reply. Server-side Uninterruptible takes precedence; do not use this annotation to promise cancellation of an uninterruptible external write.
Structured, schema-backed failures of the cluster runtime: EntityNotAssignedToRunner, MailboxFull, AlreadyProcessingMessage, PersistenceError, MalformedMessage, RunnerUnavailable, RunnerNotRegistered. Catch with Effect.catchTag.
Error
Raised when
Usual response
EntityNotAssignedToRunner
The addressed shard is genuinely not owned by the runner that received a volatile send. Transient rebalance states of a persisted message no longer produce it (see EntityProxy).
Retry after a short delay; refreshAssignmentsInterval defaults to 3 seconds.
MailboxFull
An entity's mailbox is at entityMailboxCapacity, or the runner is at maxResidentEntities and a volatile send targets a new address.
Back-pressure the caller, or mark the RPC Persisted so it waits in storage instead.
RunnerUnavailable
The owning runner could not be reached.
Bounded retry; a volatile message may not have been delivered.
PersistenceError
Message storage failed.
Treat as infrastructure failure; do not assume the message was saved.
Standard metrics the runtime records while running: active entities, singletons, registered runners, runnersHealthy, acquired shards, shardsReleasing (shards this runner is still releasing), the shardReleaseDuration timer, and entityMailboxSizeMax (largest resident mailbox per entity type). entities and the mailbox gauges are read when metrics are snapshotted and are removed when the entity manager shuts down. The opt-in entityMailboxSize gauge reports each resident entity's mailbox; enable it with ShardingConfig.entityMailboxMetrics or the mailboxMetrics option of Entity.toLayer, and its series is removed when the entity is released. Wire to a metrics exporter for cluster visibility.
Entity RPC server span names contain the entity type, not its id (for example WorkflowEntity.Run). The id remains in entity.id as an attribute. Update dashboards that parsed entity ids from span names, and apply the usual attribute privacy and cardinality policy.
Events emitted by Sharding.getRegistrationEvents when the local runner registers an entity (EntityRegistered) or singleton (SingletonRegistered). Await at startup to confirm entities and singletons are live, or assert on them in tests.
The transport envelopes entities exchange: a Request wraps a decoded payload with target address, RPC tag, request id, headers, and tracing context; AckChunk acknowledges streamed reply chunks; Interrupt cancels an in-flight request. Includes JSON codecs and storage primary-key helpers.
The message shapes moved through the cluster, in Incoming and Outgoing variants (request, envelope, interrupt). Carries entity requests and control messages between callers, storage, transports, and handlers, with serialize/deserialize helpers matched to RPC schemas.
Values produced by clustered RPC execution: a final WithExit carrying the RPC Exit, or a streaming Chunk carrying a non-empty batch of successes. ReplyWithContext carries encoding services; serialization helpers move replies through storage or transport.
A protocol for message payloads that carry their own scheduled delivery time. Implement the DeliverAt.symbol method to return a target DateTime, and durable storage will hold the message until then. The mechanism behind ClusterCron's timed runs.
The handler side of EntityProxy: layerRpcHandlers(entity) and layerHttpApi(api, name, entity) implement the derived RPC/HTTP operations by reading entityId, calling the entity client, and forwarding the payload — including the discard variants. Both layers require Sharding plus the entity RPCs' server-side and client-side schema services (Rpc.ServicesServer and Rpc.ServicesClient), because the proxy decodes the public request and then re-encodes it as an entity client. If a payload or result schema needs a service to encode or decode, provide it to the proxy layer too.
Keeps a long-lived resource alive across routine entity restarts, tied to an entity address. make({ acquire, idleTimeToLive }) wraps it with a close scope that survives passivation; makeK8sPod manages a pod. Pairs with Entity.keepAlive.
Runs durable Workflow executions on top of cluster sharding and message storage. Adapts WorkflowEngine so executions, activities, deferred completions, resumes, interrupts, and durable clock wakeups all become persisted cluster entity messages — durable, distributed orchestration for multi-step workflows. Provide its layer to back a workflow runtime with the cluster.
Its entities passivate after a fixed ten seconds. Workflow and durable-clock entities ignore entityMaxIdleTime: a completed or suspended execution releases its residency slot quickly and is rebuilt from storage when its next message arrives. Do not keep process-local state in a workflow body and expect it to survive a suspension.
A transient interrupt is an abandoned attempt, not a failure. When the owning runner shuts down or loses the shard, the run stops with nothing persisted, without compensation and without resuming a parent, and replays on the next owner.
Deferred completions survive a handover. A DurableDeferred completion that reaches a new owner before its first local run of the execution is retained for that run, and the wake-up waits until the current run's reply is persisted, so a completion racing a shard move is not lost. See DurableDeferred.
Transient storage failures are retried, not recorded. A PersistenceError while a running workflow sends an activity, reads its reply, completes a DurableDeferred, schedules a DurableClock (the wake-up time is computed once, before retrying), or starts a child workflow is retried with exponential backoff (200 ms growing 1.5×, capped at one minute, without an attempt limit) instead of becoming a workflow defect; a save that committed but was not acknowledged is deduplicated, so the activity still runs once. Reading a pending interrupt signal is retried at most three times. A PersistenceError from a call made outside a workflow (starting one from an HTTP handler, say) still fails that call.
A runner that lost its shard cannot erase newer history. Resetting a suspended activity result for a retry deletes only the exact reply it read, so a stale former owner cannot delete a result written by the new owner and run the activity again.
An interrupted child wakes its parent. When a suspended child workflow is interrupted, its parent is resumed and the parent's awaited childWorkflow.execute(...) call dies with a defect (<Child>.execute: execution "<id>" was interrupted) rather than an interrupt, so the parent completes instead of replaying; recover with Effect.catchDefect or Effect.exit if the parent should continue. An abandoned run attempt of the child does not wake the parent.
Forced shard release does not wedge reacquisition. A forced release that interrupts a resume waiting on its active run no longer blocks the shard from being reacquired.
Residency applies to workflows too. Each running execution occupies an entity slot, so size maxResidentEntities for the number of executions a runner may have active at once.
Tip: Use cluster entities when work is naturally addressed to a sharded identity and needs single-runner ownership. For the workflow definition, activity, retry, and durable-clock model that ClusterWorkflowEngine distributes, continue with Workflows & Durable Execution.
Event sourcing stores immutable facts (decisions that happened) in an append-only log and derives current state by replaying them. The effect/eventlog modules provide schema-typed events, a durable journal, handlers that fold events into projections, and a sync protocol (optionally end-to-end encrypted) for multi-device convergence.
Note:Event + EventGroup define the contract: schema-typed events grouped together. EventLog is the runtime you write through — runs the matching handler, then commits to the journal. EventJournal (and SqlEventJournal) is the storage layer. EventLogRemote connects a local log to a server; EventLogServer (with Encrypted/Unencrypted variants, backed by SqlEventLogServer*) is that server; EventLogEncryption provides end-to-end encryption; EventLogSessionAuth handles identity; EventLogMessage is the wire protocol.
Event.make({ tag, primaryKey, payload, success, error }) defines one kind of fact. tag is the stable identifier; primaryKey extracts the aggregate/entity id from the decoded payload; payload, success, and error are Schemas. The payload Schema drives the SchemaBinary encoding (event.payloadSchemaBinary) used for journal entries and replication, so the payload schema is a persisted wire contract: evolve it compatibly.
An Event is the durable contract shared by writers, handlers, the journal, and remote replicas. primaryKey groups related events for projection and compaction. Events are typically created via EventGroup.empty.add(...) rather than make directly.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { Event } from "effect/eventlog"// A single fact: "a merit raise was approved for an employee".const RaiseApproved = Event.make({ tag: "RaiseApproved", payload: Schema.Struct({ employeeId: Schema.String, newSalary: Schema.BigDecimal }), primaryKey: (p) => p.employeeId // groups all comp events for one employee})
Tip:Event.addError(event, schema) widens an event's error channel by unioning in another error schema.
Use Event when naming an atomic, immutable recorded decision with a payload, an entity key, and typed handler outcomes.
A collection of related events forming a contract. Start from EventGroup.empty and chain .add({ tag, primaryKey, payload, ... }) per event. Pure description — no writes, no execution — handed to EventLog.schema (to build a writer) and EventLog.group (to attach handlers). Tracks every event's tag and payload at the type level, enabling exhaustive handler checking.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { EventGroup } from "effect/eventlog"// A bounded context: every compensation decision we record for an employee.export const CompEvents = EventGroup.empty .add({ tag: "RaiseApproved", payload: Schema.Struct({ employeeId: Schema.String, newSalary: Schema.BigDecimal }), primaryKey: (p) => p.employeeId }) .add({ tag: "GrantIssued", payload: Schema.Struct({ employeeId: Schema.String, shares: Schema.Natural }), primaryKey: (p) => p.employeeId }) .add({ tag: "BandChanged", payload: Schema.Struct({ employeeId: Schema.String, level: Schema.String }), primaryKey: (p) => p.employeeId })
Note:EventGroup.empty.addError(schema) adds an error schema to every event in the group at once.
Use EventGroup to define the full set of events a feature or aggregate can emit as one typed contract.
The runtime service you write events through. Stitches together event groups, handlers, a journal, a local identity, optional remote replicas, and reactivity hooks. EventLog.schema(...groups) builds the typed writer contract; EventLog.group(group, (handlers) => ...) registers handlers; EventLog.layer(schema, handlersLayer) assembles the runtime.
Writing is handler-first: log.write({ schema, event, payload }) runs the matching handler first, and the journal entry is committed only if the handler succeeds. Handlers update projections; a failed projection means the decision is not recorded. Atomicity between projection work and journal insertion depends on the backend and services used by the handler: SqlEventJournal wraps the operation in the SqlClient transaction, whereas the IndexedDB journal runs the arbitrary handler before a separate IndexedDB write. Get a typed write function with EventLog.makeClient(schema) — it takes one { event, payload } object — or call log.write on the service directly. log.writeMany (and EventJournal.writeMany) writes a batch of local events under one lock, one handler transaction, and one journal commit; within a process, clock-based entry ids are strictly ascending.
Migration: The function returned by EventLog.makeClient used to take positional (event, payload) arguments; call it with client({ event: "RaiseApproved", payload }) instead.
Self-contained source · Type-checked
ts
import { BigDecimal, Effect, Layer, Ref, Schema } from "effect"import { EventGroup, EventJournal, EventLog, EventLogEncryption } from "effect/eventlog"// 1. The contract.const CompEvents = EventGroup.empty.add({ tag: "RaiseApproved", payload: Schema.Struct({ employeeId: Schema.String, newSalary: Schema.BigDecimal }), primaryKey: (p) => p.employeeId})const schema = EventLog.schema(CompEvents)// 2. Handlers — run before the entry commits; this is where the salary projection updates.const handlersLayer = (salaries: Ref.Ref<ReadonlyMap<string, BigDecimal.BigDecimal>>) => EventLog.group(CompEvents, (handlers) => handlers.handle("RaiseApproved", ({ payload }) => Ref.update(salaries, (m) => new Map(m).set(payload.employeeId, payload.newSalary)) ) ).pipe(Layer.provide(EventLog.layerRegistry))// 3. Assemble the runtime: schema + handlers + a journal + an identity.const logLayer = (salaries: Ref.Ref<ReadonlyMap<string, BigDecimal.BigDecimal>>) => EventLog.layer(schema, handlersLayer(salaries)).pipe( Layer.provide(EventJournal.layerMemory), Layer.provide( Layer.effect(EventLog.Identity, EventLog.makeIdentity).pipe( Layer.provide(EventLogEncryption.layerSubtle) ) ) )// 4. Append a comp decision, and the handler fires; the entry is now in the journal.const program = Effect.gen(function*() { const log = yield* EventLog.EventLog yield* log.write({ schema, event: "RaiseApproved", payload: { employeeId: "emp-1", newSalary: BigDecimal.fromStringUnsafe("185000") } }) const entries = yield* log.entries yield* Effect.log(`audit log has ${entries.length} entries`)})
Tip:EventLog.groupReactivity(group, keys) registers reactivity invalidation keys so the Reactivity system can refresh queries when matching events land; invalidations are flushed once per replayed remote batch. EventLog.groupCompaction(group, effect) registers a compactor: during replay, entries for one primary key are folded into a single replacement entry. EventLog.groupBatchCompaction compacts across primary keys and makes you forward or drop undecodable entries explicitly; both give the compactor forward(entry) to keep an entry unchanged at its original position. log.destroy wipes a store.
Replay is all-or-nothing per batch. A remote batch's handlers run in one EventLog.HandlerTransaction; if an entry fails to decode or its handler fails, the batch fails and is retried rather than being committed without its projection. A conflict is a stored entry for the same event and primary key with a strictly greater id, and every journal orders conflicts by entry id, so replicas converge.
Use EventLog for journal-backed, transactional, local-first event-sourced recording with reactive projections.
Mutable rows that converge across replicas, built on one event per row type with set, patch, and remove payloads. EventRow.make(tag, { key, schema, error? }) returns a value to pass to EventGroup.add; its set(row), patch(key, fields), and remove(key) return { event, payload }, which spreads into log.write, is an item of writeMany, and is the argument of a makeClient client. EventRow.handler(row, { set, patch, remove }) resolves newer conflicts per top-level field (last writer wins; nested values are atomic) and calls at most one storage callback; EventRow.compaction drops entries that newer ones shadow.
Keys.key names a required string-like field, or declares several fields ({ fields: ["parentId", "id"], derive? }) for a composite or derived key. Key fields cannot be patched; to move a row, remove it and set it again.
The callback contract is what makes it converge.set replaces the whole row, creating it if missing; patch updates an existing row and does nothing if it is missing (upserting can resurrect removed rows on some replicas); remove is idempotent. Empty patches skip the callback but are still journaled and synced.
Never compact row events with groupCompaction or groupBatchCompaction — they run before stored conflicts are read and lose writes. Use EventRow.compaction.
Schema evolution is constrained. Replay decodes old entries with the current schema: new fields must accept absence (Schema.withDecodingDefaultKey), a type change must keep the encoded type, and renames, narrowing, a new required field, or a changed key break old entries.
The storage engine for entries. Records committed entries, exposes them for replay, publishes local changes to subscribers, and tracks per-remote sequence metadata for exchange with other journals. Ships EventJournal.layerMemory (in-process, ephemeral) and EventJournal.layerIndexedDb (persistent in the browser). The IndexedDB journal upgrades existing databases automatically: version 3 adds an [event, primaryKey, id] index so remote writes read only the stored entries that can conflict, and upload progress is checkpointed by insertion order, so entries imported later with older ids are still forwarded. After that upgrade, entries the remote has not confirmed may be uploaded once more.
The append-only ledger underneath EventLog. An Entry carries a time-ordered EntryId (UUID v7 from a hybrid logical clock), the event tag, the primary key, and SchemaBinary-encoded payload bytes. writeFromRemote imports entries from another journal and deduplicates by id, enabling convergence between peer journals.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { EventJournal } from "effect/eventlog"const inspect = Effect.gen(function*() { const journal = yield* EventJournal.EventJournal const entries = yield* journal.entries // every committed comp decision, in order return entries.map((e) => e.event)}).pipe(Effect.provide(EventJournal.layerMemory))
Note: Entry ids are time-ordered (UUID v7) and generated from a hybrid logical clock: the memory, IndexedDB, and SQL journals give every local write an id after the latest id in their store, so a local write sorts after everything already committed even when the local clock is behind (IndexedDB and SQL read that id from the store, one extra read per writeMany). A clock running ahead is not clamped; an imported id more than 24 hours ahead of the local Clock logs a warning, and a store holding an id at the end of the UUID v7 range makes local writes fail with EventJournalError. Remote ids (makeRemoteIdUnsafe) identify peer journals for sequence tracking.
Custom journals. An EventJournal implementation must also provide entriesById (used to skip decrypting remote entries the journal already stores), writeMany, and writeRemoteAcks (record upload acknowledgements, advancing nextRemoteSequence only across contiguous sequences). writeFromRemote hands its effect the whole batch with conflicts read up front, and a repeated entry within one remote delivery keeps its first copy. withRemoteUncommited(remoteId, f) hands f the non-empty list of entries not yet sent to that remote and returns Option.some(result); when nothing is uncommitted, f is not called and the result is Option.none(). A custom EventJournal implementation must keep that contract (the sync loop relies on it to skip empty remote writes), advance the remote cursor only when f succeeds, and fail with exactly the error f failed with.
Use layerMemory for tests, layerIndexedDb for offline clients, or SqlEventJournal on a server.
The crypto service for end-to-end-encrypted replication. Encrypts local journal entries into remote batches, decrypts incoming encrypted changes, hashes byte data, and generates event-log identities. EventLogEncryption.layer builds it from the effect/cryptoAead, Digest, and SecureRandom services in context (so Node apps can use the NodeCrypto layers); EventLogEncryption.layerSubtle supplies the Web Crypto layers on the WebCrypto reference (browsers, Node, edge).
Enables syncing through a backend that never sees plaintext. Keys are derived from the local EventLog.Identity (public key plus redacted private-key material); the server stores ciphertext keyed by public key and only the owning devices can decrypt. EventLog.makeIdentity uses this service to mint a fresh identity.
Fragment · Type-checked
ts
import { Effect } from "effect"import { EventLogEncryption } from "effect/eventlog"const roundTrip = Effect.gen(function*() { const enc = yield* EventLogEncryption.EventLogEncryption const identity = yield* enc.generateIdentity // Batches authenticate the store id and their plaintext entry ids. const batches = yield* enc.encrypt(identity, "comp-audit", entries) // ...ship ciphertext to the comp server; only this HRBP's devices can decrypt it... return { batches: batches.length, entries: batches.reduce((n, b) => n + b.entryIds.length, 0) }}).pipe(Effect.provide(EventLogEncryption.layerSubtle))declare const entries: ReadonlyArray<import("effect/eventlog").EventJournal.Entry>
Deployment warning: Entries are encrypted in batches of up to 100 entries or about 256 KB of payload — one AES-GCM call per EncryptedBatch{ entryIds, iv, encryptedBatch } — and encrypted servers store and stream those batches. This replaced the per-entry EncryptedEntry format without migration: upgrade encrypted clients and servers together, and start encrypted servers on fresh storage, because existing per-entry rows are not read. Existing identities and derived signing keys are unchanged.
Migration:EncryptedEntry / EncryptedRemoteEntry became EncryptedBatch / EncryptedRemoteBatch, WriteEntries.encryptedEntries became batches, encrypt / decrypt take the store id, and EventLogEncryption.sha256String is gone — use digest.digestHex(Digest.sha256, bytes) from effect/crypto/Digest.
Use layerSubtle with the encrypted remote/server pair when the sync server is untrusted and data must stay private.
The client that connects a local event log to a remote replica. Writes local entries to a server, streams remote changes back from a given sequence number, and waits for local identity authentication. Two constructors: EventLogRemote.makeEncrypted / layerEncrypted (browser/edge, untrusted network) and makeUnencrypted / layerUnencrypted (trusted transports or tests).
Runs a background sync loop: push new local entries, pull new remote ones (via writeFromRemote), keeping journals converging. Encrypted mode encrypts before sending and decrypts on receive using EventLogEncryption, skipping entries the local journal already stores. The server acknowledges writes instead of echoing them back to the writing connection, and a reconnect resumes from the journal's current sequence. Chunked writes keep up to four parts in flight.
Deployment warning: The acknowledgement protocol is a breaking wire change: upgrade clients and servers together; mixed versions are unsupported.
Encrypted remote compaction. When the encrypted server's Storage provides compaction (SqlEventLogServerEncrypted.layerStorage({ compaction }) with EventLogServerEncrypted.CompactionOptions: grace 30 days, lag 24 hours, stageTtl 10 minutes, thresholdFloor 1,000 entries, sweepInterval 1 hour), the server advertises it in its hello response and an encrypted client compacts on the server's behalf — the server still never sees plaintext. EventLogRemote.layerEncryptedWith({ compaction: false }) builds a client that never calls the compaction RPCs.
Self-contained source · Type-checked
ts
import { Layer } from "effect"import { EventLogRemote } from "effect/eventlog"// Add an end-to-end-encrypted sync replica for the comp audit log.// layerEncrypted bundles the Web Crypto encryption layer internally, so you// only supply an RpcClient.Protocol transport (HTTP/WebSocket) and the Registry.// Use layerEncryptedWith({ compaction: false }) to opt out of remote compaction.const SyncLayer = EventLogRemote.layerEncrypted
Warning: The remote authenticates before writing — see EventLogSessionAuth. Writes wait until the challenge/response completes, so a client can be offline for an extended session and resync cleanly on reconnect.
Failure handling in the sync loop.
Failure
What the runtime does
A remote write fails transiently (network drop, server restart)
Retried until it succeeds, on Schedule.min([exponential(200 ms, ×1.5), spaced(10 s)]) — so the delay grows but never exceeds ten seconds. Pending local entries stay uncommitted for that remote and are sent after recovery.
The change stream from the remote ends or fails
Logged, then re-subscribed on the same schedule from the next unseen remote sequence.
The server answers a write or a change subscription with Forbidden (for example a server restart dropped the session binding)
The cached authentication is invalidated, the hello/authenticate handshake runs again, and the operation is retried — up to five times before the error surfaces as EventLogRemoteError.
Nothing is uncommitted for the remote
No write is attempted at all (withRemoteUncommited returns Option.none()).
Remote delivery is therefore at-least-once: a write that reached the server but whose acknowledgement was lost is sent again. The shipped encrypted and unencrypted servers skip entry ids they already hold, so the redelivery is harmless; a custom server built on EventLogServer.layerRpcHandlers must de-duplicate by entry id in its onWrite as well.
Use EventLogRemote when a client needs to sync a local event log to a central server while remaining offline-capable.
Server-side handlers for the event-log remote protocol. EventLogServer.layerRpcHandlers(options) runs the hello/authenticate challenge flow, attaches the authenticated EventLog.Identity to subsequent requests, accepts single or chunked writes, and streams changes back. Also provides EventLogServer.layerAuthMiddleware for the auth boundary.
Protocol engine that the encrypted and unencrypted concrete servers build on. Accepts callbacks for binding a session key, handling onWrite, and producing a changes stream, wiring them to the EventLogRemoteRpcs contract. Typically not used directly — pick a variant below.
Self-contained source · Type-checked
ts
import { EventLogServer } from "effect/eventlog"// The shared handlers/middleware the concrete comp servers build on:const Auth = EventLogServer.layerAuthMiddleware
Use EventLogServer when building a custom sync server and wanting the handshake, auth, chunking, and change-streaming plumbing provided.
A ready-made server that stores encrypted entries and replication metadata keyed by client public key and store id, streaming ciphertext back for the client to decrypt — plaintext is never visible server-side. EventLogServerEncrypted.layer mounts it over an RpcServer.Protocol; layerStorageMemory provides in-memory Storage for dev/tests. Use SqlEventLogServerEncrypted for durable storage.
SQL encrypted storage returns and publishes only newly inserted entries, so a client re-uploading a batch causes no duplicate broadcast. Custom Storage implementations write and stream batches, and must provide entrySequences (the sequence each entry was first stored at).
Use when hosting a sync endpoint that must not have access to plaintext data.
A plaintext server: accepts unencrypted batches, runs registered handlers server-side, stores entries, and streams backlog plus live changes. EventLogServerUnencrypted.layer(schema, handlersLayer) builds the full RPC server; supply infrastructure services Storage (e.g. layerStorageMemory), EventLogServerAuthorization, and StoreMapping (layerStoreMappingStatic). For trusted deployments, local dev, and tests.
Duplicate and conflict detection is indexed once per incoming batch: Storage.entriesAfter receives the batch as an optional third argument (custom storages that ignore it keep working) and returns RemoteEntry values, and SQL storage creates a <prefix>_event_key_idx index on startup. Inside a SQL transaction, publication waits for the outermost commit and is dropped on rollback.
During the Authenticate handshake the server first calls EventLogServerAuthorization.authorizeIdentity({ publicKey, signingPublicKey }), then verifies the signature against the presented signing key, and only then resolves (or creates) the identity's signing-key binding. A rejected identity or a bad signature therefore never looks up or persists a binding, and a verified key that differs from the identity's existing binding is rejected like a bad signature.
An identity's publicKey is an identifier, not a secret, and nothing ties it to a signing key: without a policy, the first signing key that authenticates for a publicKey is bound. To close that first-use window, record each identity's signing key when you provision it (EventLogSessionAuth.deriveSigningPublicKey(identity) returns it) and reject any other key in authorizeIdentity. The server always passes signingPublicKey; the field is optional only for source compatibility, so a policy that checks it should reject when it is absent.
Fragment · Type-checked
ts
import { Effect, Layer } from "effect"import { Mac } from "effect/crypto"import { EventLogServerUnencrypted } from "effect/eventlog"const { EventLogServerAuthError, EventLogServerAuthorization } = EventLogServerUnencrypted// The signing keys recorded at provisioning time, by identity public key.declare const provisionedSigningKey: ( publicKey: string) => Effect.Effect<Uint8Array<ArrayBuffer> | undefined>export const AuthorizationLive = Layer.succeed(EventLogServerAuthorization, { authorizeRead: () => Effect.void, authorizeWrite: () => Effect.void, authorizeIdentity: Effect.fn("authorizeIdentity")(function*({ publicKey, signingPublicKey }) { const expected = yield* provisionedSigningKey(publicKey) if ( expected === undefined || signingPublicKey === undefined || !Mac.timingSafeEqual(expected, signingPublicKey) ) { return yield* new EventLogServerAuthError({ reason: "Forbidden", publicKey }) } })})
The same check is available to a custom server: EventLogServer.layerRpcHandlers({ authorizeIdentity }) calls authorizeIdentity(publicKey, signingPublicKey) with both keys.
Use when the server is trusted and should run handlers/projections on synced events without an encryption layer.
Challenge-response auth for sync sessions. A peer proves control of a session signing key (Ed25519): the server issues a short-lived challenge with makeSessionAuthChallenge; the client signs a canonical payload (remote id + challenge + event-log public key + signing key) via signSessionAuthPayload; the server verifies with verifySessionAuthenticateRequest. Domain-separated by the "eventlog-auth-v1" context string. EventLogServer keeps each pending challenge on the RPC connection that asked for it: overlapping Hellos share it until Authenticate consumes it, it expires after SessionAuthChallengeTimeToLiveMillis, and it is released when the client disconnects, so challenges cannot pile up across connections. deriveSigningPublicKey(identity) returns, as an Effect<Uint8Array>, the Ed25519 signing public key an identity will present (derived from its private key on the WebCrypto reference) — record it at provisioning time for the authorization policy above.
Use when understanding or customizing how clients authenticate to an event-log server before replicating.
The wire protocol shared by clients and servers. Defines branded StoreIds, protocol errors, the hello/authenticate handshake, remote calls for writes and changes (WriteSingleRpc, WriteChunkedRpc, ChangesRpc), and encrypted vs. plaintext entry message formats — bundled into the EventLogRemoteRpcs group with an EventLogAuthentication middleware. The contract EventLogRemote and both server variants implement.
Use when inspecting the protocol, implementing a custom transport, or debugging wire traffic.
A SQL-backed implementation of EventJournal on top of a SqlClient. SqlEventJournal.layer(options?) stores entries as encoded bytes and keeps per-remote sequence metadata in separate tables, giving a server or Node/SQLite program a durable journal that replays after restart. Drop-in replacement for EventJournal.layerMemory.
Driver byte types are normalized. Entry ids and payloads decode whether the SQL driver returns a BLOB as Uint8Array or as a plain ArrayBuffer. PostgreSQL tables use BYTEA columns for entry and remote ids (not UUID); BIGINT timestamps decode whether the driver returns strings or bigints.
Upgrade note (PostgreSQL only): Tables created before 4.0.2 used UUID columns for id, remote_id, and entry_id. These columns are not migrated automatically. Recreate the journal tables only after confirming they are empty, or externally migrate those three columns to BYTEA while preserving all other data.
Your callback's error is preserved. A failure raised inside the write effect or the withRemoteUncommited callback comes back as that same error value in the typed channel, not wrapped in an EventJournalError; match on your own tags.
The write is transactional with the handler.write and writeMany callbacks run in the journal transaction, so handler work that uses the same SqlClient commits or rolls back together with the journal insert, including on interruption. Inside an enclosing SQL transaction, local ids also sort after its uncommitted rows.
Large syncs stay within parameter limits. Batch statements are split (down to the 100 parameters Durable Object SQLite allows) while still committing each batch in one transaction.
One row per imported entry. The source remote of each imported entry is tracked on the entry instead of one row per entry per remote. Older journals migrate on first open (the remotes table is dropped; this needs a writable connection), and the first upload afterwards may resend unconfirmed entries, which the server treats as duplicates. The IndexedDB journal migrates to database version 2 the same way.
Use when a persistent, restart-surviving audit journal backed by Postgres, MySQL, or SQLite is needed.
The durable Storage for EventLogServerEncrypted, persisting ciphertext in SQL. SqlEventLogServerEncrypted.layerStorage(options?) requires SqlClient and Digest.Digest (from effect/crypto/Digest; layerStorageSubtle supplies the Web Crypto one) and creates tables for the server remote id, session-auth bindings, and encrypted batches, assigns stable sequence numbers, and streams changes — without the database ever seeing plaintext, since clients encrypt/decrypt. Pass compaction to enable encrypted remote compaction. The insertBatchSize option is gone, and the entry-id tables carry a sequence column, so encrypted servers need fresh storage after the batch-format change. Existing table-name encodings are unchanged.
Use when running an encrypted sync server that must survive restarts with a SQL backend.
The durable Storage for EventLogServerUnencrypted, storing plaintext entries in SQL and streaming them back by store sequence. SqlEventLogServerUnencrypted.layerStorage(options?) creates dialect-specific tables for the server remote id, per-store sequence state, entries, and session-auth bindings. Pair with the unencrypted server layer for a trusted, restart-proof deployment.
Use when running a trusted plaintext sync server requiring SQL-backed durability.
Tip: Client setup: define EventGroups, build an EventLog over EventJournal.layerIndexedDb, register handlers that fold events into projections, wire EventLog.groupReactivity for live UI updates, add EventLogRemote.layerEncrypted to sync. Server setup: stand up EventLogServerEncrypted.layer backed by SqlEventLogServerEncrypted.layerStorage, using the same EventLogMessage protocol and EventLogSessionAuth. Result: each client writes offline to its own journal and converges through an end-to-end-encrypted server that never reads plaintext entries.
Most incorrect Effect code uses a real primitive for the wrong job. Choose first by semantics—absence, failure, coordination, ownership, durability, or distribution—and only then by API convenience.
“In-process” means that a restart loses the state unless the program explicitly writes it to a durable subsystem. Scope in the requirements column means that acquisition or borrowing is tied to structured cleanup. Every table ends with a Details line that names the section owning the full explanation; this page only decides. Official guide links track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
One shape recurs in every table below: keep a fact explicit inside the program and collapse it only at the edge that owns the decision. If the collapse happens earlier, no primitive further down can recover the information.
Not everything needs a primitive. A deterministic, synchronous transformation with no dependency, expected failure, asynchronous step, interruption, concurrency, or lifetime stays a plain TypeScript function. Details: Decide what to leave out.
Choose the constructor by how the wrapped JavaScript reports failure and when it does its work, not by which one makes E smallest. sync and promise are assertions that the code cannot fail; when it fails anyway the result is a defect.
You are wrapping
Constructor
A throw or rejection becomes
Avoid it when
A value you already hold
Effect.succeed(value)
not applicable: the argument is evaluated eagerly, while the program is built
the expression does work (Date.now(), counter.next(), a side effect); use Effect.sync
Synchronous code that cannot throw
Effect.sync(() => ...)
a defect
the code can throw: JSON.parse, new URL, a synchronous Schema decoder
Synchronous code that can throw
Effect.try({ try, catch })
the typed error catch returns
you would use the bare-thunk form and accept Cause.UnknownError without meaning to
No error channel and no services. None says only “absent”; it carries no reason.
An eager immutable value. No execution, interruption, concurrency, or cleanup.
Data only. It can be encoded, but has no persistence or transport behavior itself.
A value may legitimately be absent and callers do not need to distinguish why.
Absence has domain meaning that callers must handle differently, or obtaining the value performs work.
Result<A, E>
An eager Success<A> or Failure<E> value; no R. Both branches are ordinary data and can be inspected repeatedly.
No runtime, scheduling, interruption, or lifetime. Useful for pure validation and for storing an already-computed outcome.
Data only. Durability depends on an explicit Schema/store.
A pure calculation has a meaningful failure value and execution has already happened.
The operation is lazy, asynchronous, interruptible, resource-owning, or requires services.
Exit<A, E>
An eager Success<A> or Failure<Cause<E>>; no R. The Cause keeps defects, interruption, and several reasons.
The recorded outcome of a finished run. No execution of its own.
Data only; it is what Persistence, Deferred.done, and request completion store.
The full outcome of a run must be inspected, stored, or replayed: test assertions, host adapters, RequestResolver completion.
A two-case answer is enough (Result), or the value is not the outcome of running anything.
Effect<A, E, R>
Typed failure E; required services R; defects and interruption remain in Cause.
A lazy description run by a fiber. Supports structured concurrency, retry, timeout, and scoped acquisition.
Ephemeral by default. It can call Persistence, Workflow, Cluster, or another durable/distributed subsystem.
Describing application work, including synchronous work that must compose with typed failure, services, or lifecycle.
You only need a small, eagerly available data value and no execution semantics.
Do not turn every None into a defect, or every pure Result into a running Effect. Convert at the boundary where semantics change: Option to a typed failure when absence becomes exceptional, and Result to Effect when the outcome joins effectful control flow. Effect.result and Effect.option capture typed failures only; Effect.exit captures the whole Cause.
a tag already says it; the narrowest selector documents the policy best
Handle one nested reason of a wrapper error
Effect.catchReason, catchReasons
the other reasons
the error has no reason union
Translate without recovering
Effect.mapError
the new error
nothing was learned at this layer; pass the error through unrenamed
Turn an unacceptable success into a failure
Effect.filterOrFail
the added error
the check belongs in a Schema at the boundary
Produce exactly one ordinary shape at a terminal edge
Effect.match, Effect.matchEffect
never
the code is not a terminal boundary; folding in a lower layer steals policy from callers
Default a value
Effect.orElseSucceed after narrowing with catchTag
never
only one variant should default; un-narrowed, it replaces every typed failure
Try different effects in order
Effect.firstSuccessOf([...])
the last error
the same effect should run under different services; that is ExecutionPlan
Observe only
Effect.tapError, tapErrorTag, tapCause, tapDefect
unchanged
you intended to recover
Treat the outcome as data
Effect.result, Effect.option, Effect.exit
never
option would discard an error value somebody needs
Inspect defects or interruption deliberately
Effect.catchCause with a guard, Effect.catchDefect that re-dies what it does not recognize
unchanged unless handled
inside domain logic; these belong to a request, job, or process boundary
Discard a best-effort failure
Effect.ignore (typed failures only), Effect.ignoreCause (defects and interruption too)
never
anything but best-effort cleanup or telemetry
Promote to a defect
Effect.mapError then Effect.orDie
never
the goal is only a tidier error union
Typed recovery operators look at the first Fail reason. A defect beside it takes precedence — the operator does not recover and propagates the error as a defect — while an interruption beside it is dropped when the handler's result replaces the Cause. Where an interruption or a second failure matters, use a guarded catchCause. Details: Effect error handling, Recovery and mixed causes, Classifying an error union.
Ref vs SynchronizedRef vs SubscriptionRef vs transactions
Effect 4 exposes software transactional memory through Effect.tx, Effect.txRetry, and the Tx* structures. There is no public STM namespace in this release.
Primitive
Error and requirements
Scope, lifetime, and backpressure
Durability and distribution
Choose it when
Avoid it when
Ref<A>
Reads and pure modify/update operations cannot fail and require no services.
One in-memory cell. Each pure modification is atomic; there is no waiting protocol or change stream.
In-process only.
Several fibers share one value and every transition is a fast, pure function.
A transition must run an Effect, several cells must commit together, or consumers need every update.
SynchronizedRef<A>
Effectful modifiers contribute their own E and R.
A one-permit semaphore serializes the whole effectful transition. Other updaters wait until it finishes.
In-process only.
Load-once state, token refresh, or another effectful read-modify-write must not overlap.
The slow transition should run concurrently, or several independent values need one atomic commit. Do not hold its permit around avoidable network latency.
SubscriptionRef<A>
Reads/writes are infallible; effectful modifiers contribute E/R. changes is a Stream<A>.
Serialized state plus an unbounded replay-one PubSub. A subscriber first sees the current value, then committed changes; a permanently slow subscriber can accumulate backlog.
In-process only.
Consumers need both the latest state and a live stream of subsequent changes.
You need bounded backpressure, durable replay, or only event fan-out without a current value.
Effect.tx + TxRef / TxQueue / other Tx*
The body retains its typed E/R; Effect.tx supplies the internal transaction service. Effect.txRetry waits without a typed error.
Optimistic journal over multiple transactional values. Conflicts rerun the entire body; commit is all-or-nothing. txRetry wakes when a read transactional value changes.
In-process only; this is not a database transaction.
Several related in-memory values must change atomically, or a condition should wait transactionally.
Work must survive restart, coordinate across processes, or perform an external side effect. A transaction body can rerun, so keep non-idempotent I/O outside it.
Classify the communication before naming a primitive. Each of the four classic coordination bugs — a hang, a leaked listener, duplicated work, an event seen by only one observer — comes from answering one of these questions wrongly.
Question
Answer
Primitive
Do readers want the current value or each event?
current value
Ref, or SubscriptionRef when they also want changes
Does it happen once or repeatedly?
once
Deferred (a result) or Latch (a reopenable gate)
Should one consumer or every consumer see each value?
one / every
Queue / PubSub
Under overload, should the producer wait, should data be shed visibly, or does only the latest value matter?
Completed once with success, typed failure, or an Effect/Exit; awaiters observe that outcome. No service requirements.
Write-once cell. Any number of fibers may await the same result. No capacity or stream of values.
In-process only.
One result or readiness signal must be delivered to many waiters exactly once within the process.
The gate must reopen, or more than one value must be transferred.
Latch
No value or typed error; no services.
Repeatable open/close gate. await and whenOpen block while closed; opening releases current and future waiters until closed again.
In-process only.
Pausing and resuming work behind a lifecycle gate.
A result must be communicated, or each signal must be counted. For mutual exclusion use Semaphore.make(1) with withPermit: a latch lets every waiter through together and hands nothing back.
Queue<A, E>
Consumers can fail with queue error E; Queue.end uses the done cause. No service requirements.
Point-to-point: one offered element is taken by one consumer. Bounded queues suspend producers; dropping and sliding queues shed data explicitly.
In-process only.
Producer/consumer handoff, bounded mailboxes, worker pipelines, and local backpressure.
Every subscriber must see every event, or messages must survive process loss.
PubSub<A>
Publish is infallible at the typed level; subscriber dequeue lifetime is scoped.
One-to-many fan-out. Bounded mode can suspend publishers on slow subscribers; dropping/sliding modes shed data. Late subscribers miss history unless replay is configured.
In-process only.
Independent live consumers must each receive published events.
Work should be distributed among workers rather than copied, or delivery/replay must be durable.
{ concurrency } on Effect.all, Effect.forEach, Stream operators
Combines each child’s E and R. Child fibers are structurally owned by the enclosing operation.
A local bound for one traversal: sequential by default, a positive number, or "unbounded". It does not create a shared global quota.
In-process, for one invocation.
A finite batch or one stream stage needs a straightforward parallelism bound.
Several unrelated call sites must share the same quota, or the limited thing is a reusable resource.
Semaphore
Wrapped work keeps its own E/R; semaphore operations are infallible. No Scope is required.
Shared permit budget across arbitrary fibers. withPermit(s) releases on success, failure, or interruption. Waiters are scanned in registration order, but a smaller later request can overtake an earlier request that needs more free permits.
In-process only.
Rate/concurrency limiting or mutual exclusion must span several call sites.
You need to construct, health-check, invalidate, and release actual resource instances.
Pool<A, E>
Acquisition error is E; acquisition may require services. Pool construction and every borrowed get require Scope.
Fixed or elastic collection of acquired resources, with per-item concurrency, waiters, invalidation, TTL strategies, and finalizers.
In-process ownership; pooled clients may themselves talk to remote systems.
Expensive reusable resources such as connections or sessions need bounded sharing and cleanup.
The work has no reusable resource, or a simple semaphore around an existing client is sufficient.
batching shrinks one burst and remembers nothing afterwards
Cold stampede on one key
a burst of identical lookups at startup or right after expiry
already solved by Cache.get: concurrent misses for one key share one lookup
a hand-written promise map or lock duplicates it
N+1 over different keys
backend calls scale with rows, one id each
RequestResolver + Effect.request; SqlResolver for SQL
a cache cannot help: remembering one key does nothing for the others
Single-flight is not batching: the first collapses concurrent gets of the same key, the second collapses requests for different keys into one backend call. They compose through RequestResolver.withCache and asCache. Base batching does not deduplicate equal requests; only those two combinators do. Details: Which problem do you have?, Caching a single Effect, Resolver obligations.
Cache vs ScopedCache vs Resource vs RequestResolver
Primitive
Error and requirements
Scope, lifetime, and backpressure
Durability and distribution
Choose it when
Avoid it when
Cache<Key, A, E, R>
Lookups expose E; lookup services can be captured at construction or required at lookup.
Capacity + TTL key cache. Concurrent misses for one key share the same lookup. Both successful and failed Exit values are cached. Values have no finalizers.
In-process only.
Pure/plain values are expensive to load repeatedly by key.
Cached values own resources, or results must survive restart.
ScopedCache<Key, A, E, R>
Same lookup error model; cache construction requires an owning Scope, but get itself does not require a caller Scope.
Per-entry scopes. Expiry, invalidation, eviction, and cache shutdown close the corresponding resources; get is not a per-caller lease, so callers must not retain a value past invalidation or cache closure.
In-process only.
Each cached value owns a connection, subscription, file, or other finalizable resource.
Values are plain data and a normal Cache is enough, or each caller needs a separately scoped lease such as Pool.get.
Resource<A, E>
Acquisition error is stored and re-exposed by get; construction needs acquisition services and Scope.
One refreshable value, not keyed. manual or schedule-driven auto; replacing a successful scoped value releases the previous value. A failed refresh leaves the previous stored result in place.
In-process only.
The application needs the latest configuration/snapshot/client and explicit or scheduled refresh.
You need many keys, per-request batching, or durable history.
RequestResolver<Request> + Effect.request
Each request declares its success/error type; resolver effects contribute services and failures while completing request entries.
Data-loader model: concurrent requests are collected and handed to batched resolvers. withCache adds equality-based sharing of in-flight/completed requests; TTL and resource ownership are not implicit.
In-process by default; persisted can add durable result reuse and the resolver may call a remote backend.
Many fibers make declarative lookups that should use one backend batch; add withCache when equal requests should also share results.
You need a general mutable cache, arbitrary resource ownership, or a continuously refreshed value.
Separately types input/output elements, errors, done values, and services.
Lowest-level bidirectional streaming algebra underneath Stream and Sink; precise leftovers, completion, piping, and codec protocols.
Ephemeral unless connected to durable transport.
Implementing transports, framing, codecs, or a reusable streaming primitive.
Ordinary business pipelines can be expressed with Stream and Sink.
Stream.runCollect is an explicit decision to move the entire remaining stream into memory. Prefer a bounded Sink, incremental runForEach, or streaming output when the size is not proven small.
binary frames whose layout is compiled once from the Schema's encoded side
Schema.SchemaError
tolerant: fields carry hashed ids, so peers may add optional fields independently; pin SchemaBinary.fieldId(n) before a rename
workers, TCP, cluster runners, high-throughput links between Effect programs
the peer cannot share the Schema, or frames must be read by humans
SchemaBinary with { fingerprint: true }
positional layout plus a layout hash
Schema.SchemaError; a mismatched layout is rejected
none: both peers must deploy the same schema together
smallest frames under lock-step deployment
peers are upgraded independently
Sse — unstable
server-sent events text
a Retry failure carries the retry: directive
as JSON for the data payload
one-way server-to-browser push
bidirectional or binary traffic
SchemaBinary is the default binary format for cluster runner transports and EventLog journals and remote messages, so switching a link or a journal to or from it changes bytes on the wire and on disk. maxFrameSize is unset by default on the raw codec; set it for untrusted peers. Details: SchemaBinary, Ndjson, RpcSerialization, Serialization codecs.
These modules are @stability unstable; pin all Effect packages to exactly the same release. The adjacent GraphQL family is experimental, so it can change even in a patch release.
Primitive
Error and requirements
Scope, lifetime, and backpressure
Durability and distribution
Choose it when
Avoid it when
HttpClient
Typed request/response/client errors; requires an implementation such as FetchHttpClient.layer. Response bodies are scoped when streamed.
Outbound HTTP with middleware, retries, tracing, redirects, cookies, and streaming bodies.
Remote request/response; HTTP itself supplies no durable orchestration.
Calling arbitrary HTTP services or building a provider-specific client.
You own both ends and want one shared typed contract.
Use GraphQL operations, GraphQLGroup, and GraphQLClient when an existing endpoint speaks GraphQL. GraphQLProtocol selects HTTP, SSE, or WebSocket transport; GraphQLResolver batches lookups by operation and resolved URL. This is a client abstraction, not a GraphQL server or an alternative way to derive OpenAPI. Choose a partial-result mode deliberately: GraphQL can return useful data together with errors, unlike a simple success/failure HTTP decoder. Use @effect/graphql-generator when operations and schemas should be generated from .graphql documents rather than authored by hand.
Repeats only after typed failure. Final E remains if the schedule stops; schedule errors/services are added. Effect.retryOrElse(effect, schedule, orElse) runs a fallback with the last error and the schedule's output once the policy is exhausted.
One fiber reruns the whole Effect according to a Schedule. Interruption stops it.
Ephemeral; progress disappears on restart.
A transient operation is safe to attempt again with a bounded, classified policy.
Failures are permanent, external writes are not idempotent, or the retry window must survive restart.
Effect.repeat(schedule)
Repeats after success and stops immediately on typed failure; final success is determined by the Schedule output.
One fiber runs once immediately, then recurs by policy.
Ephemeral.
Periodic maintenance or repeated successful work while the process is alive.
You meant “recover from failure,” or missed work must be remembered.
Polling with repeat/Schedule.passthrough or a Stream
Poll errors remain typed; clock and schedule requirements compose normally.
Repeated reads until a terminal value, usually with Schedule.while. A Stream is preferable when callers consume multiple observations.
Ephemeral.
A remote system exposes status but no push callback, and loss of the polling fiber is acceptable.
The wait lasts across deployments or must resume without redoing prior steps.
Workflow + Activity / durable primitives
Payload, success, and failure are Schema-typed; the engine, storage, runner, and activity dependencies are required.
Journaled deterministic orchestration. Completed activity exits replay; durable sleeps/deferreds/queues suspend and later resume. Activity delivery is at least once until its result is recorded.
Durable and deployable across workers when backed by durable engine/storage.
Multi-step business work must survive restarts, be resumed/inspected, and use stable idempotency keys.
A short in-process retry is sufficient, or the body cannot be made deterministic and side effects idempotent.
Schema encoding/decoding and backing-store errors are typed; Layers require the selected memory, SQL, Redis, filesystem, or browser backend. Stores are scoped.
Keyed storage of encoded Exit values, TTL caches, and durable queues. It stores results/state but does not orchestrate steps.
Durable only with a durable backing Layer; shared backends can serve multiple processes.
Results, idempotency records, cached computations, or queue items must survive restart.
You need an append-only domain history or deterministic multi-step orchestration.
EventLog
Event payload/success/error Schemas plus journal, identity, handler, encryption, and optional remote services.
Append-only facts with handlers/projections, replay, compaction, and local/remote synchronization. Handler/journal atomicity depends on the backend.
Durable with IndexedDB/SQL journal; optional encrypted or unencrypted replication.
Audit history, event-sourced state, offline-first convergence, and rebuildable projections are central.
You only need current keyed state or an imperative job runner.
Workflow
Schema-typed workflow/activity outcomes plus engine/storage requirements.
Persistent execution journal, suspension, resumption, compensation, and operational control. Non-deterministic work belongs in Activities.
Durable orchestration; runners may execute resumed work on another process.
A business process has ordered steps, long waits, retries, and recovery semantics.
You need entity placement, low-latency messaging, or an event-sourced domain ledger rather than orchestration.
Cluster / Entity / Sharding
Entity request/reply Schemas and cluster transport/storage services; failures include domain, transport, and runner availability concerns.
Routes calls to the runner owning an entity shard; supports entity lifetimes, messaging, runners, singleton/cron facilities, and rebalancing.
Distributed. State durability depends on the entity/message storage and application design; sharding alone is not persistence.
Stateful or addressed capabilities must be located and invoked across a fleet.
One process is enough, or you merely need durable records/work without entity placement.
Is this outcome a result or a failure? A correct negative answer belongs in A; a condition some caller needs its own policy for belongs in E; a broken invariant is a defect; a departed caller is interruption.
Is this just data? Start with Option, Result, Array, Chunk, or Iterable. Keep pure, synchronous, dependency-free transformations as plain functions.
Is it one lazy operation? Use Effect<A, E, R>, model expected failure in E, and choose the constructor by the wrapped code's failure convention. Forward the AbortSignal in every Promise adapter.
Does it need something? Put it in R; provide one value with provideService, a graph with a Layer, and the live graph once at the edge.
Does it hold something open? Name the owner: one operation (acquireUseRelease), a region (Effect.scoped), a Layer, or a stream. For a fiber, name the owner before choosing the fork.
Is it a sequence? Choose Stream; add a Sink for reusable consumption and Channel only for protocol-level work. Bound every stage and choose batch size separately from buffer capacity.
Is shared state involved? Choose Ref, SynchronizedRef, SubscriptionRef, or Effect.tx according to update and observation semantics.
Is coordination involved? Classify the communication first — current value or events, once or repeatedly, one consumer or all, and the overload policy — then choose Deferred/Latch for signals, Queue for work distribution, PubSub for fan-out, Semaphore for a quota, and Pool for owned reusable resources.
Is work repeated? Measure the waste shape: one effect (Effect.cached), the same key (Cache), or many keys at once (RequestResolver).
Is the boundary remote? Choose HttpClient for outbound calls, HttpRouter for low-level inbound HTTP, HttpApi for REST contracts, and RPC for typed procedures; then choose the wire codec by who the peer is and how the two sides are deployed.
Must state or progress survive restart? Move to Persistence, EventLog, or Workflow. Add Cluster when work or addressed state must also be placed across processes.
Who runs it? One platform runMain per process, one ManagedRuntime per foreign host, a request scope per Web handler call — and a runner that keeps cancellation distinct when the host can represent it.
How will you know? Pick the test tool by the claim, and finish with the Review Checklists.
Use this page three ways: in a design review, read a section before code exists and treat every "not decided yet" as an open design question; in a code review, answer each question from the diff alone; as a coding-agent self-check, run the relevant sections over generated code before proposing it. Every question is phrased so that yes is the safe answer — a "no" or "cannot tell from the diff" is a finding, and the link leads to the section that owns the rule and its evidence.
The items are deliberately short; the owning pages carry the reasoning, the probed behavior, and the examples. For symptoms rather than rules, start from Troubleshooting & Anti-Patterns; for choosing between primitives, from Choosing Effect Primitives.
Is every constructor chosen by how the wrapped code fails — Effect.try / Effect.tryPromise for code that can throw or reject, Effect.sync / Effect.promise only for code that cannot? Creating effects
Is every argument to Effect.succeed and Effect.fail a value that is safe to compute while the program is being built — no clock reads, counters, or side effects? Creating effects
Does each adapter's catch recognize the failures its contract allows and turn everything else into a defect, instead of mapping every rejection to one retryable error? Cancellable adapters for promises and callbacks
Is the diff free of runners (runPromise, runSync, runFork, a second ManagedRuntime) inside services, handlers, and domain functions? Running effects at an owned edge
Where a host can represent cancellation, does the edge use runPromiseExit (or runFork) with { signal } rather than collapsing every outcome into a rejection? Running effects at an owned edge
Is every Effect that is constructed also returned, yielded, or composed — none built inside a callback and dropped, none nested by Effect.map? “My Effect never ran”
Are callbacks written as lambdas rather than functions passed by name to Effect.forEach, Effect.map, and similar operators? Generated-code anti-pattern index
Does branching and looping use ordinary if / for inside Effect.gen (and Effect.when with an Effect<boolean>), with none of the removed Effect.if / unless / loop / zipRight family? Branching and looping
Do effect-returning functions use Effect.fn("name"), so they carry a span and a readable stack? Sequencing with gen & fn
Is pure, synchronous, dependency-free logic left as plain functions instead of being wrapped in Effect? Decide what to leave out
Is each new unpleasant outcome placed deliberately: ordinary negative answers in A, caller-actionable conditions in E, broken invariants as defects, and interruption left alone? Designing the error model
Does every error variant carry the facts its policy needs as fields (retryable, ids, limits) rather than a message to parse? Designing the error model
Are missing, conflict, unavailable, timeout, corrupt, and forbidden kept distinct wherever their policies differ — and is "not found" produced only by a query that succeeded and returned nothing? Designing the error model
Does each catch* use the narrowest selector that expresses the policy, leaving the undecided variants in E? Selective recovery beyond one tag
Is every handler clearly one of recover, translate, compensate, or observe — with no catch that exists only to empty E? Recover at the narrowest owner
Is every whole-union classification closed with Match.exhaustive or Match.tagsExhaustive, with no default branch or unexplained Match.orElse? Classifying an error union
Where an interruption or a second typed failure can sit next to the one being handled, does recovery go through a guarded Effect.catchCause so the other reasons survive, and is a defect beside a typed failure expected to propagate rather than be recovered? Recovering from a mixed Cause
Is the diff free of Effect.orDie, Effect.ignoreCause, and catchCause(() => Effect.void) used only to tidy types? Fallback values and ignoring failures
Is every retry classified, bounded in attempts and elapsed time, paced with backoff, and wrapped around the smallest idempotent operation? Retry policy checklist
Do public error values expose only stable tags and safe identifiers — no cause, driver message, SQL text, or Redacted? Designing the error model
When several problems must be reported together, are they accumulated as data (Effect.validate, Effect.partition, mode: "result")? Accumulating errors instead of failing fast
Is each service named for a business capability, with domain-verb methods that return Effects and never throw? Designing a service contract
Do all public service methods have R = never, with construction dependencies captured in the Layer? Designing a service contract
Is the service shape free of implementation details: no SQL client, transaction handle, logger, or concrete class in parameters or fields? Designing a service contract
Does a new service have a substitution reason (test, tenant, vendor, lifetime) rather than existing to make one helper mockable? Designing a service contract
Is the application graph provided once — one enclosing Effect.provide, Layer.launch, or ManagedRuntime — rather than per request or per call? What is shared, and what is rebuilt
Is every Layer that must be shared a single named value, not an inline expression or a function called twice? What is shared, and what is rebuilt
Does anything that needs teardown use Layer.effect with Effect.acquireRelease, not Layer.succeed? Resourceful services
Does a Layer that must see another's output receive it through Layer.provide / provideMerge rather than sitting beside it in Layer.merge? Reading and composing the graph
Do test Layers honor the production contract, including typed failures, and does each test prove that the fake — not a live default — answered? Test layers and substitution
Is there exactly one composition root per executable, and does it install configuration and observability before dependents acquire anything? What the composition root owns
Is there one Config program that defines a valid deployment, with no process.env reads or second hand-written parser elsewhere? Designing the startup contract
Is each setting explicitly required, optional, or defaulted — and do credentials, bind addresses, CORS origins, and destructive modes have no silent default? Deciding required, optional, and defaulted
Do defaults use Config.withDefault or Config.option (absence only), with Config.orElse reserved for an alternative source? Absence is not malformed input
Are numeric bounds, duration syntax, and URL shape validated in the Config itself, not after startup? Validating more than syntax
Are secrets read with Config.Redacted, kept wrapped until the single call that needs the bytes, and never logged after Redacted.value? Redacted
Do schemas that decode a secret set disallowEncode / disallowJsonEncode wherever their encoded side leaves the process? Secrets that arrive through a schema
Do config tests use an in-memory provider and cover absent, malformed, and boundary values without mutating process.env? Testing the contract
Can the reviewer name, for every new resource, fiber, and runtime, who closes it, what bounds it, and what runs when it loses? Three questions for anything that runs
Does every acquired handle have its own acquireRelease, registered in the scope that matches its lifetime? One bracket per resource
Is every Scope in a signature discharged by a deliberate choice (Effect.scoped, a Layer, a held scope), never by accident at the entrypoint? Scope left in R means nobody owns it yet
Do scoped values stay inside their scope — nothing returned from Effect.scoped that is still borrowed? Scope closed or resource leaked
Is all cleanup attached structurally (ensuring, onExit, acquireRelease), so it also runs on failure and interruption? Success-only cleanup
Does every finalizer have a time bound and a stated policy for its own failure? When cleanup can fail
Is each fork chosen by its owner — forkChild, forkScoped, forkIn, or a FiberSet / FiberMap — and does every forkDetach name who stops it? Choosing a fork by its owner
Where a forked fiber must be listening before the parent continues, is that guaranteed by startImmediately or a handshake rather than by yieldNow? When a forked fiber starts
Does every Deferred and Latch have a completion path on success, failure, and interruption, and a fresh instance per lifecycle generation? Deferred
Does every queue, PubSub, and buffer have a capacity and an overflow strategy chosen as a policy? Queue
Wherever dropping, sliding, or offerUnsafe is used, is the loss counted and documented? Make loss observable
Is it decided who ends each queue, and does a producer failure reach its consumers (Queue.end, Queue.fail, Queue.into) — with Queue.shutdown reserved for abandoning work? Queue lifecycle
Was the delivery semantics — one taker or every subscriber, late joiners, nobody listening — chosen explicitly? Delivery semantics: Queue or PubSub
Is every shared-state transition one Ref.update / modify call over an immutable value, with SynchronizedRef for effectful transitions and Effect.tx for multi-cell atomicity? One transition, one call
Is every stream stage bounded, including Stream.callback (bufferSize), mapEffect (concurrency), and framing decoders (frame or line limits)? Where buffering hides
Are resources acquired inside the stream (Stream.unwrap, Stream.scoped) so they close on early stop as well as completion? Owning resources inside a stream
Is Stream.retry placed directly after the source it reconnects, upstream of any non-idempotent write, and is silence detected with timeoutOrElse rather than timeout? Handling stream failures
Is batch size set with grouped / groupedWithin / rechunk rather than inferred from a buffer capacity, and is runCollect used only on sources known to be small? Where buffering hides
Is untrusted input decoded exactly once, at ingress, with no casts (as Model, as EmployeeId) standing in for a decode? The boundary pipeline
Were the boundary questions answered before the schema was written: who produces the input, what absence means, which keys are allowed, who reads the errors? Answer eight questions before writing the schema
Is the decode runner chosen by who consumes the failure, with decodeUnknownEffect inside Effect code and no synchronous decoder inside Effect.sync? Decoding and encoding — pick your result style
Are decoding defaults (withDecodingDefault*) and constructor defaults (withConstructorDefault) used for the side they actually affect? Default values
Do external numbers use Schema.Finite, Schema.Int, or explicit checks rather than bare Schema.Number? Refinements
Are transport, domain, and stored-row shapes separate schemas, with transformations that are reversible where data is written back? Treat stored rows as another encoded form
Do codec tests use named malformed fixtures as well as generated valid values, and assert the round-trip law that actually holds? Assert the law that actually holds
Does each handler only translate one decoded request into one use-case Effect — no runner, no SqlClient, no client construction? Handlers are lazy adapters
Is every member of the public error union mapped to a truthful status through an exhaustive matcher, with the implicit 400 declared? Status mapping is part of the contract
Is authentication done in middleware with a narrow decoded principal, and authorization checked per operation against actor, action, tenant, and resource? Authentication is not authorization
Are body size, multipart limits, CORS origins, redacted headers, proxy trust, and the shutdown window set explicitly? Edge policy checklist
Is the listener allocated during Layer acquisition, bound to port 0 in tests, and proven released? Own the listener
Is the response status checked before the success schema is decoded, and are transport, status, and decode failures kept distinct? Three failure classes
Is every user-supplied URL allow-listed, resolved to a public address, and re-validated on each redirect? User-controlled destinations
Is each RPC contract change classified as compatible or not, deployed in the right order, and covered by a version-skew test through a real serializer? Evolving a contract
Are RpcServerconcurrency, disableFatalDefects, streamBufferSize, and every Rpc.fork chosen deliberately? Operational defaults
Do retried RPC or HTTP mutations carry one idempotency key per intent that the server records with the mutation? Retried mutations need a ledger
Do dependencies point one way — transport, use case, domain repository, SQL implementation, SqlClient — with the transaction boundary owned by the use case? Where SQL belongs in an application
Is the whole atomic unit inside withTransaction, and does every failure leave the body so that recovery happens outside? Transactions
Are external effects (email, webhook, HTTP export, model call) kept out of the transaction and delivered after commit from an intent row? External effects after commit (outbox)
Does each repository expose one stable storage error, check which constraint fired before reporting a conflict, and leave defects alone? Normalizing errors at a repository boundary
Are migrations append-only with increasing ids, compatible with the release still running, and free of long backfills at startup? Operating migrations
Is the pool sized from the database-wide budget, and is everything that holds a connection (transaction, stream, listener) bounded in time? Pools, reservations, and streaming
Is there a repository contract suite against a real database, rather than an identity withTransaction fake? Verification levels
For durable work, is the guarantee stated honestly (at-least-once), with an idempotency key derived from the item and a sink that rejects stale owners? Failure windows and honest guarantees
Is a failure logged once, where recovery or translation is decided, with stable event text and variables in fields? Logging practice
Does a custom Logger.layer([...]) keep Logger.tracerLogger (or use mergeWithExisting) when logs should still appear on spans? Installing and swapping loggers
Is trace context carried explicitly across queues, workers, and message buses, and is malformed inbound context dropped rather than rejected? Span and correlation rules
Does each test state its claim, boundary, replaced requirements, and oracle — and would a believable wrong implementation fail it? Model the proof before writing the test
Is every Effect-returning test written with it.effect (or it.live), never returned from plain it(...)? When green means nothing
Is there at least one typed-failure case per operation, and an interruption or cleanup case for resourceful code? Test interruption and cleanup
Are failures asserted structurally through Exit — tag and fields — rather than by message text or Cause snapshots? Assert typed failures as data
Is time driven with TestClock in fork–adjust–join order, synchronized on handshakes rather than yieldNow counts or real sleeps? Synchronize on phases, not on turns
Does a retry or TTL test assert the timeline and the non-retryable path, not just the final value? Testing a policy
Do fakes record what they received and choose each scripted answer when the returned Effect runs, so forwarding, call counts, and retries are asserted rather than assumed? Spy, lazy, and clock-driven fakes
Is each test classified by the boundary it really crosses, with no in-memory harness used to claim socket, serializer, or database behavior? In-memory test runtimes shipped with Effect
Do real fixtures come from scoped Layers, with unique names per worker, a real readiness probe, and loud cleanup failures? A contract for real fixtures
Do property tests derive generators from Schemas with constructive checks, and keep each shrunk counterexample as a permanent example test? What a derived generator cannot test
Is there exactly one runner per host: one platform runMain per process, or one warmed ManagedRuntime per foreign host? Choosing a host
Is every long-lived thing a row in an ownership ledger with an owner scope, a bounded release, and a proof? Write the ownership ledger first
Is startup all-or-nothing: closed to traffic, acquire in dependency order, probe through the assembled graph, publish ready last? Startup is a transaction
Is shutdown one operation — closing the root scope — that stops intake, drains within a deadline, interrupts survivors, and releases in reverse order? One shutdown operation
Is ordering that matters expressed as a Layer dependency rather than as a convention between Layer.mergeAll peers? One shutdown operation
In a foreign host, is the host's AbortSignal forwarded to the runner, admission stopped before dispose(), and shutdown memoized? A production-shaped bridge
Does each cross-cutting policy — time, recurrence, configuration, capacity, execution, export, atomicity — have exactly one owning value? One owner per policy
On a request-bound host, does the endpoint use layerHttpRequestScoped with sessionless protocols and no subscriptions, rather than depending on long-lived server fibers? McpServer
Does every server layer list the protocol revisions it accepts, with at most one stateless revision, and is the Streamable HTTP endpoint deployed with its allowedOrigins, content-type, and accept checks intact? McpServer
Is the MCP endpoint an OAuth resource server — bearer token verified in router middleware, tenant and scopes taken from token claims only, per-tool scope checks in handlers, and no client token forwarded downstream? Exposing an Effect Application over MCP
Does each tool declare its failure schema, carry honest Readonly / Destructive / Idempotent annotations, use Tool.Strict where unexpected arguments must be rejected, and stay hidden from clients that cannot use it via McpSchema.EnabledWhen? McpServer
Does every consequential tool confirm with the user — McpServer.elicit on session protocols, an InputRequired round trip on the stateless protocol — and is any requestState sealed with an HMAC, bound to the caller, and given a TTL before it is trusted on the way back? Exposing an Effect Application over MCP
Can a retried tools/call (a broken stream, a resumed round trip) run twice without a second side effect, and is an ErrorReporter wired so undeclared tool failures page someone? McpServer
Were experimental GraphQL and networking contracts re-checked even for a patch upgrade, including generated GraphQL output? GraphQL, Platform & Runtime Hosts
Were the per-package changelogs read for changes that alter bytes on the wire or on disk, and is there a coordinated rollout plan for them? Stability and support
Do both peers of every binary RPC, cluster, or EventLog link move to SchemaBinary together, with old journals accounted for? SchemaBinary
Do all boolean CLI flags have Flag.withDefault(false), Flag.optional, or a fallback? Flag
Were Config, Flag, and Prompt constructors renamed to PascalCase, and Config.mapOrFail to Config.mapEffect? Built-in constructors
Were property tests moved to Arbitrary.schema and { arbitrary: { runs } }, opaque filters replaced with constructive checks, and saved failures re-recorded? Arbitrary
Were PostgreSQL row Schemas re-checked against the native client's result types, JSON parameters wrapped in sql.json, and multi-statement strings split? Upgrading @effect/sql-pg to the native client
Were JSON Schema consumers and snapshots checked against open-by-default output? JsonSchema
Debug Effect code in this order: read Effect<A, E, R>, inspect the complete Cause or Exit, check ownership and termination, and only then change the implementation. Most “Effect bugs” are mismatches between the intended success, failure, requirement, or lifetime and the type that was actually built.
Find the symptom, apply the first correction, and follow Details to the section that owns the explanation. Rows are grouped by where the symptom shows up, not by module. Each owning page carries the evidence; many of these causes were confirmed by running probes against the installed release rather than read off the types.
Symptoms: construction, running, and cancellation
Symptom
Likely cause
First correction
Details
Nothing happened
An Effect was constructed but never executed, or a branch was never composed into the returned Effect.
Return/yield the Effect; run only the fully provided top-level program.
A timeout or race "won" but the slow request kept running
The Promise adapter is () => fetch(url). Effect.tryPromise creates an AbortController only when the thunk declares the signal parameter, so there is nothing to abort.
try: (signal) => fetch(url, { signal }) in every adapter.
catchTag did not recover although its tag failed, and the program died
A defect beside the typed failure takes precedence: typed recovery does not run, and the error is propagated as Die(error) beside the defect. An Interrupt beside a Fail is still dropped by recovery.
Recover a recognized defect with Effect.catchDefect, or inspect the whole cause with Effect.catchCause; re-fail when Cause.hasInterrupts matters.
An MCP client sees only a generic error instead of the tool's failure
The failure was undeclared, a defect, or failed to encode; those are logged and reported server-side, and the client gets a generic message. Declared failures reach the client as isError: true in either failureMode.
Declare the failure schema on the tool; look for the logged cause.
McpServer.elicit cannot be used, or a confirmation never reaches a 2026-07-28 client
elicit pushes elicitation/create to a session-era client; the stateless protocol has no server-initiated requests.
Register the tool through the low-level McpServer.McpServer.addTool and return McpSchema.InputRequired; read the answer from McpRequestContext.inputResponses on the retry.
RPC or cluster peers cannot decode each other; an EventLog journal written by another release is unreadable
The peers or the journal do not share a wire format. SchemaBinary is the binary format for RPC, cluster runner transports, and EventLog journals and remote messages; there is no MessagePack codec.
Use RpcSerialization.layerSchemaBinary() on both peers together; upgrade both ends of a binary link in one rollout and rehearse mixed-version deployments.
PostgreSQL rows decode differently than a row Schema expects: bigint for int8, Date for timestamp / timestamptz, text for an enum, Uint8Array for bytea, or SqlError in a listen queue type
@effect/sql-pg is a native wire-protocol client with its own result codecs: int8 is bigint, timestamps are Date, unregistered types such as enums are UTF-8 text, and listen queues are typed with SqlError.
Match the row Schema to those types or register a codec (enum arrays need one); wrap JSON parameters in sql.json; send one statement per query string; wrap listen consumers in Stream.retry.
Code from elsewhere fails with "Cannot find module" or missing exports
It was written for Effect 3 or imports a path that is not part of Effect 4.
Subsystems ship inside effect under effect/<area> (effect/http, effect/http-api, effect/rpc, effect/sql), Arbitrary comes from "effect", and the codecs live under effect/encoding/*; then follow the migration guide for Effect 3 code.
An Effect is a lazy description. Calling a function that returns an Effect, placing an Effect inside Effect.sync, or constructing one inside an unreturned callback does not execute it.
Contextual fragment — wrong and corrected composition.
Fragment · Type-checked with fixture
ts
// Wrong: the callback constructs an Effect and discards it.const wrong = Effect.sync(() => saveEmployee(employee))// Correct: compose the returned Effect.const correct = Effect.flatMap(validateEmployee(employee), saveEmployee)// Also correct inside Effect.gen: yield the operation.const correctGen = Effect.gen(function*() { const valid = yield* validateEmployee(employee) return yield* saveEmployee(valid)})
Run with Effect.runPromise, runSync, or a platform runMain only at an edge that owns the fiber and only after R is fully supplied. Calling a runner inside a service creates a separate root fiber with an empty context, so interruption, provided services (including TestClock), and the typed failure are all lost; Running effects at an owned edge has the runner table and the one safe shape for an unavoidable nested runner.
The opposite mistake looks the same from the outside: work that ran too early.Effect.succeed(Date.now()) and Effect.fail(buildError()) evaluate their argument while the program is being built, so every run and every retry replays one captured value. Use Effect.sync or Effect.suspend, and pin the behavior with a laziness test — build the effect, assert the spy count is 0, run it, assert 1 (Prove laziness and the static contract).
If a branch appears skipped, inspect the returned structure. Effect.when(self, condition) takes an Effect<boolean> — not a plain boolean and not a thunk — and returns Effect<Option<A>>, with Option.none() for the skipped case; there is no Effect.unless, Effect.if, Effect.whenEffect, or Effect.unlessEffect, so negate the condition or use an ordinary if inside Effect.gen (Branching and looping). Option/Result combinators can select another branch, and Effect.as changes only the success value—it does not execute a discarded Effect hidden in a callback. Passing a function by name can also skip or corrupt a call: Effect.forEach(ids, loadBand) invokes loadBand(id, index).
Official guide: Running Effects (it names the runFork result RuntimeFiber; it is Fiber<A, E>).
R is a set of unsatisfied service tags. Read a diagnostic such as Effect<User, DbError, Users | SqlClient> literally: the program still needs both services.
Contextual fragment — provide dependencies at the edge.
Fragment · Type-checked with fixture
ts
const UsersLive = Layer.effect(Users, makeUsers).pipe( Layer.provide(SqlLive) // SqlLive is used to build Users and is not re-exposed.)const main = program.pipe( Effect.provide(UsersLive))
Use Layer.provide(dependency) when the dependency exists only to construct that Layer. Use Layer.provideMerge(dependency) when the dependency must also remain in the output for other consumers. Layer.merge combines sibling outputs; it does not automatically feed one sibling into another.
Reuse the same named Layer value when several branches must share one pool or scoped resource. Layer memoization is based on object identity inside one build graph; reconstructing equivalent expressions can acquire separate instances. Sharing also needs one enclosing build: two sibling Effect.provide(PoolLive) calls — sequential or concurrent — build two pools, because each writes to its own memo map, while the same provides nested under an enclosing build of PoolLive reuse it. { local: true } and Layer.fresh rebuild on purpose. The measured matrix is in What is shared, and what is rebuilt.
A clean R is not proof of correct wiring. Clock, ConfigProvider, Console, Random, and Tracer are references with live defaults, so a forgotten test override compiles and silently uses the real one (Default services); and an Effect.provide(LiveLayer) buried inside reusable logic makes R look satisfied while hard-wiring production I/O into every test.
Do not silence a missing service with a cast. Find the tag in R, locate its implementation Layer, and decide whether it belongs under one component or at the application root.
Effect.fail(error) contributes to E. Effect.die(defect), thrown exceptions not captured by an Effect constructor, and impossible-state bugs are defects. Interruption records that a fiber was cancelled. All are represented in Cause, but ordinary typed recovery sees only failures.
Contextual fragment — preserve the intended channel.
Fragment · Type-checked with fixture
ts
const request = Effect.tryPromise({ try: () => fetch(url), catch: (cause) => new NetworkError({ cause })})const recovered = request.pipe( Effect.catchTag("NetworkError", () => cachedResponse))// Use at a deliberate boundary only: this removes NetworkError from E by// turning it into a defect. Effect.catchTag can no longer recover it afterward.const unrecoverable = request.pipe(Effect.orDie)
The fragment keeps the adapter short to show the channels. A production adapter also declares and forwards the signal that Effect.tryPromise offers — try: (signal) => fetch(url, { signal }) — because without the parameter no AbortController is created and an interrupted fiber leaves the request running (Cancellable adapters).
Defects come from Effect.die(value), from Effect.orDie, from a rejection inside Effect.promise, and from any throw the runtime catches outside a try constructor — inside Effect.sync, an Effect.map callback, or the body of Effect.gen. When a boundary promotes a typed failure deliberately, Effect.mapError it into a descriptive Error first so the defect is diagnosable.
Use Effect.exit when success/failure should become data and Effect.catchCause when cleanup, reporting, or a true boundary must examine the complete cause. Do not catch every Cause and pretend interruption or defects are ordinary domain failures; doing so can prevent shutdown and hide bugs.
A defect beside a typed failure wins. A Cause is a flat list of reasons and may hold a Failand a Die — a failing operation whose finalizer dies is the common case. Effect.catch, catchTag, match, result, retry, and orDie then do not recover: they turn the typed error into a defect and propagate both, so a crashing finalizer cannot be swallowed. An Interrupt beside a Fail does not block recovery, and the handler's result drops it. mapError maps every typed error in place. Where the interruption or a second failure matters, use Effect.catchCause and re-fail with Effect.failCause(cause) when Cause.hasInterrupts(cause); the truth table is in Recovering from a mixed Cause.
Where a boundary must survive a crash — a plugin host, a per-job worker — Effect.catchDefect is the narrow tool: typed failures and interruption pass through it untouched. Recover only the defect you recognize and re-raise the rest.
Boundary shape — isolate a recognized defect, re-die everything else.
Fragment · Type-checked
ts
import { Effect, Predicate } from "effect"declare const runBandImportPlugin: Effect.Effect<string, "BandFileMissing">const isolated = runBandImportPlugin.pipe( Effect.catchDefect((defect) => Predicate.isError(defect) && defect.name === "PluginCrash" ? Effect.logError("band import plugin crashed", { message: defect.message }).pipe( Effect.as("plugin disabled") ) : Effect.die(defect) // not ours: do not swallow an unknown bug ))
A value acquired with Effect.acquireRelease, Pool.get, ScopedCache.get, PubSub.subscribe, server Layers, or platform handles belongs to a Scope. The finalizer runs when that scope closes, regardless of success, typed failure, defect, or interruption.
Contextual fragment — keep acquisition and use under one scope.
Returning connection from Effect.scoped is a bug: its borrow has already ended. Return plain data, move the caller into the same scope, or expose the owned resource through a scoped Layer whose consumers run while that Layer is alive.
For a whole Effect application, use Layer.launch and a platform runMain. For repeated calls from a non-Effect host, use one ManagedRuntime and always call dispose() (or use await using). Do not allocate a new ManagedRuntime, pool, client Layer, or Scope per request unless isolation is intentional. dispose() is not a drain — it interrupts and awaits managed request fibers and their cleanup before releasing Layer resources — so stop admission and wait for in-flight work first (Bridge into a host that is not Effect).
Three more leak shapes have the same root, a lifetime nobody chose:
Scope left in R means nobody owns the lifetime yet. Each discharge (Effect.scoped, Layer.effect, a hand-made scope) is a decision about how long the resource lives; a Layer provided inside a request handler is acquired and released once per request (Write the ownership ledger first).
One acquireRelease per handle. The release is registered only after the acquire effect succeeds, so an acquire that opens two handles and fails on the second leaks the first (One bracket per resource).
Acquire inside a stream, never before it. A handle opened outside and closed "when the consumer is done" leaks on the first take(n) or decode failure (Owning resources inside a stream).
Finalizers are infallible by type and run uninterruptibly: a fallible close() needs a stated policy (log and ignore, bound then ignore, orDie, or report through acquireUseRelease), and an unbounded finalizer is an unbounded shutdown (When cleanup can fail).
One mistake keeps reappearing under different names: a closing action attached to the happy path only. Code placed after yield* work runs on success; Effect.tap plus Effect.tapError still misses interruption, which is how timeouts, races, and shutdown end work. Anything opened, incremented, awaited, or promised needs its closing action attached structurally — Scope, Effect.ensuring, Effect.acquireRelease, Effect.onExit, or "iterate the entries" — so success, typed failure, defect, and interruption all pass through it.
Instance
What goes wrong
Structural fix
Details
A Deferred completed after a fallible step
Waiters hang when the step fails or is interrupted
Complete it from Effect.onExit, or with the step's Exit
Fiber, Queue, Deferred, Latch, and TestClock hangs
A hang usually means the program has no event capable of satisfying its wait:
Fiber.join waits for that fiber’s completion. Joining a server, Effect.never, or an unbounded stream is intentionally permanent.
Queue.take waits for an element; a bounded Queue.offer waits for capacity. Supply a producer/consumer and call Queue.end or Queue.fail when the protocol finishes.
Deferred.await needs one completion path on every outcome. If completion follows a fallible operation, use Effect.exit/Deferred.complete or an ensuring/finalizer strategy.
Latch.await waits until open. Decide which supervised fiber owns Latch.open and what happens on its failure.
A bare SubscriptionRef.changes, PubSub stream, or Queue stream is live. Tests and finite consumers should use Stream.take, timeout, or an explicit end signal.
Queue.takeN(q, n) and Queue.takeBetween(q, min, max) wait for min while the queue is open. Closing the queue lets them drain a smaller final batch before the terminal error. Use takeBetween(q, 1, max) or takeAll when waiting for a full batch is not intended, and always check the returned length (Consuming).
A consumer blocked in take learns nothing from a producer fiber that died. Propagate a terminal signal with Queue.end, Queue.fail, or Queue.into(q) (Queue lifecycle).
Queue.shutdown interrupts pending take and Queue.await callers on an open queue, so their follow-up andThen steps never run. Pending single offers instead return false, and batch offers return their unaccepted suffix. An existing closing cause is preserved. Attach terminal reactions with Effect.onExit and observe consumers with Fiber.await.
A forked subscriber can miss the first events: forking only schedules the child, so a parent that publishes straight away runs first. Pass { startImmediately: true } or wait for a handshake (When a forked fiber starts).
Effect.race waits for the first success. A main task that fails while a never-ending side task is healthy leaves race waiting forever; use Effect.raceFirst (Running a side task).
Contextual fragment — virtual time must be driven from another fiber.
The deadlocking order is “join, then adjust”: execution can never reach the adjustment. @effect/vitest supplies TestClock to it.effect; use it.live only when real time is genuinely under test. TestClock.adjust gives initially forked fibers a scheduling turn before advancing. It also tracks tasks scheduled by each woken sleeper across yields and child forks, waiting for them to suspend before checking the next sleep (bounded by warningDelay). This is not a general readiness barrier for unrelated work. Do not count turns with Effect.yieldNow; have the operation announce each attempt and wait for that handshake before each adjustment (Synchronize on phases, not on turns). The warning "A test is using time, but is not advancing the test clock" indicates a missing adjustment; a busy-fiber warning means the wake tracker reached its live-time bound.
Prefer forkChild, forkScoped, FiberSet, FiberMap, or another owner-aware supervisor. forkDetach deliberately escapes the parent and should be rare; detached work can keep resources or business work alive beyond the request that created it. Name the owner first and the fork function follows (Choosing a fork by its owner); work that must outlive its request is transferred to a named, Layer-owned, bounded supervisor, never detached.
Official guide: Fibers (its prose calls Effect.yieldNow(); Effect.yieldNow is a value, and the guide does not mention the startImmediately fork option).
A buffer without a capacity is a memory leak waiting for load, a capacity without an overflow policy is an undecided design, and a loss nobody counts is invisible. Several defaults are unbounded, so "we never configured it" usually means "it has no limit". Audit these first when memory grows or a dependency is flooded:
Effect.retry reacts to typed failure, not defects, and reruns the entire wrapped Effect. Place it around the smallest idempotent operation, before orDie, and filter by retryability.
Contextual fragment — bounded and classified retry.
Do not retry validation errors, authentication/authorization failures, schema defects, or permanent 4xx responses. Respect provider backoff and Retry-After, add jitter for many clients, and cap attempts or elapsed duration.
Retried external writes are not automatically exactly once. Use an idempotency key, database uniqueness/transaction, or outbox. Workflow Activities are also delivered at least once until their completed Exit is durably recorded.
Four more ways a retry policy goes wrong, each owned elsewhere:
A defect is never retried, and must not be. Mapping every rejection of a foreign Promise to one retryable error makes a TypeError in the adapter look like an outage; recognize the failures the contract allows and Effect.die the rest (Cancellable adapters).
The options form can be a hot loop.Effect.retry(effect, { while: isTransient }) with no schedule and no times retries immediately and without limit (Shorthand options).
The side effect must be built inside the retried Effect. Retrying Effect.promise(() => pending) over a Promise created earlier replays one settled result (Retry policy checklist).
Timeout placement changes the meaning.Effect.timeout before retry bounds each attempt and turns TimeoutError into a retry input the policy must classify; after retry it bounds the whole operation (Where the timeout sits relative to retry).
Transport-specific retries have their own traps: HttpClient.retryTransient replays a POST as readily as a GET (HttpClient), a failed RPC call has an unknown outcome (RPC), and a model call must not be retried once output or a side effect exists (AiError).
For a Schema S, S["Encoded"] is the boundary representation and S["Type"] is the domain value after decoding. A transformation makes the distinction visible—Schema.NumberFromString is encoded as a string and decoded as a number.
Contextual fragment — decode inbound, encode outbound.
HttpApi decodes request params/query/payload before the handler and encodes handler successes/errors for the response. SqlSchema encodes its request before execute and decodes unknown driver rows afterward. Do not decode a value again merely because it crossed an internal function boundary.
Use Schema.Unknown only when the domain genuinely accepts arbitrary data. For numbers from untrusted input, choose the real domain: Schema.Finite, Schema.Int, Schema.Natural, or checks such as Schema.isBetween. Schema.Number accepts JavaScript NaN and infinities; it is not a default “safe JSON number” validator.
Three boundary mistakes compile cleanly and fail only at run time:
The excess-property policy was never chosen. The default onExcessProperty: "ignore" strips undeclared keys, so { id, admin: true } decodes successfully. That is right for a tolerant reader and wrong for a config file, a signed payload, or a PATCH body; decide per boundary and test it (Parse options are boundary policy).
A synchronous decoder inside Effect.sync.Effect.sync(() => Schema.decodeUnknownSync(S)(input)) has error type never, so bad input is a defect that no catchTag("SchemaError") can see; use Schema.decodeUnknownEffect(S)(input). Decoding and then orElseSucceed(default) hides malformed input behind a plausible value.
Absence, undefined, and null were treated as one state.Schema.optionalKey rejects an explicit undefined, withConstructorDefault never applies while decoding, and Schema.Option(S) is not a wire codec (Optional fields, null, and Option).
Effect separates capabilities from host implementations. Importing FileSystem, Path, HttpClient, or server interfaces gives types and operations, not a Node/Bun/Deno/browser implementation.
Typical outer-edge choices include:
Requirement
Example implementation Layer
outbound HttpClient
FetchHttpClient.layer, NodeHttpClient.layerUndici / layerNodeHttp, or the host equivalent
FileSystem
NodeFileSystem.layer, Bun/Deno equivalent, or FileSystem.layerNoop in a narrow test
Path
Path.layer
Node HTTP server
NodeHttpServer.layer(createServer, options)
terminal/worker/platform services
the corresponding @effect/platform-* Layer
Keep platform imports at composition roots. Domain services should depend on the capability interface, so tests can provide deterministic Layers without importing Node globals. The host decides more than the package: who owns the runtime, what cancels work, and whether cleanup is awaited differ between a process, a Web handler, a foreign framework callback, a browser page, and a test (Choosing a host). Quarantine platform imports and @stability unstableeffect/<area> imports behind an app-owned capability so a release that reshapes one becomes a one-file change (Keep platform and unstable imports behind a capability).
Keep application effect and @effect/* integration packages on the same release; compiler tooling such as @effect/tsgo has its own version line. Unstable packages share internal symbols, Schema types, Context tags, and peer dependencies; mixing release lines can produce huge structural errors or values that look identical but are not compatible.
Inspect the installed graph rather than only package.json:
Runnable diagnostic command.
sh
pnpm list --depth Infinity --json
Pin exact versions—no caret or tilde—for effect and every @effect/* runtime package, update them together, and install with the committed lockfile. Tool-only packages can have separately documented version lines, but their Effect peer must still resolve coherently. Install by exact version (Getting Started).
Mixed versions fail at run time as well as in the type checker. The internal type-id and service-key strings follow module paths (for example "~effect/Option" and "effect/http-api/..."), so a guard or a Context lookup from one copy of effect does not recognize values made by another copy or by a release that spelled the path differently.
Version skew between processes is a wire problem, not a type problem.SchemaBinary is the binary format for RPC, the default cluster runner transport, and EventLog journals and remote messages, and its bytes depend on the schemas and the codec version on both ends. Upgrade both peers of a binary link together, keep old journals readable by the release that wrote them until they are migrated, and rehearse mixed-version rollouts in staging; the per-package CHANGELOG.md files call out changes that alter bytes on the wire or on disk.
Record the exact package versions and lockfile, the inferred Effect<A, E, R>, the complete pretty-printed Cause/Exit, whether the program was interrupted, the owning Scope, and a minimal reproducer using the same platform Layer. For time/concurrency bugs, record the queue capacity/strategy, concurrency bound, fiber ownership, schedule, and whether TestClock or the live clock was installed.
This is the list to check generated or pasted code against. Each row names the shape to search for, why it is wrong, the preferred shape, and the section that owns the explanation. For a reviewer's yes/no version of the same material, use the Review Checklists.
Generated code most often breaks on a name carried over from Effect 3. Each of these fails to compile against this edition's audited release; use the Effect 4 spelling instead.
modules inside effect: FileSystem and Path from "effect", HTTP from "effect/http", and so on; host Layers from @effect/platform-node — see Getting Started
Expected output: two lines: Hello, Ada! and [test] Ada.
Before provision:greet("Ada") is Effect<string, never, GreetingService>.
After provision: each runnable program is Effect<string, never, never>.
Required Layers: exactly one implementation of GreetingService; no platform Layer is needed.
Lifetime and interruption: these Layers contain plain values and own no resources. If construction later uses Effect.acquireRelease, its finalizer is owned by the Layer scope and runs on failure or interruption.
Build frequency: each Effect.provide below is its own Layer build — sibling provides never share a memo map, so each call to Effect.provide(GreetingService.layer) builds that Layer again, independent of any other call. With Layer.succeed that costs nothing; once a Layer acquires a resource, two sibling provides mean two acquisitions, so a real application provides its composed graph once at the edge. See What is shared, and what is rebuilt.
Service contract:greet returns an Effect with R = never and no typed failure. Any implementation — live or test — must keep that shape: construction needs go into the Layer, expected failures go into E, and nothing throws.
Context.Service gives the capability one stable type-level key; Layer describes how an implementation is constructed and, when necessary, released. Business code depends on the capability, not a global singleton or a concrete client. Tests replace the Layer without changing the program.
Layer.succeed is enough here because both implementations are finished values. Reach for Layer.effect as soon as an implementation needs configuration, another service, state, or a resource with a finalizer; for a one-off value in a single test, Effect.provideService(GreetingService, fake) skips the Layer entirely. Providing one value or building a graph has the decision table, and Designing a service contract covers what belongs in the shape.
When the live implementation is itself an Effect (needs other services, Config, or a resource), the two-argument form Context.Service<Self>()(id, { make }) stores that constructor Effect on the class and infers the shape from it, so the usual Layer is Layer.effect(this, this.make) — see Declaring the constructor with make. Both forms produce the same kind of key; this recipe uses the explicit-shape form because GreetingService never needs a constructor Effect.
Official guide: Managing Layers extends this pattern to services with dependencies and to test injection (it names the dependency-free Layer layerWithoutDependencies; this handbook uses layerNoDeps).
Prove that the test Layer is actually wired. A test Layer that is declared but never provided still type-checks if something else satisfies the requirement, and the test passes against the wrong implementation. Make the assertion depend on state only the fake can produce. The fake below keeps its state in a Ref built by the Layer — so every Effect.provide starts clean — and exposes it through a small probe service:
Layer.provideMerge is deliberate: the probe must stay visible to the test, whereas a production dependency would be hidden with Layer.provide. Stubs, failure Layers, contract suites shared by the fake and the live adapter, and Layer.mock are covered in Testing & Dev Tooling and Testing an Effect Application.
Do not call Effect.runPromise inside greet, hide a client in a module-global variable, or pass dependencies manually through every function. Return Effects that retain GreetingService in R, compose all Layers once, and run only at the outer application boundary.
Two quieter versions of the same mistake:
Providing the live Layer inside business logic — greet(name).pipe(Effect.provide(GreetingService.layer)) inside a reusable function makes R look clean while hard-wiring the production implementation. Tests can no longer substitute it, and every call is a separate Layer build. Provide live implementations at the application edge and fakes at the test edge, nowhere else.
A fake that throws — greet: () => { throw new Error("down") } produces a defect, which no Effect.catchTag in the program under test can see. If the contract has an expected failure, declare it in E and have the fake return Effect.fail(...), so tests exercise the same channel as production.
For a component Layer that itself needs another service, use Layer.provide(dependency) beneath that component. Use Layer.provideMerge only when the dependency must also remain visible to sibling/top-level consumers.
Use one domain Schema across the HTTP contract and SQL result decoder, while keeping transport decoding and database access at their respective boundaries.
Classification: Runnable example; complete employees-api.ts. It uses an in-process HttpApi client and an embedded PGlite database, so no port or external database is required.
Core handler type: after EmployeeRepository is supplied, the HttpApi handler Layer has no business-service requirement. SqlSchema retains SchemaError | SqlError | NoSuchElementError; this recipe treats those as invariant/infrastructure defects at the repository boundary, so endpoint handlers expose no declared domain error.
Runnable program type:Effect<ReadonlyArray<Employee>, SqlError, never> because building the embedded database Layer can fail.
Required Layers: PGlite supplies generic SqlClient; EmployeeRepositoryLive uses it; HttpApiTest additionally needs Path, FileSystem, Etag.Generator, and HttpPlatform test Layers.
Lifetime and interruption: PGlite and the HttpApi test pipeline are scoped by their Layers. Interrupting the caller stops its Effect-side continuation; closing the scope closes the managed embedded database. A SqlClient.withTransaction region rolls back on failure or interruption.
Employee is the decoded domain value and the shared contract. HttpApi derives request decoding, response encoding, the typed client, routing, and OpenAPI shape from it. SqlSchema encodes requests before execution and decodes unknown driver rows back into Employee, preventing unchecked database objects from leaking inward. SqlClient remains an injected capability, so PGlite can be replaced by PostgreSQL without changing repository or handler code.
HttpApiTest.groups exercises real request encoding, routing, response encoding, and client decoding without opening a socket. It is stronger than directly invoking the handler and faster than an external integration server.
Production variation: a repository error and a declared conflict
The complete file turns every storage failure into a defect, which is right for a demo and too blunt for a service: a duplicate email is an outcome the caller can act on. The middle path keeps three things separate — what the repository owns, what the endpoint publishes, and what stays a defect.
Self-contained source · Type-checked
ts
import { type Cause, Context, Data, Effect, Layer, Schema } from "effect"import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"import { SqlClient, type SqlError, SqlSchema } from "effect/sql"class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, // The rule lives on the contract: HttpApi rejects a malformed email with 400 before the handler runs. email: Schema.String.check(Schema.isPattern(/^[^@\s]+@[^@\s]+$/))}) {}// Public: declared on the endpoint, serialized to clients — a tag and a safe identifier only.class EmployeeEmailTaken extends Schema.TaggedError<EmployeeEmailTaken>()( "EmployeeEmailTaken", { email: Schema.String }, { httpApiStatus: 409 }) {}// Internal: one stable repository failure that keeps the diagnostic cause. Never declared on an endpoint.class RepositoryError extends Data.TaggedError("RepositoryError")<{ readonly operation: string readonly cause: SqlError.SqlError | Schema.SchemaError | Cause.NoSuchElementError}> { violates(constraint: string): boolean { return this.cause._tag === "SqlError" && this.cause.reason._tag === "UniqueViolation" && this.cause.reason.constraint === constraint }}class EmployeeRepository extends Context.Service<EmployeeRepository, { readonly create: (employee: Employee) => Effect.Effect<Employee, RepositoryError>}>()("app/EmployeeRepository") {}export const EmployeeRepositoryLive = Layer.effect( EmployeeRepository, Effect.gen(function*() { const sql = yield* SqlClient.SqlClient const insert = SqlSchema.findOne({ Request: Employee, Result: Employee, execute: (employee) => sql`insert into employees (id, name, email) values (${employee.id}, ${employee.name}, ${employee.email}) returning id, name, email` }) return EmployeeRepository.of({ // mapError touches only the typed channel; defects and interruption pass through untouched. create: (employee) => insert(employee).pipe( Effect.mapError((cause) => new RepositoryError({ operation: "create", cause })) ) }) }))class Api extends HttpApi.make("employee-api").add( HttpApiGroup.make("employees").add( HttpApiEndpoint.post("create", "/employees", { payload: Employee, success: Employee, error: EmployeeEmailTaken }) )) {}export const EmployeesHandlers = HttpApiBuilder.group( Api, "employees", Effect.fn(function*(handlers) { const repository = yield* EmployeeRepository return handlers.handle("create", ({ payload }) => repository.create(payload).pipe( Effect.catchTag("RepositoryError", (error) => error.violates("employees_email_key") ? Effect.fail(new EmployeeEmailTaken({ email: payload.email })) // an intentional 409 : Effect.die(error)) // anything else: a sanitized 500, the full Cause in the server log )) }))
Probed on PGlite with the table declared as constraint employees_email_key unique (email): a second employee with the same email fails the typed client with EmployeeEmailTaken, while a duplicate primary key — also a UniqueViolation — stays a defect. Matching on the reason tag alone would have reported the wrong conflict; name your constraints and match on them.
Use Effect.mapError, not Effect.catchCause, at the repository seam.catchCause also captures defects and interruption, so a programming bug would be reported as a routine storage failure and a shutdown could be swallowed.
Absence is a successful empty result. Map NoSuchElementError to a declared 404 only for a lookup that ran and found nothing; a timeout or a lost connection is never "not found".
Decide what an unknown request field means. By default HttpApi drops a property the payload schema does not declare, so a client's misspelled optional field is silently ignored. Annotating the API with HttpApi.ParseOptions{ onExcessProperty: "error" } turns it into the same 400 as any other decode failure, matching the additionalProperties: false the OpenAPI document already advertises (HttpApi).
Split the schemas the moment they diverge. One Employee for the endpoint and the row decoder is honest while the public shape and the table coincide. When the table gains an internal column, or a field is renamed, keep a row schema for SqlSchema and a DTO for the endpoint, and map between them in the repository — the public contract must not move because a column did.
HttpApiTest proves codecs, routing, and status mapping, but its typed client cannot send malformed input — encoding fails locally first. To prove that validation lives on the contract, send a raw request through HttpRouter.toWebHandler and assert both the 400 and that a counting repository fake was never called; the full test is in What each test ring proves.
Do not cast driver rows to Employee, manually parse JSON in handlers, interpolate untrusted SQL text with string concatenation, or define separate request/response/database interfaces that silently drift. Parameterize values with the sql tag, decode every untrusted boundary with Schema, and map only intentional database failures into declared endpoint errors; unexpected invariant failures should remain visible.
Use a bounded Queue for producer backpressure, a fixed number of supervised consumers for concurrency, and acquireUseRelease around each resource-owning job.
Required Layers: none; Clock is a default runtime reference used by Effect.sleep.
Lifetime and interruption: each job release action runs on success, failure, or interruption. Worker fibers are children of the producer program, and the Queue’s done signal terminates their streams. Interrupting the parent interrupts the workers and releases any active job resources.
The Queue owns buffering and backpressure; the two consumers define actual concurrency. Effect.acquireUseRelease owns the per-job resource even though processing can be interrupted. Queue.end is an explicit protocol event, so consumers do not remain blocked forever after the producer finishes.
Three details carry more weight than they appear to:
Overflow is the queue's contract.Queue.bounded(2) suspends offerAll when two jobs are waiting, so the producer is paced by the workers and nothing is lost. Queue.dropping or Queue.sliding in the same position would turn this worker into a lossy one; choose them only as a stated policy and count what they shed, as described in Make loss observable.
concurrency: "unbounded" is safe here only because the collection is the bound.Effect.all([worker, worker], …) starts exactly two fibers; the number of workers is the limit. The same option over one effect per job would start a fiber per job and defeat the queue.
Release runs on every exit of use.Effect.acquireUseRelease runs the release action on success, typed failure, defect, and interruption — including a use function that throws synchronously before returning an Effect — and a failure inside the release action is combined with the original failure rather than replacing it. That is why released reaches 5 without any try/finally.
In a larger program, give the producer a Queue.Enqueue<Job, Cause.Done> and each worker a Queue.Dequeue<Job, Cause.Done> so that only the wiring code can both offer and take; see Put queue roles in function signatures. If the producer is an independent fiber that can fail, pipe it through Queue.into(queue) so its failure reaches the workers instead of leaving them blocked in take.
For a single finite input where buffering is unnecessary, Effect.forEach(jobs, processJob, { concurrency: 2 }) is simpler. Use the Queue shape when producers and consumers have independent lifetimes, input arrives over time, or capacity itself is operationally important. Structured Concurrency Through a Bounded Worker builds the same design step by step, including failure policy and shutdown.
Avoid Effect.all(jobs.map(processJob), { concurrency: "unbounded" }) over uncontrolled input, a growing module-level array as a mailbox, or manual acquire/release calls with release only on the success path. Also do not confuse a Queue with PubSub: Queue distributes work among consumers; PubSub copies each event to every subscriber.
Expected output:{"value":"ready","attempts":3} immediately; no three-second wall-clock wait.
Before provision: the test program is Effect<Result, TransientError, never>. Clock is a defaulted context reference, so using time does not add a compile-time requirement.
After provision:Effect<Result, TransientError, never>. Retry does not erase the final typed error because all attempts can still fail.
Required Layers: none at the type level. Provide TestClock.layer() to replace the live Clock reference with controllable virtual time; calling TestClock-only controls without installing it is unsupported and can defect.
Lifetime and interruption: the retrying Effect runs in a child fiber. Interrupting the parent interrupts the current attempt and cancels future retries. TestClock state lives for the provided Layer scope.
What the complete file proves: the fork–adjust–join mechanics and that a retryable error eventually succeeds. What it does not prove: the delays between attempts or the non-retryable path. Assert the shape of the policy adds both.
Effect.retry reacts to typed TransientError; the Schedule owns classification, delay, and the hard recurrence bound. TestClock replaces time at the service boundary, so the same retry implementation is tested without sleeps or timing races. Forking is essential because TestClock.adjust must execute while the retrying fiber is suspended.
In @effect/vitest, it.effect already provides TestClock and TestConsole. The fork-adjust-join ordering is the same.
A retry policy is a specification, and {"value":"ready","attempts":3} checks very little of it. That expectation also passes for a policy with no backoff at all, for one that retries permanent errors, and for one with the wrong multiplier. Test the two paths the policy distinguishes, and record when each attempt ran:
Retryable path: every attempt reports its number and Clock.currentTimeMillis; assert the exact virtual timeline — 0, 1000, 3000 for Schedule.exponential("1 second") bounded to two recurrences.
Non-retryable path: the same harness with retryable: false must record exactly one attempt at time zero and leave the TransientError in E.
Handshake before every adjustment. The operation offers each attempt to a Queue; the test takes that attempt before it moves the clock. The test then never depends on how many scheduler turns the retrying fiber needs to reach its next sleep.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Clock, Effect, Fiber, Queue, Schedule, Schema } from "effect"import { TestClock } from "effect/testing"class TransientError extends Schema.TaggedError<TransientError>()( "TransientError", { attempt: Schema.Int, retryable: Schema.Boolean }) {}// The asserted policy has no jitter; compose Schedule.jittered only where production uses it.const retryPolicy = Schedule.exponential("1 second").pipe( Schedule.setInputType<TransientError>(), Schedule.while(({ input }) => input.retryable), Schedule.upTo({ times: 2 }))interface Attempt { readonly attempt: number readonly at: number}// Every attempt reports its number and the virtual time at which it ran.const makeOperation = (options: { readonly retryable: boolean; readonly succeedOn: number }) => Effect.gen(function*() { const attempts = yield* Queue.unbounded<Attempt>() let count = 0 const operation = Effect.gen(function*() { const attempt = ++count yield* Queue.offer(attempts, { attempt, at: yield* Clock.currentTimeMillis }) if (attempt < options.succeedOn) { return yield* new TransientError({ attempt, retryable: options.retryable }) } return "ready" }) return { attempts, operation } })it.effect("retryable failures follow the exponential timeline", () => Effect.gen(function*() { const { attempts, operation } = yield* makeOperation({ retryable: true, succeedOn: 3 }) const fiber = yield* operation.pipe(Effect.retry(retryPolicy), Effect.forkChild) // Wait for each attempt before moving time: a handshake, not a scheduler guess. const first = yield* Queue.take(attempts) yield* TestClock.adjust("1 second") const second = yield* Queue.take(attempts) yield* TestClock.adjust("2 seconds") const third = yield* Queue.take(attempts) assert.deepStrictEqual([first, second, third], [ { attempt: 1, at: 0 }, { attempt: 2, at: 1_000 }, { attempt: 3, at: 3_000 } ]) assert.strictEqual(yield* Fiber.join(fiber), "ready") }))it.effect("a non-retryable failure is attempted once and stays typed", () => Effect.gen(function*() { const { attempts, operation } = yield* makeOperation({ retryable: false, succeedOn: 3 }) const fiber = yield* operation.pipe(Effect.retry(retryPolicy), Effect.flip, Effect.forkChild) // A policy that wrongly retried would use this time and record more attempts. yield* TestClock.adjust("10 seconds") const error = yield* Fiber.join(fiber) assert.strictEqual(error._tag, "TransientError") assert.strictEqual(error.retryable, false) assert.deepStrictEqual(yield* Queue.clear(attempts), [{ attempt: 1, at: 0 }]) }))
Both tests fail fast against the policies they are meant to reject: replacing the backoff with Schedule.forever records attempts two and three at time 0, and deleting the Schedule.while line lets the second test's operation succeed on its third attempt, so Effect.flip reports the unexpected success. Add a third case for exhaustion — an error that never clears must surface the last TransientError after exactly three attempts. The unbounded queue is safe here because the attempt bound is the policy itself. Scheduling & Time lists the same checks as a policy checklist.
Do not call Effect.orDie before retry, retry every error indefinitely, use setTimeout in tests, or join the sleeping fiber before adjusting time. External writes also need idempotency even with a correct Schedule: retry provides at-least-once attempts, not exactly-once effects.
Two more mistakes are specific to virtual time:
Adjusting the clock before forking. A sleep is registered relative to the clock's current reading, so TestClock.adjust("10 seconds") followed by the fork leaves the first retry delay entirely in the future and Fiber.join never returns. Fork first, then adjust.
Asserting a jittered policy.Schedule.jittered scales every delay by a random factor between 0.8 and 1.2, so an exact timeline is no longer deterministic. Keep jitter out of the policy under test and add it in the production composition, or pin the generator with Random.withSeed and advance by the full jittered delay.
Run locally: Node 26+: OTEL_EXPORTER_OTLP_ENDPOINT= node observability.ts
Run with an OTLP collector:OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 node observability.ts
Expected local output: one JSON log event containing order accepted, service=orders, and orderId=ord-42, followed by {"orderId":"ord-42","status":"accepted"}. Timestamp and fiber/span identifiers vary.
Program type: after the observability Layer is supplied, Effect<OrderResult, Config.ConfigError, never>; configuration-provider or string-decoding failures remain typed startup failures. This example does not validate URL syntax.
Required Layers: local mode installs Logger.consoleJson plus Logger.tracerLogger and runtime metrics. OTLP mode additionally provides FetchHttpClient.layer internally.
Lifetime and interruption: OTLP log/metric/span exporters are scoped. Layer shutdown flushes registered exporters, and each flush is bounded by shutdownTimeout (3 seconds here, which is also the default): with an unreachable collector the process still exits about three seconds after the work finishes instead of hanging, and whatever was still buffered is dropped. Process interruption reaches Layer finalizers. The local JSON logger has no acquired resource.
Local collector: the official Tracing guide shows a single-container Grafana stack that accepts OTLP on port 4318 and how to find the trace in it. Where that guide and the edition's tagged source disagree, this recipe and the source win.
Logs, spans, and metrics are fiber-aware Effect operations, so annotations and parent spans propagate without parameter plumbing. The exporter remains a Layer: tests can omit it, local runs can use JSON, and production can install OTLP without changing business logic. Otlp.layerJson is the compact default for all three signals and owns batching, HTTP export, retry behavior, and shutdown flush. Reach for the separate @effect/opentelemetry package's NodeSdk (imported from @effect/opentelemetry/NodeSdk; the package root does not re-export it) instead only when an existing OpenTelemetry setup (its SDK config, its exporters, its instrumentation) is already in place; new projects use effect/observability's Otlp.
Define metric values at module scope so updates with the same name/attributes share one registry entry. Avoid sensitive identifiers in annotations unless the telemetry policy explicitly permits them.
Three details in the file are deliberate:
The span name is the operation, the order id is an attribute.orders.accept stays one operation in every backend view; order.id rides along as a span attribute and a log annotation, where per-event detail belongs. The counter has no order label at all — every distinct attribute value on a metric is a separate time series, so metric attributes must come from a small, fixed vocabulary (see Cardinality).
Logger.layer([...]) replaces the active logger set, which by default is Logger.defaultLogger plus Logger.tracerLogger. Listing only Logger.consoleJson would silently stop log calls from becoming span events; the local branch therefore lists tracerLogger again. The OTLP branch needs no such care because Otlp.layerJson adds its logger with loggerMergeWithExisting: true by default, which is also why the default text logger keeps printing there.
The exporter has one owner and a deadline. One Otlp Layer is provided at the root, and shutdownTimeout bounds how long its scope may hold the process open. Export is best effort: after a failed export the exporter drops its buffer and disables itself for 60 seconds, so treat telemetry as explanation, never as an audit trail or a readiness signal.
This example reads one variable by hand to pick a branch, not to configure the exporter.Otlp.layerFromConfig reads OTEL_EXPORTER_OTLP_ENDPOINT (and the per-signal OTEL_EXPORTER_OTLP_{LOGS,METRICS,TRACES}_ENDPOINT/_HEADERS variants) itself; reach for it instead of Otlp.layer/layerJson when the deployment already follows the OpenTelemetry environment-variable convention.
Every metric attribute has a bounded vocabulary and a series ceiling; ids, raw paths, and error text live on spans and logs only.
Every logged or exported field is on an allow-list; secrets travel as Redacted and are never unwrapped into telemetry (see Privacy).
Each signal has exactly one export path — no SDK bridge and direct OTLP for the same signal (see One export path per signal).
The observability Layer is provided to the application Layer, not merged beside it, so eager fibers and finalizers log through it (see Layer order and shutdown).
Sampling has a named owner, and SLIs come from metrics rather than sampled spans.
The collector is not part of any readiness check, and the process exits within its termination grace period with the collector down.
A test asserts on recorded log fields, span structure, and Metric.value — see Verifying telemetry.
Do not scatter vendor SDK calls, console.log, Date.now, or exporter construction through service methods. Do not create an OTLP Layer per request. Provide one observability graph at the application root, use Effect.withSpan/Effect.fn, structured log annotations, and Metric operations inside the program, and let the owning Scope flush and close exporters.
Represent the long-lived application as a Layer, put every background fiber and acquired handle under its Scope, then hand the launched Layer to NodeRuntime.runMain.
Official guides:Guidelines (why runMain rather than runPromise). Where that guide and the edition's tagged source disagree, this page and the source win.
Expected output:worker started; then heartbeat every second. Press Ctrl+C or send SIGTERM and it prints worker stopped before exit.
Program type:Layer.launch(WorkerLive) is Effect<never, never, never> after the Layer has no unsatisfied dependencies.
Required Layers:WorkerLive is the application Layer. Real production workers may additionally require Config, database, HTTP, and observability Layers.
Lifetime and interruption:NodeRuntime.runMain installs SIGINT/SIGTERM handling and interrupts the main fiber. Layer.launch closes the Layer scope; the scoped child is interrupted and its finalizer runs.
Exit code:0 on success, 130 when the Cause holds only interruptions (the Ctrl+C / SIGTERM path here), otherwise the failing error's [Runtime.errorExitCode] or 1. An interruption annotated with Runtime.InterruptExitCode uses that code instead of 130 when every interruption in the Cause carries one (the largest wins). The runner calls process.exit only after teardown, and only when a signal arrived or the code is non-zero.
Layer.effectDiscard describes startup and scoped background work without exposing a service. forkScoped attaches the heartbeat to the Layer scope; addFinalizer declares cleanup beside acquisition. Layer.launch keeps that scope alive, and the platform runner translates process signals into Effect interruption before process teardown.
An HTTP server, Queue consumer, Cluster runner, or OTLP exporter follows the same shape: merge all live Layers, provide their dependencies once, launch the combined Layer, and run that one main Effect.
Effect.addFinalizer receives the Exit that closed the scope, so cleanup can tell a clean stop from a crash: Exit.isSuccess(exit), Exit.hasInterrupts(exit) for a signal, anything else for a failure. A finalizer's error type is never — decide up front whether a failed cleanup is logged and ignored, bounded with Effect.timeout, or promoted to a defect.
The core runtime keeps the process alive on its own now — a reference-counted keep-alive is built into every fiber, so runFork and runPromise no longer exit early while a fiber is suspended on something like Deferred.await. runMain is still the right call for process entrypoints, but for signal handling, exit codes, and error reporting rather than for keeping the process up. What it adds on top of runFork, all of it replaceable through its options:
Behavior
Default
Override
Signals
SIGINT and SIGTERM interrupt the main fiber. A repeated signal does not force an exit: the process ends when the finalizers do, so every finalizer needs its own bound.
none — give slow finalizers a timeout
Error reporting
A failure that is not interruption-only is logged once with Effect.logError
disableErrorReporting: true, or set [Runtime.errorReported] = false on an error class that was already reported
Exit code
Runtime.defaultTeardown: 0 / 130 / [Runtime.errorExitCode] or 1
teardown: (exit, onExit) => …; or, for a component that ends the program by interrupting the main fiber on purpose, Fiber.interruptAs(fiber, undefined, Context.make(Runtime.InterruptExitCode, 0)) — RPC and MCP stdio servers do this after stdin closes, so they exit 0
Official guide: Runtime (platform). The tagged source additionally uses 130 for an interruption-only exit and listens for SIGTERM as well as SIGINT; this page follows the source. The runner itself is described in Core Runtime & Execution.
The file above stops instantly because a heartbeat has nothing to finish. A worker that holds admitted jobs needs three more things, and none of them is a second shutdown code path — shutdown order is just Layer order, reversed, and finalizer order within one Layer, reversed:
Fragment · Type-checked
ts
import { NodeRuntime } from "@effect/platform-node"import { Context, Effect, FiberSet, Layer, Ref } from "effect"type Phase = "starting" | "ready" | "draining"class Lifecycle extends Context.Service<Lifecycle, Ref.Ref<Phase>>()("app/Lifecycle") { static layer = Layer.effect(Lifecycle, Ref.make<Phase>("starting"))}declare const nextApproval: Effect.Effect<string> // suspends until intake has workdeclare const applyRaise: (approvalId: string) => Effect.Effect<void>const WorkerLive = Layer.effectDiscard( Effect.gen(function*() { // Released 3rd: survivors of the drain are interrupted, and awaited. const inFlight = yield* FiberSet.make() // Released 2nd: admitted jobs get a bounded chance to finish. yield* Effect.addFinalizer(() => FiberSet.awaitEmpty(inFlight).pipe(Effect.timeoutOption("10 seconds")) ) // Released 1st: intake stops, so the set can only shrink. yield* Effect.forkScoped( Effect.forever( Effect.flatMap(nextApproval, (approvalId) => FiberSet.run(inFlight, applyRaise(approvalId))) ) ) }))// Acquired last, released first: "ready" is true only while everything below it is up.const ReadyLive = Layer.effectDiscard( Effect.gen(function*() { const phase = yield* Lifecycle yield* Effect.acquireRelease(Ref.set(phase, "ready"), () => Ref.set(phase, "draining")) }))const MainLive = ReadyLive.pipe( Layer.provideMerge(WorkerLive), Layer.provideMerge(Lifecycle.layer))NodeRuntime.runMain(Layer.launch(MainLive))
Layer.provide and Layer.provideMerge build the provided Layer first, so MainLive starts Lifecycle, then the worker, then flips to "ready"; a signal flips to "draining", stops intake, drains for at most ten seconds, interrupts what is left, and only then releases whatever the worker depended on. A readiness endpoint reads the Ref; liveness never does.
Size the drain below the platform's grace period. Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds (30 by default), then SIGKILL — which no finalizer survives. In a container, make sure the process that receives the signal is Node (exec form, or an init that forwards signals), or none of this runs. The full treatment, including how to test the drain bound with TestClock, is Owning Lifetimes — Startup, Readiness, and Shutdown.
Do not call process.exit() from business code, maintain a separate array of ad-hoc cleanup callbacks, use forkDetach for ordinary workers, or start a server outside Effect and hope its callbacks shut down in the right order. Abrupt exit can skip finalizers and telemetry flushes. Keep ownership in Scope and let interruption unwind it.
Do not end the entrypoint with Effect.runPromise(main). Nothing listens for signals, so Ctrl+C takes Node's default action and the process dies with every finalizer unrun. Do not publish readiness before the last dependency is acquired, or leave it true while draining: both route traffic to a process that cannot serve it.
Decisions & RecipesPage 45 of 66
Recipe: ManagedRuntime at an Imperative Boundary
Build the service graph once, call it from Promise-based callbacks many times, and dispose it when the host application stops.
Official guides:Runtime. Where that guide and the edition's tagged source disagree, this page and the source win.
Expected output:Hello, Ada, Hello, Grace, then runtime disposed.
Before the bridge:greet(name) is Effect<string, never, GreetingService>.
At the bridge:runtime.runPromise(greet(name)) is Promise<string>; the runtime’s construction error is never in this example.
Required Layers:GreetingLive is captured by the ManagedRuntime.
Lifetime and interruption: the Layer is built lazily on first use and cached across calls. await using invokes Symbol.asyncDispose at block exit, closing the runtime scope and all Layer resources. A fiber returned by runFork still needs an ownership/cancellation policy.
Cancellation: the asynchronous runners take { signal } as their second argument; runSync and runSyncExit accept no run options. Aborting the signal interrupts that run's fiber. The minimal file below omits it because nothing here can be cancelled — a real request handler must not. Recipe: Request Cancellation Through a Host is the runnable proof.
Disposal is not a drain:dispose() interrupts every fiber the runtime started and waits for them — and their finalizers — to finish, and only then releases the Layer; a second dispose() is a no-op; and any later run dies with ManagedRuntime disposed. Stop admitting work and wait for it first.
import { Context, Effect, Layer, ManagedRuntime } from "effect"class GreetingService extends Context.Service<GreetingService, { readonly greet: (name: string) => Effect.Effect<string>}>()("app/GreetingService") {}const GreetingLive = Layer.succeed(GreetingService)({ greet: (name) => Effect.succeed(`Hello, ${name}`)})const greet = (name: string): Effect.Effect<string, never, GreetingService> => Effect.flatMap(GreetingService, (service) => service.greet(name))async function hostApplication() { await using runtime = ManagedRuntime.make(GreetingLive) // These could be framework event handlers, job-runner callbacks, or methods // on a library whose public contract must return native Promises. const onRequest = (name: string): Promise<string> => runtime.runPromise(greet(name)) console.log(await onRequest("Ada")) console.log(await onRequest("Grace"))}await hostApplication()console.log("runtime disposed")
If the host cannot use explicit resource management, create one runtime at application startup and call await runtime.dispose() from the host’s shutdown hook. Do not create a runtime for every request.
The complete file shows the lifetime. A real host adds four obligations around it, and each is one line: warm the runtime at boot, admit or refuse before doing work, forward the host's AbortSignal, and make shutdown one memoized operation that stops intake, drains with a bound, and only then disposes.
Fragment · Type-checked
ts
import { Cause, Context, Data, Effect, Exit, ManagedRuntime } from "effect"import type { Layer } from "effect"class RaiseRejected extends Data.TaggedError("RaiseRejected")<{ readonly reason: string}> {}class Compensation extends Context.Service<Compensation, { readonly approveRaise: (input: unknown) => Effect.Effect<string, RaiseRejected>}>()("app/Compensation") {}declare const AppLive: Layer.Layer<Compensation>interface HostResponse { readonly status: number readonly body: string}const runtime = ManagedRuntime.make(AppLive)let accepting = trueconst inFlight = new Set<Promise<unknown>>()// Warm: pay Layer acquisition at boot, so a broken deployment fails its start-up probe.export const onBoot = (): Promise<void> => runtime.runPromise(Effect.void)export const onRequest = (input: unknown, signal: AbortSignal): Promise<HostResponse> => { // Admit: refuse before any work starts. An aborted signal would still run the synchronous prefix. if (!accepting) return Promise.resolve({ status: 503, body: "shutting down" }) if (signal.aborted) return Promise.resolve({ status: 499, body: "client closed request" }) const response = runtime // Forward: the host's abort becomes fiber interruption. .runPromiseExit(Compensation.use((service) => service.approveRaise(input)), { signal }) .then((exit): HostResponse => { if (Exit.isSuccess(exit)) return { status: 200, body: exit.value } // An interrupt-only Exit says "cancelled", not by whom. The host knows: client or shutdown. if (Cause.hasInterruptsOnly(exit.cause)) { return signal.aborted ? { status: 499, body: "client closed request" } : { status: 503, body: "shutting down" } } const rejected = Cause.findErrorOption(exit.cause) return rejected._tag === "Some" ? { status: 422, body: rejected.value.reason } : { status: 500, body: "internal error" } }) inFlight.add(response) return response.finally(() => inFlight.delete(response))}const settleWithin = (work: Promise<unknown>, millis: number): Promise<void> => new Promise((resolve) => { const timer = setTimeout(resolve, millis) void work.finally(() => { clearTimeout(timer) resolve() }) })// One shutdown: hot reload and double signal handlers all get the same Promise.let stopping: Promise<void> | undefinedexport const onShutdown = (): Promise<void> => stopping ??= (async () => { accepting = false // 1. stop intake, synchronously await settleWithin(Promise.allSettled(inFlight), 10_000) // 2. drain, with a bound await runtime.dispose() // 3. interrupt survivors, release the Layer })()
Register before shutdown can miss it.inFlight.add happens in the same synchronous turn as the admission check, so there is no window in which onShutdown sees an empty set while a request is starting.
Choose how failures cross the boundary once.runPromiseExit keeps typed failure, defect, and interruption apart; runPromise rejects with a squashed error and loses that distinction. Use it only when the host's contract really is "reject on anything".
A failed build is permanent. The build runs once and its failure is cached: every later run on that runtime fails the same way. Treat a failed onBoot as a failed start-up, not as something the next request will retry.
Size the drain below the platform's grace period (Kubernetes terminationGracePeriodSeconds, a serverless shutdown hook), leaving room for dispose() and finalizers.
Test the host lifecycle, not just one request. Give the Layer an acquisition counter and a release counter, then assert three things: many requests, including concurrent first requests, leave acquired = 1; after onShutdown()released = 1; after a second onShutdown() it is still 1. Those reject a runtime per request, a missing dispose, and a non-idempotent hook. For cancellation, abort on an "in flight" latch and await a cleanup gate rather than sleeping after the abort — the cancellation recipe is that test written as a program.
ManagedRuntime is the deliberate seam from Effect to a host that controls invocation: UI callbacks, existing Promise frameworks, plugin hooks, or gradual migration. It provides the same built Layer context to every run and gives that context one explicit lifetime.
Do not sprinkle Effect.runPromise(effect.pipe(Effect.provide(layer))) throughout handlers. That can rebuild expensive Layers on every call and makes cleanup easy to forget.
Do not ignore the host's abort signal. runtime.runPromise(effect) without { signal } keeps working for a client that has left, holding a pool slot and rate-limit budget; and a tryPromise adapter that does not pass Effect's own signal to the SDK leaves the socket open even after the fiber is interrupted. Both hops are needed.
Do not call dispose() as the first step of graceful shutdown, and never start an interior Effect.runFork "so the work survives the request": disposal interrupts in-flight requests and awaits their cleanup before releasing dependencies, rather than letting requests finish normally; an interior runner creates a fiber no scope owns. Work that must outlive a request is handed to a Layer-owned supervisor (a bounded queue and a scoped worker) inside the same runtime.
Conversely, when the whole application is already Effect, do not add ManagedRuntime: compose the live Layers, use Layer.launch for long-lived infrastructure, and call the platform runMain once.
When a framework that is not Effect owns the request — Express, Hono, a queue SDK, a plugin API — a client disconnect has to travel two hops before any work actually stops: from the host's AbortSignal into the Effect fiber, and from that fiber into the Promise-based SDK call at the bottom. This recipe wires both hops through one ManagedRuntime and proves each one in its output.
Classification: Runnable example; complete request-cancellation.ts. No network, no timers longer than 25 ms.
Install:pnpm add effect@4.1.4
Run: Node 26+: node request-cancellation.ts
Before the bridge:compBand(employeeId) is Effect<string, HrisUnavailable, HrisDirectory>.
At the bridge:runtime.runPromiseExit(effect, { signal }) is Promise<Exit<string, HrisUnavailable>>. It never rejects, so the host maps success, interruption, and typed failure to three different responses.
Hop one (host → fiber): the signal run option interrupts the fiber when the host aborts. The asynchronous runners on ManagedRuntime and Effect accept it; runSync and runSyncExit do not accept run options.
Hop two (fiber → SDK):Effect.tryPromise hands its callback an AbortSignal that Effect aborts when the fiber is interrupted. It is a different signal from the host's; pass it to the SDK.
Required Layers:HrisDirectory.layer, captured once by the ManagedRuntime.
Lifetime and interruption: the Layer is acquired on the first request and released by runtime.dispose(). The request-scoped permit is released on every exit path, and its finalizer sees the interrupt-only Exit. An aborted request leaves the runtime fully usable.
Expected output (exact):
text
layer: HRIS directory acquired effect: rate-limit permit taken sdk: lookup emp-1042 in flighthost: client disconnected, aborting request 1 sdk: lookup emp-1042 aborted, socket freed effect: rate-limit permit returned (interrupted)host: request 1 -> 499 client closed request effect: rate-limit permit taken sdk: lookup emp-2077 in flight effect: rate-limit permit returned (success)host: request 2 -> 200 emp-2077 is in band L5layer: HRIS directory releasedhost: runtime disposed
Cancellation is only as good as its weakest hop. The host knows the client left; the SDK holds the socket. Effect sits between them and owns the fiber, so it needs an input (the run option) and an output (the adapter's signal). Interruption then does the rest: it aborts the adapter's controller, runs the request scope's finalizers with the interrupt-only Exit, and completes the fiber — in that order, which is why the output shows the SDK abort before the permit is returned.
runPromiseExit keeps the three outcomes apart.runPromise would reject an aborted request with a plain Error: All fibers interrupted without error, which a framework's error middleware turns into a 500 and a log line for something that is not a fault. Matching on Exit lets interruption become a quiet 499, a typed failure become a 503, and success a 200. Cause.hasInterruptsOnly is the right test: a Cause that also carries a failure or defect is not a clean cancellation.
One runtime, many requests. The Layer line prints once and the second request succeeds after the first was interrupted. Interrupting a request fiber closes that request's scope only; the runtime's scope, and everything the Layer acquired, is untouched until dispose().
permit returned (interrupted) and 499, but no sdk: … aborted line — the lookup keeps running and settles later with nobody listening
Effect looks cancelled while the socket, pool slot, or upstream rate-limit budget stays occupied. This is the version that survives code review.
Effect.tryPromise (and Effect.promise) only create the AbortController when the callback declares a parameter, so () => fetch(url) is not merely ignoring a signal — none exists. On interruption the fiber moves on immediately and the orphaned Promise finishes in the background.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const lookupBand: (employeeId: string, signal?: AbortSignal) => Promise<string>// Interruptible all the way down: the SDK sees the abort.const forwarded = Effect.tryPromise((signal) => lookupBand("emp-1042", signal))// Interruptible only on the Effect side: the lookup is orphaned, not cancelled.const orphaned = Effect.tryPromise(() => lookupBand("emp-1042"))
The constructor-level mechanics (Effect.callback, Effect.promise, the run options) are defined in Core Runtime & Execution; this recipe is only the seam.
The host has no AbortSignal. Node's http.ServerResponse (and therefore Express) emits close instead. Create one AbortController per request, abort it from that listener when response.writableEnded is still false, and pass controller.signal as the run option — the same test Effect's own Node server uses. A host deadline is one more abort source: combine them with AbortSignal.any([...]), or keep the deadline inside the Effect with Effect.timeout so TestClock can drive it.
An already-aborted request. Check signal.aborted in the host before calling the runtime. With an aborted signal Effect still starts the fiber and interrupts it at its first asynchronous boundary, so the synchronous prefix runs — and an Effect with no asynchronous step completes normally.
The SDK's cancel is itself asynchronous. Use Effect.callback and return the cancel as the cleanup Effect. Interruption awaits that cleanup, so the host's Promise stays pending until the driver confirms — which is what rules out "completed after it was cancelled". Effect.tryPromise does not wait: it aborts and moves on.
The host wants a rejection, not an Exit. Keep runPromise, but catch at the adapter and test the abort yourself (signal.aborted), because the rejection value is an ordinary Error, not a Cause.
An Effect-native server needs only hop two.NodeHttpServer interrupts the request fiber when the client closes the connection, and HttpEffect.toWebHandler listens to request.signal. The interrupt lands only in interruptible code: HttpRouter routes and HttpApi handlers are interruptible by default, but an app handed directly to HttpServer.serve or toWebHandler runs uninterruptibly until it has a response, so wrap it in Effect.interruptible. This recipe is for hosts that Effect does not own; see HTTP Server.
Testing the seam. Three assertions reject the three common mistakes: count Layer acquisitions across many requests (must be 1 — not a runtime per request); count releases after calling dispose() twice (must be 1 — disposal happened, and is idempotent); and for cancellation, abort on an "in flight" latch and await a cleanup gate, as the file above does, instead of sleeping after the abort.
Shutting the host down.runtime.dispose() interrupts managed request fibers and awaits their cleanup before releasing Layer resources. Stop admitting requests and drain first: Recipe: ManagedRuntime at an Imperative Boundary has the protocol and Owning Lifetimes explains why.
Commit a domain change and the event that announces it in one SQL transaction, then deliver the event after commit with honest at-least-once semantics.
Classification: Runnable example; complete raise-outbox.ts. It runs on an embedded PGlite database and a scripted in-memory broker, so no network, port, or Docker is required.
Expected output: six JSON lines, reproduced byte for byte under Expected output.
Before provision:program is Effect<Array<unknown>, EmployeeNotFound | MeritBudgetExceeded | RepositoryError, Raises | Outbox | Payroll | Publisher>; one relay pass is Effect<{ delivered: number; failed: number }, RepositoryError, Outbox | Publisher>. No SqlError, SchemaError, or driver type appears in either signature.
After provision:Effect<Array<unknown>, EmployeeNotFound | MeritBudgetExceeded | RepositoryError | SqlError, never>. The only SqlError left is the one that building the database Layer (opening PGlite, running the migrations) can raise.
Required Layers: PGlite supplies the generic SqlClient; Outbox.layer and Raises.layer are both built from that one client, which is what lets the outbox insert join the transaction that Raises.approve opens. Publisher and Payroll are the demo's broker and idempotent consumer.
Lifetime and interruption: the embedded database is scoped by its Layer. SqlClient.withTransaction commits only when its body succeeds and rolls back on typed failure, defect, or interruption. The relay runs outside any transaction; interrupting it between the publish and the acknowledgement leaves the row pending, so the next pass redelivers the same outbox id.
The intent row is part of the state change.Raises.approve wraps the salary update, the outbox insert, and the budget draw in one sql.withTransaction. Commit or rollback is decided solely by the Exit of that body, so the body contains no recovery: MeritBudgetExceeded leaves it as a failure and takes both writes with it. Publishing from inside the transaction would be wrong in both directions — a rollback cannot recall a delivered event, and a retried transaction would deliver it twice.
Two repositories, one client.Outbox.enqueue is an ordinary method on another service, yet it joins the transaction because both Layers were built from the same SqlClient and the active connection travels in the fiber context. A separately constructed client would run outside it.
A typed COMMIT error does not prove the write failed.sql.withTransaction issues BEGIN (or a SAVEPOINT when nested), runs the body, then COMMIT on success or ROLLBACK on failure. A failed COMMIT remains a typed SqlError when commit-failure cleanup succeeds; failed cleanup promotes the combined commit and cleanup failures to defects. Rollback and savepoint-release failures are defects too. The SqlError handler above can therefore produce a RepositoryError after a failed commit. Preserve that uncertainty at the caller: do not blindly replay the write or report that it definitely did not commit. Reconcile by the business idempotency key; see Classify every outcome of an external write.
Repositories own their failures.owned(operation) uses Effect.mapError at the two places a repository can fail — the statement (SqlError) and the row decode (SchemaError) — and produces one RepositoryError with a typed cause. Defects and interruption pass through untouched; Effect.catchCause would have reported a programming bug as a storage failure. Zero rows is a different outcome: findOneOption returns Option.none(), which the use case turns into EmployeeNotFound.
The guarantee is at-least-once, by construction. The relay records the attempt, publishes, and acknowledges in that order. Every failure between "the consumer accepted" and "the row is marked delivered" — a lost acknowledgement, a crash, an interrupted relay, a failed update — produces a redelivery, never a loss. That is why the consumer deduplicates on the outbox id, and why the id is derived from the business fact (raise-approved:<cycle>:<employee>) rather than generated per attempt.
Run the relay continuously.relayPass.pipe(Effect.repeat(Schedule.spaced("1 second"))) forked into the application scope turns the pass into a poller; on PostgreSQL, listen / notify can wake it early, with polling kept as the safety net. With @effect/sql-pg a dropped listener connection fails the notification queue with its SqlError, so wrap the listener in Stream.retry and run one pass after every re-registration, because notifications sent in the gap are not replayed (Dates, enums, and LISTEN queues).
Several relay instances. Claim rows before sending — for example an update … set claimed_until = … where id in (select … for update skip locked) returning … that commits before the publish — so two relays do not send the same row concurrently. The claim shortens duplicates; it does not remove the need for consumer deduplication.
Retry a serialization failure or deadlock. Wrap the outermost Raises.approve call, never a statement inside it, and never retry a ConnectionError blindly, since the commit may have landed (Transactions). Keep the body free of forked fibers that outlive it: a statement from such a fiber fails because the transaction has already ended.
Poison messages.attempts is already durable. Stop selecting rows above a threshold, surface them on a dashboard, and redrive them deliberately instead of retrying forever.
Ordering. This relay continues past a failed row. If a topic needs per-key order, stop the pass at the first failure for that key.
Let the library run the queue.PersistedQueue with its SQL store on the same SqlClient is a ready-made outbox: queue.offer(event, { id }) inside sql.withTransaction commits or rolls back with the domain write, and queue.take adds retry schedules and dead-lettering.
Expose it over HTTP. Map EmployeeNotFound, MeritBudgetExceeded, and RepositoryError to declared endpoint errors in HttpApi; the shared-Schema wiring is shown in Recipe: Schema to HttpApi to SQL.
Beyond one database. When the work spans services or must survive long waits, move up the durability and distribution ladder to workflows and cluster messaging.
The CLI modules define parsers, help, completions, prompts, and command handlers as typed values that compose with ordinary Effects and Layers. Import the barrel with import { Argument, Command, Flag, Prompt } from "effect/cli", or use the module paths shown in each section.
Warning: The framework lives under effect/cli; pin the Effect version because this surface can change between minor releases. The release-matched ai-docs CLI example provides a compact runnable companion.
A fiber-scoped Context.Reference controlling runner-wide CLI behavior. Its service contains the ordered list of built-in global flags installed by Command.run; the default is GlobalFlag.BuiltIns. Earlier action flags have precedence.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { CliConfig, Command, GlobalFlag } from "effect/cli"const app = Command.make("comp", {}, () => Effect.void)// Keep help, version, and completions, but do not accept --log-level.const withoutLogLevel = CliConfig.layer({ builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.LogLevel)})const program = Command.run(app, { version: "1.0.0" }).pipe( Effect.provide(withoutLogLevel))
CliConfig.make(options) returns a value merged over the defaults; CliConfig.layer(options) provides it for parsing, help generation, and command execution. This only controls built-ins — application-specific global flags still attach with Command.withGlobalFlags.
Reach for it when embedding a CLI, constraining its global surface, or removing a built-in flag that conflicts with your application.
A Command<Name, Input, ContextInput, E, R> is both a typed description of how to parse a command's flags and arguments and an Effect that yields its parsed input when run. Subcommands can yield* parentCommand inside their handlers to read the parent's typed config without prop-drilling.
Mental model: a command declares what it needs from the CLI (config shape), what it returns (handler Effect), and how it composes with siblings (subcommands) and ancestors (shared flags). Command.make(name, config, handler) is the constructor; all other methods decorate it.
Flags declared with Command.withSharedFlags are visible to every subcommand handler; a subcommand reads them via const root = yield* comp.
Self-contained source · Type-checked
ts
import { NodeRuntime, NodeServices } from "@effect/platform-node"import { Console, Effect } from "effect"import { Argument, Command, Flag } from "effect/cli"// Reusable flag — share it across commandsconst outputFormat = Flag.Literals("format", ["table", "json", "csv"]).pipe( Flag.withAlias("f"), Flag.withDescription("Output format for results"), Flag.withDefault("table" as const))// Root command: declares shared flags visible to all subcommandsconst comp = Command.make("comp").pipe( Command.withSharedFlags({ format: outputFormat, verbose: Flag.Boolean("verbose").pipe( Flag.withAlias("v"), Flag.withDescription("Print diagnostic output"), Flag.withDefault(false) // an omitted boolean flag is otherwise a MissingOption error ) }), Command.withDescription("Compensation administration CLI"))// Subcommand: grant equity to an employeeconst grant = Command.make( "grant", { employee: Flag.String("employee").pipe( Flag.withAlias("e"), Flag.withDescription("Employee ID (e.g. e-42)") ), shares: Flag.Int("shares").pipe( Flag.withDescription("Number of RSU shares to grant") ), cliff: Flag.String("cliff").pipe( Flag.withDescription("Cliff period, e.g. 12mo"), Flag.withDefault("12mo") ) }, Effect.fn(function*({ employee, shares, cliff }) { // Access parent's shared flags by yielding the parent command const root = yield* comp if (root.verbose) { yield* Console.log(`format=${root.format} action=grant`) } yield* Console.log( `Granted ${shares} RSUs to ${employee} with ${cliff} cliff` ) })).pipe( Command.withDescription("Grant equity (RSUs) to an employee"), Command.withExamples([ { command: "comp grant --employee e-42 --shares 1000 --cliff 12mo", description: "Grant 1 000 RSUs to employee e-42 with a 12-month cliff" } ]))// Subcommand: start a merit review cycleconst reviewStart = Command.make( "start", { cycle: Flag.String("cycle").pipe( Flag.withDescription("Merit cycle ID, e.g. 2025-Q1"), Flag.withDefault("current") ), budget: Flag.Int("budget").pipe( Flag.withDescription("Approved merit budget in USD") ) }, Effect.fn(function*({ cycle, budget }) { const root = yield* comp if (root.verbose) { yield* Console.log(`format=${root.format} action=review/start`) } yield* Console.log(`Merit review cycle "${cycle}" started — budget $${budget}`) })).pipe( Command.withDescription("Start a new merit review cycle"), Command.withAlias("s") // comp review s --budget 500000)// Group review actions under a "review" parent subcommandconst review = Command.make("review").pipe( Command.withDescription("Manage merit review cycles"), Command.withSubcommands([reviewStart]))// Wire subcommands and runcomp.pipe( Command.withSubcommands([grant, review]), Command.run({ version: "1.0.0" }), Effect.provide(NodeServices.layer), NodeRuntime.runMain)
Tip: Use Command.withSharedFlags for typed values that child handlers read by yielding their parent command. Use Command.withGlobalFlags for runner-wide actions or settings rather than ordinary parsed command input.
Constructor — name + typed config + optional inline handler
Command.withHandler(fn)
Attach or replace the handler after construction; the command keeps its existing error type, so validation errors and a replaced handler's errors stay in E
Command.withSubcommands([...])
Register child commands (union of their errors/requirements flows up)
Command.withSharedFlags({...})
Parent flags visible inside all subcommand handlers
Command.withGlobalFlags([...])
Attach GlobalFlag instances (settings, not shared input)
Command.withDescription(s)
Long description shown in --help
Command.withShortDescription(s)
One-liner shown in parent's subcommand list
Command.withAlias(s)
Alternate invocation name (review start → review s)
Command.unlisted
Keep a command invocable but omit it from normal listings/help
Command.withExamples([...])
Curated examples shown at the bottom of --help; pass ({ commandPath }) => [...] to derive them from where the command is mounted
Command.validate(f)
Check the parsed input before the handler runs (for example mutually exclusive flags). A CliError such as CliError.ValidationError is shown with help like a parse error; any other error is reported like a handler failure and added to the command's error type (see below)
Command.provide(layer)
Provide a Layer to the handler (static or derived from parsed input)
Command.provideEffect(effect)
Run an effect before the handler and provide its result as a service
Command.run({ version })
Convert to a runnable Effect (reads argv from Stdio)
Command.runWith(cmd, cfg)(args)
Run with an explicit string[] — great for testing
Testing:Command.runWith(rootCmd, { version: "1.0.0" })(["grant", "--employee", "e-42", "--shares", "1000"]) runs against explicit argv. Its requirements always include Command.Environment, so provide NodeServices.layer or the in-memory environment shown below.
Command.validate(f) receives the same input as the handler, with defaults, prompts, and wizard answers already applied. Validations run in the order they were added, stop at the first failure, and survive a later withHandler. Added after withSharedFlags, a validation sees the shared flags; added after withSubcommands, it also runs when a subcommand is selected. The error decides how the failure is reported:
Validation fails with
Reported as
a CliError, usually CliError.ValidationError({ message })
a usage mistake: Command.run prints the help and the message, then fails with ShowHelp
any other error
a handler failure: no help, the original error reaches the caller, its CliError.userMessage (if any) is rendered unless renderErrors is false, and its type is added to the command's E
Self-contained source · Type-checked
ts
import { Effect, Option, Schema } from "effect"import { CliError, Command, Flag } from "effect/cli"class ConflictingSources extends Schema.TaggedError<ConflictingSources>()("ConflictingSources", {}) { override get [CliError.userMessage]() { return "--plan-file and --plan-url cannot be used together" }}export const importPlan = Command.make( "import", { planFile: Flag.String("plan-file").pipe(Flag.optional), planUrl: Flag.String("plan-url").pipe(Flag.optional) }, ({ planFile, planUrl }) => Effect.log("importing", Option.orElse(planFile, () => planUrl))).pipe( // A usage mistake: shown with the command help. Command.validate(({ planFile, planUrl }) => Option.isNone(planFile) && Option.isNone(planUrl) ? Effect.fail(new CliError.ValidationError({ message: "pass --plan-file or --plan-url" })) : Effect.void ), // A domain error: no help, and the command's error type becomes ConflictingSources. Command.validate(({ planFile, planUrl }) => Option.isSome(planFile) && Option.isSome(planUrl) ? Effect.fail(new ConflictingSources()) : Effect.void ))
Use your own tagged errors when the caller must tell failures apart, for example to map them to exit codes or JSON output. To tell an omitted flag from one passed with its default value (--force=false), declare it with Flag.optional and apply the default in the handler; once withDefault or a config fallback has filled the value in, presence is lost.
Migration:Command.withHandler keeps the command's existing error type instead of replacing it with the new handler's. Code that annotates such a command with a narrower error type must widen the annotation, or pass the final handler to Command.make instead.
Command.runWith is the seam: it takes explicit arguments, requires the same Command.Environment services as production (FileSystem, Path, Terminal, Stdio, ChildProcessSpawner — all supplied by NodeServices.layer), and writes help, version, and rendered errors through Effect's Console service. Inside it.effect that output lands in TestConsole, so a CLI test needs no process spawn and no stdout scraping.
Self-contained source · Type-checked
ts
import { NodeServices } from "@effect/platform-node"import { assert, it } from "@effect/vitest"import { Console, Effect, Result } from "effect"import { Command, Flag } from "effect/cli"import { TestConsole } from "effect/testing"const grant = Command.make( "grant", { employee: Flag.String("employee"), shares: Flag.Int("shares") }, ({ employee, shares }) => Console.log(`Granted ${shares} RSUs to ${employee}`))const run = Command.runWith(grant, { version: "1.0.0" })it.effect("runs the handler with parsed input", () => Effect.gen(function*() { yield* run(["--employee", "e-42", "--shares", "1000"]) assert.deepStrictEqual(yield* TestConsole.logLines, ["Granted 1000 RSUs to e-42"]) }).pipe(Effect.provide(NodeServices.layer)))it.effect("a bad value fails with ShowHelp carrying the structured cause", () => Effect.gen(function*() { const result = yield* Effect.result(run(["--employee", "e-42", "--shares", "many"])) assert.isTrue(Result.isFailure(result)) if (Result.isFailure(result) && result.failure._tag === "ShowHelp") { const [first] = result.failure.errors assert.strictEqual(first?._tag, "InvalidValue") assert.strictEqual(first?._tag === "InvalidValue" ? first.option : undefined, "shares") } else { assert.fail("expected a ShowHelp failure") } // Usage went to Console.log, the rendered error to Console.error. assert.strictEqual((yield* TestConsole.errorLines).length, 1) }).pipe(Effect.provide(NodeServices.layer)))
NodeServices.layer gives the command the real filesystem and terminal. When a test must be hermetic — no disk, no TTY, no child processes — assemble the environment from the in-memory pieces instead; the stubs below turn an unexpected terminal read or process spawn into a defect. A custom Terminal.make must supply every member, including size (a scoped queue of { columns, rows } that starts with the current dimensions and receives each resize):
Self-contained source · Type-checked
ts
import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from "effect"import { ChildProcessSpawner } from "effect/process"export const CliTestEnvironment = Layer.mergeAll( FileSystem.layerNoop({}), // operations you do not supply fail as NotFound (or die); `exists` answers false Path.layer, Stdio.layerTest({}), Layer.succeed(Terminal.Terminal, Terminal.make({ columns: Effect.succeed(80), rows: Effect.succeed(24), size: Effect.die("this command must not watch the terminal size"), readInput: Effect.die("this command must not read keys"), readLine: Effect.die("this command must not prompt"), display: () => Effect.void })), Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => Effect.die("this command must not spawn processes")) ))
What this proves
What it does not prove
parsing, defaults, fallbacks, handler wiring, and the typed failure for bad input
that the packaged binary starts, reads real argv, and exits with the right status — launch the built artifact once for that (see Testing an Effect Application)
Assert on the structured error, not on the rendered help text: help tables are aligned by terminal display width (wide, emoji, combining, and zero-width graphemes), so exact column spacing is a formatter detail. Pass { renderErrors: false } when the embedding host owns error rendering; help documents are still printed. To suppress or redirect the built-in help, version, and invalid-invocation output itself, provide a CliOutput.Presenter.
Use when you need a type-safe CLI application with subcommands, help generation, and shell completions.
A Flag<A> is a typed parser for named CLI options (--verbose, --shares 1000). Flags are composable: chain Flag.withDefault to make optional, Flag.optional to get Option<A>, Flag.withFallbackConfig to satisfy from an environment variable when absent. Boolean flags: --dry-run alone means true; --no-dry-run negates it — rename that form with Flag.withNegation("skip-dry-run") or remove it with Flag.withoutNegation (both also change shell completions). An omitted boolean flag is not an implicit false: like every other flag it fails with CliError.MissingOption unless you add Flag.withDefault(false), Flag.optional, or a config/prompt fallback. That makes absence uniform across flag types and lets a fallback chain decide it. The built-in global flags add their own false default.
Self-contained source · Type-checked
ts
import { Config } from "effect"import { Flag, Prompt } from "effect/cli"// Boolean: --dry-run / --no-dry-runconst dryRun = Flag.Boolean("dry-run").pipe( Flag.withAlias("n"), Flag.withDescription("Simulate without writing changes"), Flag.withDefault(false) // required when omitted unless given a default, optional, or fallback)// Integer: number of RSU sharesconst shares = Flag.Int("shares").pipe( Flag.withAlias("s"), Flag.withDescription("Number of RSU shares"), Flag.withDefault(500))// Constrained enum: target merit cycleconst cycleKind = Flag.Literals("kind", ["rsu", "option", "bonus"]).pipe( Flag.withDescription("Grant type"), Flag.withDefault("rsu" as const))// Fall back to an env-var when the flag is absentconst hrisToken = Flag.String("hris-token").pipe( Flag.withFallbackConfig(Config.String("HRIS_API_TOKEN")))// Redacted string — value is masked in help and logsconst apiSecret = Flag.Redacted("api-secret")// Optional — yields Option<string>, None when omittedconst note = Flag.String("note").pipe(Flag.optional)// Key-value map: --label team=eng --label region=us -> Record<string, string>const labels = Flag.KeyValuePair("label").pipe( Flag.withDescription("Attach metadata labels to the grant"))// Fall back to an interactive prompt when the flag is absent and the terminal can prompt.// Pass the Prompt directly — no callback wrapper needed.const employeeId = Flag.String("employee").pipe( Flag.withFallbackPrompt( Prompt.String({ message: "Employee ID: " }) ))
import { Schema } from "effect"import { Flag } from "effect/cli"// Validate or transform the parsed string with any Schema: bad input is a parse error,// so the handler only ever sees a valid value.const Email = Schema.String.check( Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { message: "Expected an email address" }))const approver = Flag.String("approver").pipe(Flag.withSchema(Email))// Alternatives: try --plan-file, then --plan-url. The result is a union...const planSource = Flag.File("plan-file").pipe( Flag.orElse(() => Flag.String("plan-url")))// ...or a Result that records WHICH flag supplied the value.const planSourceTagged = Flag.File("plan-file").pipe( Flag.orElseResult(() => Flag.String("plan-url")))// An alternative chain can be optional as a whole: None when neither flag is present.const optionalPlanSource = Flag.File("plan-file").pipe( Flag.orElse(() => Flag.String("plan-url")), Flag.optional)const _ = [approver, planSource, planSourceTagged, optionalPlanSource]
Situation
Behavior
Neither flag of an orElse chain is given
the chain fails with MissingOption naming the last alternative; wrap it in Flag.optional or Flag.withDefault to make absence legal
A KeyValuePair value contains =
only the first = splits: --label note=a=b yields { note: "a=b" }
A value begins with - and parses as a number (-3, -3.70, -2e5)
parses as a value either way: --delta -5 and --delta=-5 both set delta to -5
A value begins with - but is not numeric, such as a string flag value of -x
write it inline: --label=-x. The spaced form --label -x reads -x as another flag and fails with UnrecognizedOption
A boolean flag is omitted
MissingOption, unless the flag has a default, is optional, or has a fallback
A single-valued flag is given twice (--shares 1 --shares 2)
rejected with InvalidValue (expected "at most 1 value") instead of keeping the first; use Flag.atLeast, Flag.atMost, or Flag.between to accept repeats. KeyValuePair flags still merge their occurrences
A short cluster with an inline value (-vn=3)
split into -v -n=3; a single dash before a multi-character name (-num=3) is split the same way, so write --num=3
--=value
passed through as a plain value, not an empty-named flag
Flag.withOptionalValue(rawValue) lets a present flag omit its value. The raw string is parsed and validated by the original flag. It does not make the flag itself optional; add Flag.optional or withDefault for absence.
Self-contained source · Type-checked
ts
import { Flag } from "effect/cli"const color = Flag.Literals("color", ["auto", "always", "never"]).pipe( Flag.withOptionalValue("auto"), Flag.optional)// --color -> Some("auto")// --color=never -> Some("never")// absent -> None
Explicit values must use =, including a short alias (-c=never). --color never leaves never for positional/subcommand parsing; the flag never consumes the next token. Help renders an optional-value form such as --color [=choice].
Metadata for documentation tools.Flag.annotate(key, value) (and Argument.annotate) attaches a value under a Context.Key, for facts the parser cannot know, such as the environment variable behind a withFallbackConfig or a deprecation note. Annotations never affect parsing, help, or completions, and survive combinators applied before or after them; CommandSpec reports them.
Use when you need named -- options for type-safe command configuration.
Positional command-line arguments — values without a --name prefix. Argument<A> is structurally identical to Flag<A> with nearly the same constructor surface; the distinction is named vs positional.
Arguments resolve in declaration order. Argument.variadic collects all remaining positionals into an array. Only one variadic argument is allowed per command, and it must be last.
Self-contained source · Type-checked
ts
import { Argument } from "effect/cli"// Required positional: the employee ID to look upconst employeeArg = Argument.String("employee-id").pipe( Argument.withDescription("Employee ID (e.g. e-42)"))// Optional positional: an output file pathconst outFile = Argument.String("output-file").pipe( Argument.optional // yields Option<string>)// Variadic — collect zero or more employee IDs for a bulk operationconst employeeIds = Argument.String("employee-ids").pipe( Argument.variadic, Argument.withDescription("Employee IDs to process"))// Read a comp-plan JSON file directly from a positional pathconst planFile = Argument.FileText("plan-path").pipe( Argument.withDescription("Path to the comp plan JSON file"))// Parse positional as a chosen enum valueconst reviewAction = Argument.Literals("action", ["start", "close", "reopen"])
Tip: Options can appear before or after positional arguments: both comp grant e-42 --shares 1000 and comp grant --shares 1000 e-42 are accepted.
Variadic bounds and defaults interact. Argument.variadic accepts zero or more values, so omission already parses — to [] — and a withDefault placed after it never applies. Require at least one value, and the default becomes reachable:
Self-contained source · Type-checked
ts
import { Argument } from "effect/cli"// Omitted -> [] (the default below is dead code)const anyIds = Argument.String("employee-id").pipe( Argument.variadic, Argument.withDefault(["all"]))// Omitted -> ["all"]; given -> one or more idsconst idsOrAll = Argument.String("employee-id").pipe( Argument.atLeast(1), Argument.withDefault(["all"]))// Bounded: between one and five ids, no defaultconst fewIds = Argument.String("employee-id").pipe(Argument.between(1, 5))const _ = [anyIds, idsOrAll, fewIds]
Use when the natural invocation uses positional subjects (file paths, resource IDs) rather than --name <value> flags.
The shared machinery powering both Flag and Argument. A Param<Kind, A> carries a Kind type tag ("flag" or "argument") determining tokenisation. All combinators (withDefault, optional, map, mapEffect, filter, withFallbackConfig, withFallbackPrompt, withSchema) are implemented once in Param and re-exported by both Flag and Argument (variadic is on Argument only).
Rarely imported directly in application code — use Flag and Argument instead. Relevant when building custom param combinators or reading the parsing internals.
Param.Single — Leaf param backed by one Primitive value parser. Has a name, optional aliases, optional metavar for help text.
Param.Map / Transform — Wraps a param with a pure or effectful transformation; implements Flag.map, Flag.mapEffect, Flag.filter.
Param.Optional — Wraps a param, changing its result from A to Option<A>. Succeeds with None when the token is absent.
Param.Variadic — Allows a param to appear 0–N (or min–max) times, collecting results into ReadonlyArray<A>.
Param.annotate(key, value) is the shared implementation of Flag.annotate and Argument.annotate; the values live on each Single node's annotations. withDefault, withFallbackConfig, and withFallbackPrompt record a structural Param.Fallback on their Transform node without evaluating it: { _tag: "Default", value } for a literal default, and only the kind ("DefaultEffect", "Config", "Prompt") for fallbacks that would have to run to be inspected. CommandSpec reads both.
Use when building abstractions over the CLI library — custom combinators that work for both flags and arguments, or inspecting param structure for documentation generation.
Leaf-level value parsers converting raw CLI strings into typed TypeScript values. Each Flag.* and Argument.* constructor wraps a Primitive. A Primitive<A> is essentially (rawString: string) => Effect<A> with a display name; the framework derives shell completion types from _tag.
Primitive.Int / Primitive.Finite — Schema-validated numeric parsers. Produces a structured InvalidValue error on bad input.
Primitive.Date — Parses ISO-8601 date strings into Date.
Primitive.Choice — Restricts value to a fixed string set; drives completion script's value list.
Primitive.Path — Primitive.Path(pathType, mustExist?) validates existence and type (file | directory | either) against the real filesystem at parse time.
Primitive.Redacted — Returns Redacted<string>; masked in help output and Effect logging.
Primitive.FileText / FileParse / FileSchema — Reads a file at the given path and returns its text, parsed INI/JSON/TOML/YAML, or Schema-decoded value. FileParse() infers from .ini, .json, .toml, .yaml, or .yml; { format } overrides detection.
Primitive.KeyValuePair — Parses KEY=VALUE pairs; multiple appearances merge into Record<string, string>. Only the first = separates key from value, so values may themselves contain =.
Use when inspecting what type a flag or argument represents (e.g. documentation generation or custom completion logic) — _tag is the canonical discriminant.
Interactive terminal prompts. A Prompt<A> is an Effect that runs a TUI render loop and yields a typed value on confirmation. Prompts compose with Effect.gen, chain with Prompt.flatMap, and collect with Prompt.all.
Each prompt has three phases: render (write ANSI), process (receive keypress, return next state or final value), clear (erase frame). The CLI connection is Flag.withFallbackPrompt (and Argument.withFallbackPrompt): when a required flag is absent, the prompt runs automatically — but only when TerminalCapabilities reports canPrompt. Otherwise the prompt is not built or shown and the parse fails with the original MissingOption / MissingArgument, so a CI job or piped invocation fails instead of hanging. Pass the Prompt or an Effect yielding one directly.
Prompts and the command wizard respect NO_COLOR, suppressing color/style escapes but retaining cursor and redraw controls: this is not a plain non-interactive transcript mode. Terminal input is acquired only when a prompt needs user input, so constant fallback prompts leave piped stdin untouched.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Flag, Prompt } from "effect/cli"// Text input — for capturing an employee's new title on promotionconst titlePrompt = Prompt.String({ message: "New job title: " })// Password — masked input for the HRIS API tokenconst hrisTokenPrompt = Prompt.Password({ message: "HRIS API token: " })// Yes/No confirm — guard a raise that exceeds the pay bandconst confirmAboveBand = Prompt.Confirm({ message: "Salary exceeds band midpoint by > 20%. Proceed anyway?", initial: false})// Select from a list — choose a performance ratingconst ratingPrompt = Prompt.Select({ message: "Performance rating", choices: [ { title: "Exceeds expectations", value: "exceeds" }, { title: "Meets expectations", value: "meets" }, { title: "Below expectations", value: "below" } ]})// Toggle — approve or reject a raise recommendationconst approvalToggle = Prompt.Toggle({ message: "Approve raise recommendation?", active: "approve", inactive: "reject", initial: true})// Multi-select — pick which comp components to adjustconst componentsPrompt = Prompt.MultiSelect({ message: "Adjust compensation components", choices: [ { title: "Base salary", value: "base" }, { title: "Bonus target", value: "bonus" }, { title: "RSU grant", value: "equity" } ]})// Chain prompts: an interactive raise-approval wizardconst raiseWizard = Effect.gen(function*() { const rating = yield* ratingPrompt const approved = yield* approvalToggle if (approved) { const aboveBand = yield* confirmAboveBand return { rating, approved, aboveBand } } return { rating, approved, aboveBand: false }})// Fallback prompt on a flag: if --employee is omitted, the prompt fires.// Pass the Prompt directly — no callback wrapper.const employeeFlag = Flag.String("employee").pipe( Flag.withFallbackPrompt(Prompt.String({ message: "Employee ID: " })))
Prompt symbols and colors come from one Prompt.Theme — a Context.Reference whose default is built by Prompt.makeTheme() from platform-appropriate glyphs (Windows-specific fallbacks, not exclusively ASCII). Provide it once to restyle every prompt in the application; pass a partial theme to a single prompt to override it there. The per-prompt option wins over the context value.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Prompt } from "effect/cli"// A message-less Select shows only the choices. AutoComplete still requires one.const cyclePrompt = Prompt.Select({ choices: [ { title: "FY27 merit cycle", value: "fy27" }, { title: "FY27 mid-year adjustment", value: "fy27-mid" } ]})// One prompt with a local override: a different mask character for this secret only.const tokenPrompt = Prompt.Password({ message: "HRIS API token", theme: { passwordMask: "•" }})const wizard = Effect.gen(function*() { const cycle = yield* cyclePrompt const token = yield* tokenPrompt return { cycle, token }})// Application-wide theme: plain ASCII markers for a terminal without Unicode glyphs.const asciiTheme = Prompt.makeTheme({ prefix: ">", pointer: ">", tick: "ok", checkboxOn: "[x]", checkboxOff: "[ ]"})const themedWizard = wizard.pipe(Effect.provideService(Prompt.Theme, asciiTheme))
Theme fields: prefix, pointer, pointerSmall, ellipsis, tick, arrowUp, arrowDown, checkboxOn, checkboxOff, descriptionSeparator, passwordMask, toggleSeparator, and the colors primaryColor, mutedColor, successColor, errorColor, submittedColor. Setting a symbol to the empty string removes both the symbol and its adjacent spacing.
Notable current prompt behavior: Prompt.Select and Prompt.MultiSelect without a message show only the choices and, on submit, a tick followed by the selected titles; Prompt.Date does not carry typed digits into the next field on Tab, including when navigation wraps; and Prompt.AutoComplete and Prompt.File do not swallow j and k while a filter query is being typed.
Use when you want wizard-style interactive CLIs or need to prompt for a required value absent from the environment.
The intermediate data structure for a command's help page. Captures description, usage line, flag/argument docs, inherited and global flag docs, subcommand listing, and examples — before any string formatting. Shared flags declared on ancestor commands arrive in inheritedFlags (rendered as an INHERITED FLAGS section), not in flags; commandPath and globalFlagsScope record where the command and its global flags are declared. Rendering is delegated to CliOutput.Formatter.
HelpDoc is to --help output what Schema is to JSON serialization: a structured description renderable multiple ways (plain text, ANSI, Markdown, JSON). The CLI framework builds it automatically from the command tree; inspect or transform it for custom tooling.
Self-contained source · Type-checked
ts
import { Context, Option as O } from "effect"import type { HelpDoc } from "effect/cli"// HelpDoc is plain data — construct it manually for testing or tooling.// Note: subcommands is ReadonlyArray<HelpDoc.SubcommandGroupDoc>, not a flat list.const grantCommandHelp: HelpDoc.HelpDoc = { description: "Grant RSUs or options to an employee", usage: "comp grant [options]", annotations: Context.empty(), flags: [ { name: "employee", aliases: ["-e"], type: "string", description: O.some("Employee ID (e.g. e-42)"), required: true }, { name: "shares", aliases: ["-s"], type: "integer", description: O.some("Number of RSU shares to grant"), required: true }, { name: "cliff", aliases: [], type: "string", description: O.some("Cliff period, e.g. 12mo"), required: false } ], args: [], globalFlags: [], subcommands: [], // ReadonlyArray<SubcommandGroupDoc> examples: [ { command: "comp grant --employee e-42 --shares 1000 --cliff 12mo", description: "Grant 1 000 RSUs with a 12-month cliff" } ]}
The default formatter aligns the flag, argument, and subcommand tables by terminal display width rather than string length, so wide characters, emoji, combining marks, and zero-width graphemes in names or descriptions do not skew the columns. A custom formatter that pads with String.prototype.padEnd does not get that for free; test on the HelpDoc data rather than on padded output.
Migration: a custom formatter that read ancestor shared flags from HelpDoc.flags must read them from HelpDoc.inheritedFlags.
Use when implementing a custom CliOutput.Formatter, generating Markdown documentation from the CLI tree, or building tooling requiring structured access to the help model.
Shell completion script generator. Given a CommandDescriptor, Completions.generate returns a static completion script string for Bash, Zsh, Fish, or PowerShell ("powershell"). The built-in --completions flag also accepts pwsh as an alias for powershell; use the canonical name for programmatic generation.
Rarely called directly. GlobalFlag.Completions wires it automatically: comp --completions bash prints a script users can source. Completion-aware types (choice, path, file, directory) produce richer tab-completion suggestions automatically.
bash
# Install completions for the comp-admin CLI (once)comp --completions bash >> ~/.bash_completioncomp --completions zsh >> ~/.zshrccomp --completions fish > ~/.config/fish/completions/comp.fish
For PowerShell, save comp --completions powershell > comp-completion.ps1 and dot-source the script from your profile (. ./comp-completion.ps1). Regenerate scripts after changing the command tree.
To generate completions programmatically (e.g. in a build script or test), Completions.fromCommand(command) converts an existing Command tree into a CommandDescriptor — the same one --completions uses, with shared flags, aliases, and negations, and without hidden flags or unlisted subcommands:
What the built-in --completions flag and Completions.fromCommand derive for you — and what a hand-written CommandDescriptor must therefore reproduce:
Behavior
Detail
Subcommand aliases complete like the canonical name
the generated descriptor lists an aliased subcommand a second time under its alias, with the same flags and nested commands
Shared flags reach every descendant
flags declared with Command.withSharedFlags are included in each descendant's flag list
Choice values survive supported quoting contexts
values containing quotes, spaces, word-break characters, Unicode, or shell metacharacters are escaped for Bash (including Bash 3.2, without associative arrays), Zsh, and Fish; Bash still has partial-quote limitations for ! inside an already-open double quote and apostrophes inside a mid-word single quote
Positional arguments and subcommands coexist in Zsh
a command that has both completes correctly
Repeatable flags keep completing
a flag under Flag.atLeast, Flag.between with a maximum above 1, or a KeyValuePair flag is still offered after its first use; the descriptor marks it repeatable: true, which a hand-written descriptor must set itself
Subcommand names may contain :
names such as test:unit complete in Bash and Zsh
Optional positionals are not required
an argument that is optional, or variadic without a positive minimum (Argument.variadic, Argument.atLeast(0)), is described as not required
--completions sh
accepted as an alias for bash
Regenerate installed completion scripts after upgrading Effect; a script generated against an older command tree does not reflect flags or subcommands added since.
Use when you need programmatic completion script access. For normal CLIs, GlobalFlag.Completions handles it automatically. For a complete description of a command, including hidden flags and unlisted subcommands, use CommandSpec.
A projection of one command path of a Command tree into plain data, for documentation tooling: reference pages, man pages, JSON schemas, or a check that every config fallback is documented. Where Completions.fromCommand deliberately drops what a shell should not offer, CommandSpec keeps everything: hidden flags and unlisted subcommands are included and marked, primitive types are not collapsed, and each flag says where it is declared.
CommandSpec.resolve(command, path, { builtIns? }) returns Option<Spec>. It is pure and synchronous: it runs no handler, prompt, Config lookup, or effectful default. path names commands from the root down, root first, exactly like HelpDoc.commandPath; only canonical names match, so an alias, an unknown segment, a different root name, or an empty path gives Option.none() rather than the nearest ancestor. builtIns defaults to GlobalFlag.BuiltIns; pass the list from your CliConfig when it differs, or [] to omit built-ins.
the resolved command; examples are resolved for this path
flags
local flags, then flags inherited through withSharedFlags from the root down, then global flags (built-ins first), in help order. A nearer flag hides an inherited one of the same name; a global flag is always listed
arguments
positional arguments in declaration order
subcommands
direct children with name, alias, group, unlisted, and descriptions; an alias is a field, not an extra entry
Each flag carries name, aliases (without dashes), description, hidden, type (one variant per Primitive, such as { _tag: "Choice", values } or { _tag: "Path", pathType }), typeName, metavar, required, fallbacks, variadic ({ min, max } or undefined), optionalValue, negation (the effective no-<name> form of a boolean flag), scope (Local, Inherited with declaredBy, or Global with declaredBy and kind), and the annotations set with Flag.annotate. Arguments carry the same facts except aliases, hidden, optional value, negation, and scope.
required ignores Config and Prompt fallbacks. It says whether parsing fails when the entry is absent and nothing on its own path supplies a value, so a flag with withFallbackConfig is still required; render it from fallbacks as "required unless $DB_URL is set". withDefault and optional clear it, a bare boolean flag is required like any other, and a global action flag is never required.
fallbacks are structural. They are Param.Fallback values in the order the parser consults them (innermost first): { _tag: "Default", value } for a literal default, and only the kind for DefaultEffect, Config, and Prompt. The config key is not recoverable, which is what annotate is for.
Transformations are transparent and alternatives are split.map, withSchema, and filter do not show up; a parameter built with orElse yields one entry per alternative, each with its own branch-local required and fallbacks.
Reach for it when generating documentation or a machine-readable description of a CLI in a build step. For shell scripts use Completions, and for rendering --help use HelpDoc.
Built-in and user-defined flags that intercept parsing before the normal handler runs. A global flag is either an Action (runs a side-effect and exits) or a Setting (provides a context service to the handler). Built-ins: Help, Version, Wizard, Completions, LogLevel.
Global flags have higher precedence than all other parsing. Action globals exit; Setting globals inject a context value (e.g. LogLevel sets the minimum log level for the handler's Effect runtime).
Constructors: GlobalFlag.Action({ flag, run }) for action flags; curried GlobalFlag.Setting(id)({ flag }) for setting flags. A setting is a Context.Service the handler can yield* to read the parsed value.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Command, Flag, GlobalFlag } from "effect/cli"// --- Custom action flag: print the license and exit ---const licenseFlag = GlobalFlag.Action({ flag: Flag.Boolean("license").pipe( Flag.withDescription("Print license information"), Flag.withDefault(false) ), run: (_value, _ctx) => Effect.log("MIT License — Copyright 2025 CompAdmin Authors")})// --- Custom setting flag: dry-run mode as a context service ---// GlobalFlag.Setting is curried: setting(id)({ flag })const dryRunSetting = GlobalFlag.Setting("dry-run")({ flag: Flag.Boolean("dry-run").pipe( Flag.withDescription("Simulate writes without committing changes"), Flag.withDefault(false) )})// Access a setting value inside a handler by yielding the setting object:const grantCmd = Command.make( "grant", { shares: Flag.Int("shares") }, Effect.fn(function*({ shares }) { // dryRunSetting is a Context.Service — yield it to get the boolean const isDryRun = yield* dryRunSetting if (isDryRun) { yield* Effect.log(`[dry-run] Would grant ${shares} shares`) } else { yield* Effect.log(`Granting ${shares} shares`) } }))// Attach the custom globals to the commandconst grantWithGlobals = grantCmd.pipe( Command.withGlobalFlags([licenseFlag, dryRunSetting]))
Runs the interactive wizard for the selected command
--completions <bash|zsh|fish|powershell|sh|pwsh>
Action
Prints completion script and exits (sh aliases bash; pwsh aliases powershell)
--log-level <level>
Setting
Sets runtime minimum log level
Note:GlobalFlag.BuiltIns is ordered Help, Version, Wizard, Completions, LogLevel; the first present action wins. Command.withGlobalFlags attaches application-specific actions or settings to a command and its descendants.
--wizard prompts for each parameter of the selected command, prints the equivalent command line, and asks whether to run it. Two details matter for what it prints:
Secrets are masked in the rendered command. A Flag.Redacted parameter is collected with Prompt.Password, and the printed command shows <redacted> in place of the value while the real value is passed to the run.
Values that look like flags are written inline. A collected value beginning with - is emitted as --delta=-5 rather than --delta -5, so the lexer cannot mistake it for a flag or for the -- delimiter.
Already typed input is replaced, not repeated. Flags and arguments typed for the selected command before --wizard are dropped from the printed command and asked for again; parent shared flags and subcommand names are kept. For a command without subcommands, positional answers follow a -- separator, so they cannot be read as the value of a preceding boolean flag.
Invalid values for a global flag show the command help like any other parse error. --help and --version print through CliOutput.Presenter (by default the Console service) and succeed; they are not failures. A parent command invoked without a subcommand fails with ShowHelp and an empty errors list, which maps to exit code 0.
Use when you need a flag that short-circuits command dispatch or provides context-level configuration to every handler in the tree.
The typed error union for the CLI parser. CliError.CliError is what Command.run may fail with — a discriminated union covering every parser and runner failure mode. NodeRuntime.runMain handles these automatically (the runner has already printed them; the exit code comes from the error); match on _tag when embedding a CLI in a larger Effect application or writing integration tests.
Parse and validation failures arrive wrapped. The runner collects them, prints the help page plus the rendered errors, and fails with a single ShowHelp whose errors array holds the structured causes (InvalidValue, MissingOption, UnknownSubcommand, …). A catchTag("InvalidValue", …) placed on Command.run therefore never fires for bad input; inspect ShowHelp.errors instead. UserError and any error type of your own handlers, or of your own Command.validate rules, reach the caller directly.
Give a domain error a user-facing message without wrapping it. When a handler or validation fails with an object carrying a string [CliError.userMessage] — UserError does, and a tagged error can define the getter — Command.run renders that message with the installed formatter and rethrows the original error, so catchTag on your own tag still works and runMain does not log it twice. CliError.getUserMessage(error) reads it.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { CliError, Command } from "effect/cli"class GrantExists extends Schema.TaggedError<GrantExists>()("GrantExists", { employee: Schema.String }) { override get [CliError.userMessage]() { return `${this.employee} already has a grant this cycle` }}// `comp grant` prints "ERROR e-42 already has a grant this cycle" and fails with GrantExists.const grant = Command.make("grant", {}, () => Effect.fail(new GrantExists({ employee: "e-42" })))const _ = grant
Error class
When it fires
UnrecognizedOption
A --flag was passed that no command recognises. Includes Levenshtein suggestions.
DuplicateOption
A subcommand declares a flag whose name its parent already declares (a command-definition error, not a user-input error).
ValidationError
A Command.validate, Flag.mapEffect, or Argument.mapEffect rule rejected the parsed input; carries message. A validation that fails with your own error instead is not wrapped in ShowHelp.
MissingOption
A required flag was absent and had no default or fallback.
MissingArgument
A required positional argument was absent.
UnexpectedArgument
Extra positional arguments remained after parsing.
InvalidValue
A value failed Primitive parsing (e.g. "abc" for an integer flag), or a single-valued flag was repeated.
UnknownSubcommand
The first token didn't match any known subcommand. Includes suggestions.
UserError
A handler or parameter transform explicitly wrapped a failure for safe CLI rendering; carries cause and an optional userMessage. Prefer the CliError.userMessage annotation on your own error.
ShowHelp
The runner's failure for "help was shown": with errors attached for parse/validation failures (exit code 1), or with an empty errors list when a parent command is invoked without a subcommand (exit code 0). An explicit --help is not an error at all — it prints and succeeds.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Command, Flag } from "effect/cli"import { NodeServices } from "@effect/platform-node"const grant = Command.make( "grant", { employee: Flag.String("employee"), shares: Flag.Int("shares") }, ({ employee, shares }) => Effect.log(`Granted ${shares} shares to ${employee}`))const program = grant.pipe( Command.run({ version: "1.0.0" }), // Bad input surfaces as ONE ShowHelp; the structured causes are in `errors`. // Command.run has already printed the help page and the rendered errors. Effect.catchTag("ShowHelp", (help) => Effect.forEach(help.errors, (error) => { switch (error._tag) { case "InvalidValue": return Effect.logWarning(`bad value for ${error.kind} "${error.option}"`, { value: error.value, expected: error.expected }) case "MissingOption": return Effect.logWarning(`required flag missing: --${error.option}`) default: return Effect.logWarning(`cli parse failure: ${error._tag}`) } }, { discard: true })), // Catch ShowHelp only when this embedding must recover; otherwise let // NodeRuntime.runMain take the exit code from the error. Effect.provide(NodeServices.layer))
Use when embedding a CLI runner in a larger Effect program and needing to distinguish parse errors, user errors, and help requests, or when asserting on specific error conditions in tests.
Two services decide what built-in CLI output looks like and where it goes. CliOutput.Formatter is the renderer: it turns help documents, errors, and version strings into text; override it with CliOutput.layer(myFormatter). CliOutput.Presenter is the sink: Command.run / runWith hand it an event (Help with reason "Requested" or "Implicit", InvalidInvocation with the help document and errors, or Version) instead of writing to the console itself; override it with CliOutput.layerPresenter(presenter).
HelpDoc is the data; the Formatter renders it; the Presenter decides whether and where to print it. Swap the formatter for colourless output, Markdown, or JSON; swap the presenter to keep stdout clean for machine-readable results, send usage errors to stderr, or silence help in an embedding host. Presenting never changes the result: implicit help and invalid invocations still fail with CliError.ShowHelp. --completions scripts, wizard output, and CliError.userMessage renderings bypass the presenter.
CliOutput.defaultPresenter writes help and version to Console.log, and on an invalid invocation the help to Console.log and the errors to Console.error. Without an installed Formatter, it uses the default formatter colored according to TerminalCapabilities.canColor, so NO_COLOR, FORCE_COLOR, and TERM=dumb are honored.
CliOutput.defaultFormatter({ colors?, inheritedFlags?, globalFlags? }) takes "full" (default), "summary", or "none" for the INHERITED FLAGS and GLOBAL FLAGS sections of subcommand help. "summary" replaces the section with a pointer such as Run 'comp --help' for inherited flags; a command that declares global flags always lists them in full.
CliOutput.displayWidth(text) exposes the built-in help/table terminal-cell measurement for custom formatters. It ignores ANSI escapes, handles combining/zero-width characters, and accounts for wide graphemes: use it rather than text.length or padEnd when aligning terminal columns.
Self-contained source · Type-checked
ts
import { Console, Effect } from "effect"import { CliOutput } from "effect/cli"// Plain text, and subcommand help that points at the parent instead of repeating its flags.const plainFormatter = CliOutput.defaultFormatter({ colors: false, inheritedFlags: "summary", globalFlags: "summary"})const program = Effect.gen(function*() { const fmt = yield* CliOutput.Formatter // Manually format a version string console.log(fmt.formatVersion("comp", "1.0.0"))}).pipe( Effect.provide(CliOutput.layer(plainFormatter)))// Keep stdout for results: usage errors go entirely to stderr; everything else is unchanged.const StderrPresenter = CliOutput.layerPresenter({ present: (event) => event._tag === "InvalidInvocation" ? Effect.gen(function*() { const formatter = yield* CliOutput.Formatter yield* Console.error(formatter.formatHelpDoc(event.helpDoc)) yield* Console.error(formatter.formatErrors(event.errors)) }) : CliOutput.defaultPresenter.present(event)})// Custom formatter — emit JSON for machine-readable help toolingconst jsonFormatter: CliOutput.Formatter = { formatHelpDoc: (doc) => JSON.stringify(doc, null, 2), formatCliError: (err) => JSON.stringify({ error: err._tag, message: err.message }), formatError: (err) => JSON.stringify({ error: err._tag, message: err.message }), formatVersion: (name, version) => JSON.stringify({ name, version }), formatErrors: (errs) => JSON.stringify(errs.map((e) => ({ tag: e._tag, message: e.message })))}const _ = [program, StderrPresenter, jsonFormatter]
Use when you need colourless CI output, machine-readable help (JSON/Markdown), or control over where built-in help and errors are written — override the formatter or presenter rather than post-processing printed strings.
A Context.Reference of { canColor, canAnimate, canPrompt } for the current process. Built-in Command help, version, and error output follows canColor (unless you install a CliOutput.Formatter), and fallback prompts from Flag.withFallbackPrompt / Argument.withFallbackPrompt run only when canPrompt is true. canAnimate is for your own output: it says whether stdout is being watched.
Detection.TERM=dumb clears all three. Otherwise a non-empty NO_COLOR disables color and wins over FORCE_COLOR; FORCE_COLOR forces color even off a TTY, except 0 and false; empty variables count as unset. canAnimate needs stdout to be a terminal, and canPrompt needs both stdin and stdout to be terminals. The default value is detected from process the first time it is read (all false without a process global); TerminalCapabilities.layer detects through the current ConfigProvider and the Stdio service instead, and never fails.
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Command, Flag, Prompt, TerminalCapabilities } from "effect/cli"const grant = Command.make( "grant", { employee: Flag.String("employee").pipe(Flag.withFallbackPrompt(Prompt.String({ message: "Employee ID: " }))) }, ({ employee }) => Effect.log(`granting to ${employee}`))// Force non-interactive behavior: no colors, and a missing --employee fails with MissingOption.const nonInteractive = Command.run(grant, { version: "1.0.0" }).pipe( Effect.provideService(TerminalCapabilities.TerminalCapabilities, { canColor: false, canAnimate: false, canPrompt: false }))// Application output can share the same answer.const banner = Effect.gen(function*() { const { canColor } = yield* TerminalCapabilities.TerminalCapabilities return canColor ? "\u001b[1mcomp\u001b[0m" : "comp"})const _ = [nonInteractive, banner]
Reach for it when a CLI must behave correctly in CI, pipes, and dumb terminals, or when your own output should color and animate under the same rules as the built-in help.
The stack has three levels. KeyValueStore supplies raw string/binary storage and swappable backends; Persistence stores schema-typed request Exit values in named stores; PersistedCache and PersistedQueue add cache and queue behavior on top. Browser, SQL, Redis, and filesystem modules provide concrete storage layers without changing the typed interface. RateLimiter and CircuitBreaker keep shared counters and circuit state in the same memory or Redis backends, and UserDirectories resolves where a local application should keep its files.
Warning: All modules in this chapter live under effect/persistence/.... Expect API changes between minor versions. Pin your Effect version and read the changelog before upgrading.
Effectful key-value store service for string and binary (Uint8Array) values. The lowest layer of the persistence stack — a uniform interface that Persistence and PersistedCache sit on top of. Swap the backend by swapping the layer.
Mental model. A service with get, set, remove, has, size, keys, clear, clearPrefix, and modify. get returns string | undefined (not an Option) — undefined on a miss. keys returns a snapshot of the stored keys in no particular order, and clearPrefix(prefix) removes only the keys that start with prefix. For typed structured data, use KeyValueStore.toSchemaStore to get a schema-aware wrapper whose get returns Option<A> (it exposes keys too).
KeyValueStore.prefix(store, p) is a namespaced view: every key is written as p + key, and its keys, size, isEmpty, and clear see only keys under p — keys returns them with p removed, and clear delegates to clearPrefix(p), leaving the rest of the backing store alone. keys, size, and isEmpty on a view list the whole backing store and filter it, so they cost a full key scan.
modify updates an existing key: on a miss it returns undefined without calling the callback or writing a value. Its default implementation reads and then writes in separate Effects, so concurrent callers can lose updates. The interface does not promise atomic read-modify-write; use a backend transaction or native atomic operation when that guarantee matters.
Self-contained source · Type-checked
ts
import { Effect, Option, Schema } from "effect"import { KeyValueStore } from "effect/persistence"// CompBand snapshot: level -> JSON band data (min/mid/max)class CompBand extends Schema.Class<CompBand>("CompBand")({ level: Schema.String, min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite}) {}const program = Effect.gen(function*() { const store = yield* KeyValueStore.KeyValueStore // Basic string operations — store a serialised snapshot key yield* store.set("snapshot:cycle:2024:L4", '{"min":90000,"mid":110000,"max":130000}') const raw = yield* store.get("snapshot:cycle:2024:L4") // raw is string | undefined — not an Option if (raw !== undefined) { console.log("snapshot found:", raw) } // Initialise once, then update an existing key (single-writer example). yield* store.set("snapshot:cycle:2024:L4:version", "0") const version = yield* store.modify("snapshot:cycle:2024:L4:version", (v) => String(Number(v) + 1) ) // version is "1" here; a missing key would return undefined, not be created. // Namespaced sub-view — prefix all keys automatically const bandStore = KeyValueStore.prefix(store, "compband:") yield* bandStore.set("L5", '{"min":130000,"mid":155000,"max":180000}') // stored in the backing store as "compband:L5" console.log("bands:", yield* bandStore.keys) // ["L5"] — only keys under the prefix, prefix removed // bandStore.clear would remove only "compband:*" keys, like store.clearPrefix("compband:") // Schema-typed store — values encoded/decoded with Schema const typedStore = KeyValueStore.toSchemaStore(store, CompBand) yield* typedStore.set("L6", new CompBand({ level: "L6", min: 160000, mid: 195000, max: 230000 })) const band = yield* typedStore.get("L6") // Option<CompBand> if (Option.isSome(band)) { console.log("L6 mid-point:", band.value.mid) }})// Plug in the backend via a layerconst TestLayer = KeyValueStore.layerMemory // in-process, volatile// Production alternatives:// KeyValueStore.layerFileSystem("./data") — files on disk// KeyValueStore.layerSql({ table: "kv_store" }) — SQL-backed (needs SqlClient)// KeyValueStore.layerStorage(() => localStorage) — browser localStorage
layerMemory — In-process Map. Zero deps, great for tests. Volatile — wiped on restart.
layerFileSystem(dir) — One file per key under dir (keys are percent-encoded into file names, so they are only guaranteed distinct on a case-sensitive file system). Needs the FileSystem + Path services, supplied by a host layer such as NodeServices.layer from @effect/platform-node. clear removes the directory recursively — never point it at a directory shared with other data; UserDirectories resolves a per-application directory for it. remove of a key that does not exist succeeds, as on the other backends.
layerSql(options?) — SQL table (default: effect_key_value_store). Works with any SqlClient dialect; clearPrefix matches the prefix exactly (case-sensitively) on every dialect.
layerStorage(evaluate) — Wraps a lazily-evaluated Storage-shaped object (browser localStorage, etc.).
Browser layers — BrowserKeyValueStore.layerLocalStorage, layerSessionStorage, and layerIndexedDb(options?) from @effect/platform-browser. The IndexedDB layer needs the IndexedDb service and is the asynchronous alternative to the synchronous Web Storage layers; IndexedDB can be unavailable in private or restricted browsing contexts.
Every built-in layer implements keys and clearPrefix natively. A custom store built with KeyValueStore.make or makeStringOnly must supply keys; if it omits clearPrefix, the derived one lists keys and removes the matches one at a time, which is neither atomic nor cheap on a large store.
Reach for it when you need lightweight durable string storage without an opinionated client, or when building a custom persistence backend for higher-level modules.
A service that resolves where a local application (a CLI, a desktop tool, a dev server) keeps its files: home, plus config(appName), data(appName), cache(appName), and state(appName), each an Effect<string, PlatformError>. It only computes paths; it creates no directory.
Mental model. An absolute XDG_CONFIG_HOME / XDG_DATA_HOME / XDG_CACHE_HOME / XDG_STATE_HOME wins on every platform (a relative one is ignored), with the application name appended. Otherwise the native location is used: ~/.config, ~/.local/share, ~/.cache, and ~/.local/state on Linux and other Unix systems; ~/Library/Application Support (config, data, and state) and ~/Library/Caches on macOS; %APPDATA%\<app> (config and data), %LOCALAPPDATA%\<app> (state), and %LOCALAPPDATA%\<app>\Cache on Windows. Variables are read through the current ConfigProvider on every call, so tests can supply them with ConfigProvider.fromEnv; a missing HOME (USERPROFILE on Windows) fails with a NotFoundPlatformError.
Self-contained source · Type-checked
ts
import { ConfigProvider, Effect, Layer } from "effect"import { KeyValueStore, UserDirectories } from "effect/persistence"// A file-backed store in the application's own config directory,// e.g. ~/.config/comp-admin/settings on Linux.const SettingsStore = Layer.unwrap( Effect.gen(function*() { const dirs = yield* UserDirectories.UserDirectories const config = yield* dirs.config("comp-admin") // Keep each store in its own subdirectory: layerFileSystem's clear is recursive. return KeyValueStore.layerFileSystem(`${config}/settings`) })).pipe(Layer.provide(UserDirectories.layer))// Resolve for another platform, with a pinned environment, in a test.const macCache = UserDirectories.make({ platform: "darwin" }).cache("comp-admin").pipe( Effect.provideService( ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env: { HOME: "/Users/ada" } }) )) // "/Users/ada/Library/Caches/comp-admin"const _ = [SettingsStore, macCache]
UserDirectories.layer resolves for the host platform; layerPlatform(platform) and make({ platform }) resolve for "win32", "darwin", "linux", and so on. On macOS and Windows config and data are the same directory (and macOS state joins them), which is the native convention, so give each kind its own subdirectory when one application uses several.
Reach for it when a locally installed program needs a conventional place for settings, caches, or history — typically as the directory of KeyValueStore.layerFileSystem.
Service that creates named stores for schema-typed Exit values keyed by Persistable requests. Where KeyValueStore speaks raw strings, Persistence speaks typed success/failure results — it serializes an Exit<A, E> using the request's success and error schemas, and deserializes it on the next read.
Mental model. A factory yielding scoped PersistenceStore instances. Each store is bound to a storeId (a namespace in the backing store) and an optional TTL function. Call store.get(request) to retrieve a previously persisted Exit (undefined on a miss); call store.set(request, exit) after computing a fresh result. The store handles encoding, decoding, and expiry.
Self-contained source · Type-checked
ts
import { Effect, Exit, Schema } from "effect"import { Persistence, Persistable} from "effect/persistence"// A persistable request for fetching a CompBand by levelclass BandNotFound extends Schema.TaggedError<BandNotFound>()("BandNotFound", { level: Schema.String}) {}class CompBand extends Schema.Class<CompBand>("CompBand")({ level: Schema.String, min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite}) {}class GetCompBand extends Persistable.Class<{ payload: { level: string }}>()("GetCompBand", { primaryKey: (payload) => `compband:${payload.level}`, success: CompBand, error: BandNotFound}) {}const program = Effect.gen(function*() { // Obtain the Persistence service and create a named store const persistence = yield* Persistence.Persistence const store = yield* persistence.make({ storeId: "comp-bands", // Keep successful band data for 1 hour, errors for 5 minutes timeToLive: (exit, _req) => Exit.isSuccess(exit) ? "1 hour" : "5 minutes" }) const req = new GetCompBand({ level: "L5" }) // Check for a persisted result. The operation is an Effect whose success // value is Exit | undefined and whose errors include persistence/decoding. const cached = yield* store.get(req) if (cached !== undefined) { // cached is Exit<CompBand, BandNotFound> — yield it to get the value or re-raise the error const band = yield* cached console.log("persisted band:", band) return } // Miss — fetch from HRIS and persist the result const band = new CompBand({ level: "L5", min: 130000, mid: 155000, max: 180000 }) yield* store.set(req, Exit.succeed(band)) console.log("fetched and stored:", band)}).pipe( Effect.scoped // PersistenceStore is scoped — released when done)// Wire up: memory for dev, Redis or SQL for prodconst layers = Persistence.layerMemory// Persistence.layerRedis — needs Redis service// Persistence.layerSql — needs SqlClient// Persistence.layerKvs — needs KeyValueStore
Process-local map; entries expire by TTL and vanish on restart
—
Persistence.layerKvs
Any KeyValueStore backend, keys <storeId>:<key>
KeyValueStore
Persistence.layerSql
One shared effect_persistence table, rows partitioned by store id
SqlClient
Persistence.layerSqlMultiTable
One table per store id, named effect_persistence_<storeId>
SqlClient
Persistence.layerRedis
Redis keys <storeId>:<key> with native expiry
Redis.Redis
Stores are isolated namespaces. On the KeyValueStore and Redis backings every entry lives under <storeId>:<key>, with % and : in the store id percent-encoded (my:store becomes my%3Astore:), so two stores can never map different keys to the same backing key, and store.clear removes only that store's entries (through KeyValueStore.clearPrefix, or a Redis KEYS match on the namespace). layerSql keeps the store id in its own column. layerSqlMultiTable puts the store id into a table name without encoding: avoid dots, case-only differences, and ids long enough to hit the database's identifier limit (PostgreSQL truncates at 63 bytes), because colliding names share — and clear — each other's entries. Prefer layerSql for arbitrary store ids.
The TTL function decides whether anything is stored. Omitting timeToLive keeps entries forever; returning a zero or negative duration for an Exit skips the write entirely, which is how you keep failures out of the store.
Stored bytes are a compatibility contract. The storeId, the primary key, and the success / error schemas together define what a later release must still be able to read. After an incompatible schema change, store.get fails with SchemaError for the old entry instead of reporting a miss (PersistedCache treats that as a miss; see below). Version the storeId (or the key) when the shape changes, and never build keys by concatenating ambiguous user strings.
Migration: the <storeId>:<key> layout replaced the 4.0 layout, and old entries are not migrated or removed. On layerKvs / layerBackingKvs every entry written by 4.0 (keyed <storeId><key>, with no separator) becomes unreachable: cached results are recomputed, and Chat.layerPersisted on a KeyValueStore backing loses its stored chat histories. On layerRedis / layerBackingRedis keys are unchanged unless the store id contains % or :; entries for those store ids become unreachable. Plan the cold start, and delete the orphaned keys yourself if the space matters.
Security note: the SQL-backed stores bind getMany keys as query parameters rather than splicing them into the statement text. Keys come from PrimaryKey.value(request), so this holds even when untrusted input reaches a Persistable primary key (including through PersistedCache or RequestResolver.persisted).
Reach for it when you want cross-restart memoization for expensive effectful computations and need the full typed Exit (success or failure) to survive a process restart.
The protocol connecting a request value to its persistence schemas. A Persistable<A, E> is a PrimaryKey (provides a stable string key) that also carries a success schema A and an error schema E at the type level. Persistence and PersistedCache use those schemas to encode and decode the stored Exit value.
Mental model. An extended Request that declares not just the result type but also how to serialize it. Persistable.Class is the idiomatic constructor — it combines Request.Class with schema attachment and primary-key derivation. The primaryKey callback receives the payload fields directly as its argument.
Self-contained source · Type-checked
ts
import { PrimaryKey, Schema } from "effect"import { Persistable } from "effect/persistence"class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.String, baseSalary: Schema.Finite}) {}class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { id: Schema.Int.check(Schema.isGreaterThan(0))}) {}// Persistable.Class combines: Request + PrimaryKey + serialization schemas.// The primaryKey callback receives the payload fields directly.class GetEmployee extends Persistable.Class<{ payload: { id: number }}>()("GetEmployee", { primaryKey: (payload) => `employee:${payload.id}`, success: Employee, error: EmployeeNotFound}) {}// Construct a requestconst req = new GetEmployee({ id: 42 })console.log(PrimaryKey.value(req)) // "employee:42"console.log(req._tag) // "GetEmployee"// GetEmployee also extends Request.Request<Employee, EmployeeNotFound | ...>// so it can be passed to Effect.request + a RequestResolver.// Passing it to RequestResolver.persisted transparently adds cross-restart// caching without changing the call site.
Tip: A class generated by Persistable.Class is simultaneously a valid Request (can be passed to Effect.request), a valid PrimaryKey (has a stable string key), and a Persistable (carries schemas). This lets RequestResolver.persisted transparently wrap any resolver to add cross-restart caching without changing the call site.
RequestResolver.persisted(resolver, { storeId, timeToLive?, staleWhileRevalidate? }) needs Persistence and a Scope. Stored results are loaded before the wrapped resolver runs, and only the misses are resolved and written back; an entry that staleWhileRevalidate marks stale is answered from the store at once and resolved again so the refreshed result replaces it; only refresh results are written back, a whole-batch refresh failure replaces the stale value, and a refresh that completes no entries leaves the original expiry unchanged. A failure of the wrapped resolver propagates to the waiting requests, while results that already completed are preserved. See RequestResolver.
Reach for it when building a PersistedCache or using RequestResolver.persisted — schemas must be declared upfront so the persistence layer can serialize results.
A two-tier cache: in-process Cache in front of a durable Persistence store. On a miss, it checks the persistence store before running the lookup. A persistence-layer hit restores the result without calling the lookup effect — across process restarts.
Mental model. L1 = in-memory (fast, lost on restart). L2 = persistence store (slower, survives restarts). The lookup is only called on a true L2 miss. Its result is persisted before being returned into L1; writes are not simultaneous. Invalidation clears both.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"import { Persistable, PersistedCache, Persistence} from "effect/persistence"// Durable cache for employee compensation lookups —// avoids hammering the HRIS on every org-chart render.class Employee extends Schema.Class<Employee>("Employee")({ id: Schema.Int.check(Schema.isGreaterThan(0)), name: Schema.String, level: Schema.String, baseSalary: Schema.Finite}) {}class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { id: Schema.Int.check(Schema.isGreaterThan(0))}) {}class GetEmployee extends Persistable.Class<{ payload: { id: number }}>()("GetEmployee", { primaryKey: (payload) => `employee:${payload.id}`, success: Employee, error: EmployeeNotFound}) {}// Simulate an HRIS fetchdeclare const fetchEmployeeFromHris: (id: number) => Effect.Effect<Employee, EmployeeNotFound>const program = Effect.scoped( Effect.gen(function*() { const empCache = yield* PersistedCache.make( // Lookup: called only on a true L1+L2 miss (req: GetEmployee) => fetchEmployeeFromHris(req.id), { storeId: "employees", // timeToLive receives (exit, request) — keep successes 1 hour, errors 5 min timeToLive: (exit, _req) => exit._tag === "Success" ? "1 hour" : "5 minutes", inMemoryCapacity: 512, inMemoryTTL: () => "5 minutes" } ) // First call: L1 miss → L2 miss → calls HRIS const emp1 = yield* empCache.get(new GetEmployee({ id: 101 })) // Same process: L1 hit — no HRIS call const emp2 = yield* empCache.get(new GetEmployee({ id: 101 })) // After restart: L1 cold, L2 hit — still no HRIS call console.log(emp1.name, emp2.name) // Invalidate both tiers (e.g. after a salary change) yield* empCache.invalidate(new GetEmployee({ id: 101 })) }))// Provide Persistence — swap for Redis/SQL in productionconst layers = Persistence.layerMemory
Failures are cached too. The whole Exit is persisted, so a failed lookup is replayed — across restarts and across processes — until its TTL expires. That includes defects: a lookup function that throws synchronously is captured and persisted the same way. Return Duration.zero from timeToLive for the exits you do not want stored, or give failures a short TTL as above.
Defaults:inMemoryCapacity is 1024 and inMemoryTTL is 10 seconds, so without overrides most reads after the first 10 seconds go to the persistence store rather than memory.
An entry that no longer decodes is a miss. After a success- or error-schema change, get runs the lookup and replaces the stored entry with the new result instead of failing with SchemaError. Moving to a new storeId is still the cleaner cut-over when many entries change shape at once, because each stale entry otherwise costs one failed decode before it is replaced.
It is a cache, not a record. Do not read business state back out of it, and do not rely on it to suppress duplicate work across a fleet.
Reach for it when you want Cache semantics with durability — expensive lookups that should survive restarts and be shared across multiple worker processes connected to the same backing store.
A durable work queue backed by persistent storage. Items are schema-encoded before enqueueing; workers call queue.take(handler) to claim and process one item at a time. If the handler succeeds the item is acknowledged as processed; if it fails the item becomes visible again after a delay chosen by the queue's retry schedule, until maxAttempts is exhausted and the item is dead-lettered (marked failed and kept). Restarts replay unacknowledged items automatically.
Mental model. Outbox-style queue — producer writes the intent, consumer processes idempotently. Useful for any work that must not be lost if the process dies mid-flight. Delivery is at-least-once, so the handler's side effect needs its own idempotency key.
The retry policy belongs to the queue, not to an individual take call:
maxAttempts defaults to 10. An attempt is counted when the item is claimed, so attempts in the handler metadata is 1-based ("this is attempt 3") and a handler crash that kills the process still consumes an attempt.
retrySchedule defaults to an exponential delay starting at 1 second and capped at 5 minutes. Its input is the attempt number, and the persisted attempt count is the schedule state — the schedule is replayed up to the current attempt on each failure, so delays keep progressing even when consecutive retries run in different processes. Attempt-driven schedules are therefore exact; a wall-clock schedule such as Schedule.upTo bounds the summed delays, not real elapsed time.
An item that no longer decodes with the queue's schema is dead-lettered immediately and the next item is taken, so a schema change can never wedge the consumer — but it also means an incompatible schema change silently diverts old items. Evolve the item schema compatibly.
Self-contained source · Type-checked
ts
import { Effect, Layer, Schedule, Schema } from "effect"import { PersistedQueue } from "effect/persistence"// Each item in the queue is a pending raise approval request.const RaiseApprovalSchema = Schema.Struct({ employeeId: Schema.Int.check(Schema.isGreaterThan(0)), managerId: Schema.Int.check(Schema.isGreaterThan(0)), currentSalary: Schema.Finite, proposedSalary: Schema.Finite, meritCycleId: Schema.String})type RaiseApproval = Schema.Schema.Type<typeof RaiseApprovalSchema>const program = Effect.gen(function*() { // Obtain a named queue via PersistedQueueFactory (provided by PersistedQueue.layer). // The retry policy is part of the queue definition. const queue = yield* PersistedQueue.make({ name: "raise-approvals", schema: RaiseApprovalSchema, maxAttempts: 5, retrySchedule: Schedule.exponential("2 seconds") }) // Producer: enqueue a raise recommendation (returns the assigned item id) const itemId = yield* queue.offer({ employeeId: 42, managerId: 7, currentSalary: 120000, proposedSalary: 132000, meritCycleId: "cycle:2024" }) console.log("enqueued raise approval:", itemId) // Idempotent offer: pass a custom id to avoid double-queueing on retry yield* queue.offer( { employeeId: 42, managerId: 7, currentSalary: 120000, proposedSalary: 132000, meritCycleId: "cycle:2024" }, { id: `raise:${42}:cycle:2024` } ) // Consumer: process one approval at a time. // On success → acknowledged. On failure → retried on the queue's schedule, // then dead-lettered once maxAttempts is reached. yield* queue.take((approval: RaiseApproval, { id, attempts }) => Effect.log( `[attempt ${attempts}] processing raise for employee ${approval.employeeId} (item ${id})` ) )})// In-memory store: volatile, great for tests.// layer provides PersistedQueueFactory from PersistedQueueStore.const StoreLayer = PersistedQueue.layerStoreMemoryconst layers = Layer.mergeAll( PersistedQueue.layer, // Retention: run in ONE instance of a deployment, not on every worker. PersistedQueue.layerCleanup({ interval: "1 hour", timeToLive: "30 days" })).pipe(Layer.provide(StoreLayer))// Production stores:// PersistedQueue.layerStoreRedis(redisConfig)// PersistedQueue.layerStoreSql(sqlConfig)
Tip: Pass a custom id to queue.offer(value, { id }) and the queue will silently skip re-enqueueing if that id is already present. This gives idempotent producers — safe to call on retry without double-queueing. De-duplication outlives completion by default (deduplicate: "untilRemoved"): the id keeps suppressing duplicates until layerCleanup removes the completed element (timeToLive, default 30 days), so size that window to your longest producer replay.
queue.offer(value, { id, deduplicate: "untilExecuted" }) reserves the id only while its element is pending, processing, or waiting to retry. Once the element completes or fails its final attempt, the next offer of that id enqueues a new element behind queued work, with its own delay — a "coalesce while queued, run again afterwards" key such as recompute-band:L5, not an idempotency key. The mode is chosen per offer and is not stored with the id, so do not mix the two modes on one id. Two consequences to design for:
An offer that arrives after the handler read its inputs but before the element completes is ignored, so have the handler read current state (or check a version) rather than trust the offered value.
A re-offered failed id can replace its earlier failure record: the SQL store and Cloudflare's queue keep only the latest failure, while the Redis store keeps every failure in its failed list until layerCleanup removes it with failedTimeToLive (and an id whose failure was recorded by an older effect release stays reserved until then, even for "untilExecuted" offers). Inside a SQL transaction the check reads the transaction's snapshot, so under MySQL's default REPEATABLE READ an element that finished after the first read still looks in flight and the offer is ignored.
Use queue.offer(value, { delay: "5 minutes" }) to postpone first delivery, independently of the retry schedule and without counting an attempt. The memory, Redis, and SQL stores support this option; a finite positive delay enqueues now but makes the item claimable later. Delivery can lag visibility by the store's polling interval. SQL measures offer and retry delays with the database clock and rounds them up to whole seconds, so an item is never claimable early (MySQL, which stores whole-second timestamps, adds one more second); Redis depends on agreement between producer and worker clocks. Zero, negative, and omitted delays enqueue immediately. An infinite delay stores nothing, not even a deduplication record, although the offer returns its ID. An existing custom ID is still deduplicated, not rescheduled by a repeated offer.
PersistedQueue.layerCleanup deletes completed elements after timeToLive. Failed elements are the dead-letter record and are kept forever unless you set failedTimeToLive — monitor and drain them deliberately. The SQL store creates and upgrades its tables through versioned migrations.
A custom PersistedQueueStore receives each offer's deduplicate mode (undefined means "untilRemoved"), and must store an "untilExecuted" re-offer of a completed or failed id as a new element after earlier offers, atomically with respect to concurrent offers of that id. When a take scope fails, check PersistedQueue.isDeadLetterCause(cause): it is true when the queue could not decode the stored payload, and the store must then mark the element failed at once, whatever attempts remain.
The SQL and Redis stores claim an item with a per-acquisition lock that is refreshed while the handler runs (lockRefreshInterval, default 30 seconds) and expires after lockExpiration (default 2 minutes for SQL, 90 seconds for Redis); both poll every second by default. Interrupting the handler releases the item without consuming the attempt, so a graceful shutdown does not push work toward the dead-letter state. A hard kill cannot run that release: the attempt stays counted and the item becomes claimable again once its lock expires.
Settlements and lock refreshes are fenced by that acquisition: once a lapsed claim has been recovered and the item claimed again, the old handler's complete, fail, retry, or release changes nothing, so a stalled worker cannot settle a newer claim on the same id. Until another poll recovers the item, a handler whose lock lapsed can still settle or renew it.
Migration: the Redis store's lock format is incompatible with 4.0 workers on the same prefix — their settlements are not fenced and can corrupt newer claims. Stop every old worker and wait for its locks to expire (lockExpiration) before starting upgraded workers, and keep the existing Redis data rather than flushing it.
PersistedQueue.layerStoreSql() built on the same SqlClient as your repositories makes queue.offer part of your transaction. The offer is a single insert on that client, so inside sql.withTransaction it commits or rolls back with the domain write — the transactional outbox without a hand-written relay.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"import { PersistedQueue } from "effect/persistence"import { SqlClient } from "effect/sql"const RaiseApproved = Schema.Struct({ employeeId: Schema.Int, cycle: Schema.String, newSalary: Schema.Int})const approveRaise = Effect.fn("approveRaise")( function*(employeeId: number, cycle: string, newSalary: number) { const sql = yield* SqlClient.SqlClient const events = yield* PersistedQueue.make({ name: "raise-approved", schema: RaiseApproved }) yield* sql.withTransaction( Effect.gen(function*() { yield* sql`update employees set base_salary = ${newSalary} where id = ${employeeId}` // Same client, same transaction: a rollback removes the queued event as well. // The id is derived from the business fact, so a replayed request cannot enqueue it twice. yield* events.offer({ employeeId, cycle, newSalary }, { id: `raise-approved:${cycle}:${employeeId}` }) }) ) })
The memory and Redis stores share no transaction with your database: a crash between the domain commit and the offer loses the item, and an offer placed before the commit can announce a change that rolls back. With those stores, write the intent row yourself — see Recipe: A Transactional Write with an Outbox.
Start from an invariant ("every accepted raise reaches delivered or dead-letter") and mark the crash windows on the path input → durable state → claim → external effect → result persisted → acknowledged.
Outcome of an external call
What is known
What to do
Failed before dispatch
Nothing reached the sink
Retry freely.
Known failure after dispatch
The sink rejected it
Retry only if the rejection is transient; otherwise dead-letter.
Unknown — timeout, interruption, or crash after dispatch
The sink may have applied it
Never replay a mutation blindly. Reconcile through the sink's idempotency key or status API, or park the item for operator repair.
Acknowledging after the effect means at-least-once. A crash between "the sink accepted" and "the item is acknowledged" re-runs the handler, so the side effect needs an idempotency key derived from the item id — not one generated per attempt.
A lock is a lease; the queue fences only itself. A worker that stalls longer than lockExpiration loses its claim while it is still running, and a second worker starts the same item. The store fences its own bookkeeping — the stale worker cannot settle the newer claim — but nothing fences the stale worker's side effects: when a stale owner must not commit, the sink has to reject it — a monotonic token, a compare-and-set, or a uniqueness constraint that your protocol creates, persists, and checks.
Process death skips finalizers. Restart behavior must never depend on a release action having run; graceful shutdown should acknowledge only outcomes that are already committed.
Keep defects and interruption out of business retry. A defect is a bug to fix, and interruption is cancellation — neither is evidence that the sink is unavailable.
Label each guarantee by its evidence: proved by the library (attempt counting, dead-lettering), dependent on the adapter (Redis persistence settings, SQL isolation), dependent on the deployment (one cleanup instance, clock skew), or design guidance you must implement (idempotent sinks, fencing).
Test recovery in three separate lanes: a deterministic state machine on layerStoreMemory with TestClock; the real adapter with a kill-and-restart of the worker; and the built artifact. Cover the crash matrix — before the effect · after the sink accepted but before the result is stored · after the result but before the acknowledgement · during a retry delay · after lock expiry with the old owner paused · store outage · mixed old/new item schemas · a corrupt payload · restore from backup. Operator actions (inspect, cancel, redrive, release from dead-letter) change business outcomes, so authorize and audit them, and rehearse a restore rather than trusting that a backup exists. Workflows and cluster delivery add their own replay rules — see the durability and distribution ladder.
Reach for it when you need guaranteed-at-least-once delivery of background jobs that must survive process restarts and can be retried on failure.
A persistent token-bucket/fixed-window rate limiter. Stores counters in a shared backing store (memory or Redis), so limits apply across fibers and—with Redis—across multiple processes or pods.
Mental model. Each call to limiter.consume(options) atomically updates limiter state: fixed-window increments usage, while token-bucket consumes available tokens. The returned ConsumeResult carries delay, remaining, limit, and resetAfter. The onExceeded option controls whether to fail immediately ("fail") or return a delay to wait ("delay"). Use makeWithRateLimiter to wrap effects automatically, or sleep(limiter, options) to consume and sleep until the limiter allows the next call.
Self-contained source · Type-checked
ts
import { Duration, Effect, Layer } from "effect"import { RateLimiter } from "effect/persistence"// Cap calls to the HRIS and payroll API to respect their published quotas.const program = Effect.gen(function*() { // Low-level: consume tokens directly const limiter = yield* RateLimiter.make const result = yield* limiter.consume({ key: "hris-api:read", limit: 200, window: "1 minute", algorithm: "fixed-window", onExceeded: "fail", // throws RateLimiterError when exceeded tokens: 1 }) console.log(`remaining HRIS quota: ${result.remaining}, resets in: ${result.resetAfter}`) // High-level wrapper: automatically sleeps when limit is exceeded ("delay" strategy) const withLimiter = yield* RateLimiter.makeWithRateLimiter yield* Effect.log("submitting payroll change").pipe( withLimiter({ key: "payroll-api:write", limit: 50, window: "1 minute", algorithm: "token-bucket", onExceeded: "delay" }) ) // Sleep helper: consume a token and sleep for the delay before returning yield* RateLimiter.sleep(limiter, { key: "hris-api:read", limit: 200, window: "1 minute", algorithm: "fixed-window" }) // Continues only after the HRIS quota allows the next call // Adaptive lane: honor observed 429/Retry-After feedback, then learn a rate. const adaptive = yield* limiter.adaptiveConsume({ key: "payroll-api:adaptive", tokens: 1, fallbackLimit: 50, fallbackWindow: Duration.minutes(1) }) yield* Effect.sleep(adaptive.delay) const response = { status: 429, retryAfter: Duration.seconds(30) } yield* limiter.adaptiveFeedback({ key: "payroll-api:adaptive", epoch: adaptive.epoch, // correlate feedback with the state used for this request tokens: 1, status: response.status, retryAfter: response.retryAfter })})// Provide the store layer — RateLimiter.make requires RateLimiterStoreconst layers = RateLimiter.layer.pipe( Layer.provide(RateLimiter.layerStoreMemory) // in-process counters (not cross-process), swept every minute)// For cross-process:// RateLimiter.layer.pipe(Layer.provide(RateLimiter.layerStoreRedis(redisConfig)))
Stores.layerStoreMemory keeps counters in the process; each entry expires once its state is indistinguishable from a key never seen (the same TTLs the Redis store sets), and a background sweep scoped to the layer removes expired entries every minute, so an idle store drains to empty. layerStoreRedis keeps a key's state under <prefix><key>, with token-bucket refill times at <prefix><key>:refill and adaptive state at <prefix><key>:adaptive; % and : in the key are percent-encoded, so two different keys never share state.
Nonpositive limits admit nothing. A limit of 0 or less rejects every positive token request in "fail" mode, and returns an infinite delay (without touching the store) in "delay" mode — so a sleep or makeWithRateLimiter call on such a key never resumes. Validate limits that come from configuration.
fixed-window — Count requests within a time bucket. The window opens on the first admitted request for a key and lasts the full window; later requests do not extend it, and at most limit tokens are admitted in it. Cheap to compute; can allow 2x the limit across a window boundary if producers are synchronized. Best for loose API quota enforcement.
token-bucket — Tokens refill at whole-token boundaries over the window. This avoids fixed-window resets but still permits bursts up to bucket capacity; it is not a no-burst guarantee. Use it for sustained-rate control with an explicit burst allowance.
Adaptive limiting is a separate feedback API, not another algorithm string. Call adaptiveConsume before the request, retain its epoch, then report the response with adaptiveFeedback. The state progresses through inactive, cooldown, learning, and learned: a 429 with Retry-After starts or extends cooldown, later traffic measures an accepted rate, and learned state schedules future requests accordingly. The in-memory store coordinates only one process; use the Redis store when this learned state must be shared by several workers.
Note: Writing a custom RateLimiterStore? tokenBucket must return [remaining, elapsedMillis] from one atomic operation — the tokens left after consuming, and the time since the current refill interval started (at least 0, less than the refill interval). The limiter derives delay and resetAfter from both; returning [remaining, 0] reproduces the old timing error. Token-bucket timing follows whole-token refill boundaries, and fixed-window resetAfter reports the exact remaining window under onExceeded: "delay" instead of rounding up to a full window.
Reach for it when you need rate limits that work across multiple fibers or processes — protecting external APIs or enforcing per-tenant quotas in a multi-worker deployment.
Keyed circuit breakers for calls to an unreliable dependency. One breaker holds one circuit per key (a host, a tenant, an endpoint), and the circuit state lives in a CircuitBreakerStore: layerStoreMemory() keeps it in the process, layerStoreRedis(options?) (or layerStoreRedisConfig) shares it between processes through Redis.
Mental model.Closed: calls run and a trip policy watches their outcomes. Open: calls fail at once with CircuitBreakerError whose reason is CircuitOpen (carrying retryAfter) until the open time ends. HalfOpen: the next call is the probe and concurrent calls fail with CircuitHalfOpen; a successful probe closes the circuit, a failed one reopens it, and an interrupted or ignored probe frees the slot. The breaker never waits and never retries — put Effect.retry and Effect.timeoutinside it so it sees one outcome per call, and retry rejections outside it if you want to wait for the circuit.
Fragment · Type-checked
ts
// @effect-diagnostics experimentalApiUsage:offimport { Data, Duration, Effect, Exit, Layer, Option, Schedule } from "effect"import { HttpClient } from "effect/http"import { CircuitBreaker } from "effect/persistence"class PayrollError extends Data.TaggedError("PayrollError")<{ readonly status: number }> {}declare const submitPayrollChange: (employeeId: string) => Effect.Effect<void, PayrollError>const program = Effect.gen(function*() { const breaker = yield* CircuitBreaker.make({ tripPolicy: CircuitBreaker.consecutive(5), // open after 5 failures in a row // Each consecutive opening lasts the schedule's next delay: 1 s, 2 s, 4 s, ... // The cap is measured in time spent open; past one minute openings stop growing. openDuration: Schedule.exponential("1 second").pipe(Schedule.upTo({ duration: "1 minute" })) }) const submit = (employeeId: string) => submitPayrollChange(employeeId).pipe( Effect.timeout("5 seconds"), // inside the breaker: a timeout counts as one failed call breaker.execute({ key: "payroll-api", // A 4xx means payroll answered; only server errors and timeouts count against it. classify: (exit) => Exit.isSuccess(exit) ? CircuitBreaker.success : Option.match(Exit.findErrorOption(exit), { onNone: () => CircuitBreaker.ignored, // defects are bugs, not outages onSome: (error) => error._tag === "PayrollError" && error.status < 500 ? CircuitBreaker.success : CircuitBreaker.failure() }) }) ) yield* submit("emp-42").pipe( Effect.catchReason("CircuitBreakerError", "CircuitOpen", (reason) => Effect.logWarning(`payroll circuit open; retry in ${Duration.toMillis(reason.retryAfter)} ms`)) ) const state = yield* breaker.state("payroll-api") // { _tag: "Closed" | "Open" | "HalfOpen", ... } yield* Effect.log(`payroll circuit is ${state._tag}`)}).pipe(Effect.scoped, Effect.provide(CircuitBreaker.layerStoreMemory()))// HTTP: one circuit per request origin, applied after retries so an open circuit skips the retry loop.const GuardedClient = Effect.gen(function*() { const breaker = yield* CircuitBreaker.CircuitBreaker const client = yield* HttpClient.HttpClient return client.pipe( HttpClient.retryTransient({ times: 2 }), HttpClient.withCircuitBreaker({ breaker }) )})const BreakerLive = CircuitBreaker.layer({ tripPolicy: CircuitBreaker.rate({ threshold: 0.5, size: 20 }), // >= 50% of the last 20 calls failed openDuration: "30 seconds"}).pipe(Layer.provide(CircuitBreaker.layerStoreMemory()))const _ = [program, GuardedClient, BreakerLive]
Option or API
Meaning
consecutive(n)
opens after n failures in a row, counted in order of completion; only a success resets the streak
rate({ threshold?, size?, minimumCalls? })
opens when the failure fraction over the last size recorded outcomes reaches threshold (defaults 0.5, 100, and minimumCalls = size)
openDuration
a duration, or a Schedule whose n-th delay is the n-th consecutive opening; the backoff count resets once the circuit has stayed closed as long as it was last open
maxOpenDuration
caps a failure({ retryAfter }) hint (default one hour); it never caps openDuration
onStoreError
"allow" (default) runs the call unrecorded when the store is unavailable; "fail" fails it with CircuitBreakerStoreError
classify
a CircuitBreaker.Classifier: (exit, { probe }) => Outcome (or an Effect of one) mapping the call's Exit to success, ignored, or failure({ retryAfter? }); without it a success is a success and any failure is a failure. probe is true for the HalfOpen probe, so an outcome you normally ignore (a 429, say) can count as a failure that reopens the circuit. Interruption is always ignored
onRejection (per execute)
"fail" (default) fails a call the circuit refuses with CircuitOpen / CircuitHalfOpen; "allow" runs the refused call unrecorded instead. Admitted calls, the probe included, are recorded either way — so a write that must always run can still feed the circuit that guards the reads sharing its key
state(key) / transitions
read one circuit from the shared store / a stream of this breaker instance's own transitions
One policy per key. Breakers that share a key and a store share one circuit, and nothing checks that their policies agree; separate them with distinct keys or a Redis prefix. CircuitBreaker.layer(options) provides one default CircuitBreaker service; for several policies, use a LayerMap over CircuitBreaker.layer with one shared store.
It is silent. It emits no metrics or spans: observe it through state, transitions, and the typed rejection. Store errors it swallows (a fail-open admit, a failed record, a failed Redis lease renewal) are logged at References.UnhandledLogLevel.
Redis store details. Each circuit is one hash at prefix + key (default prefix "circuitbreaker:"), timed by the Redis server clock, and requires Redis 5 or later. The probe holds a lease (probeLease, default 10 seconds) renewed while it runs; if renewals cannot reach Redis, the lease lapses and a second probe can start. Idle keys expire after idleTimeToLive (default one hour) and restart Closed.
HTTP.HttpClient.withCircuitBreaker({ breaker, key?, classify? }) (its classify receives { probe } too) keys circuits by request origin and classifies with HttpClient.circuitBreakerClassifier: 408, 500, 502, 503, 504, transport errors, and timeouts are failures; other responses (including other 4xx) are successes; 429, encode/decode errors, and defects are ignored. Apply it after withRateLimiter and retryTransient (which never retries a CircuitBreakerError), and give withRateLimiter a times bound so a long 429 wait cannot hold the probe slot. See HttpClient.
Reach for it when a dependency that is down should be failed fast and given room to recover, rather than hit by every caller and every retry.
A thin service wrapper around a Redis client used internally by the other persistence modules. Provides four primitives: send for raw Redis commands on the shared connection, subscribe(channel) for a scoped pub/sub subscription delivered as a Queue.Dequeue<RedisMessage, RedisError>, eval for executing typed Lua scripts via EVALSHA (with automatic script loading and SHA caching via SCRIPT LOAD), and reserve for leasing a dedicated pooled connection.
Mental model. The barrel exports a Redis module namespace; the service tag inside it is Redis.Redis. Prefer a ready-made platform layer: NodeRedis.layer(options) / NodeRedis.layerConfig(...) from @effect/platform-node (backed by node-redis), or the BunRedis / DenoRedis equivalents. They acquire a scoped client, close it when the layer scope ends, and also expose the raw client through a NodeRedis service. NodeRedis needs the redis package 5.1.0 or newer (below 7); closing its scope destroys the shared client at once, failing commands still in flight and aborting connection attempts, including reserved connections still being opened, and interrupting a subscribe whose connection or SUBSCRIBE is stalled closes that connection promptly. All three layers' options also accept the Redis.PoolOptions that size the reserve pool — maxConnections (default 10), minConnections (default 0), idleTimeout (default 60 seconds), and acquireTimeout (unbounded by default; on expiry reserve fails with RedisError). To bring your own client instead, wrap it with Redis.make({ send, subscribe, connect, pool? }) — send, subscribe, and connect are all required, and a hand-written Redis service object also needs a reserve member. Every module in this chapter with a layerXxxRedis variant requires Redis.Redis. Scripts are described with Redis.script(paramsToArgs, { lua, numberOfKeys }) — a two-argument form where the first argument maps typed parameters to Redis argument arrays.
Migration:Redis.make requires a connect option that opens one dedicated connection ({ send, close }); its close must fail any command still in flight on that connection. Hand-written Redis.Redis implementations must add reserve.
Blocking commands go on a reserved connection.XREAD BLOCK, XREADGROUP BLOCK, BLPOP, BRPOP, BLMOVE, BLMPOP, and WAIT hold up every command queued behind them on the shared connection. yield* redis.reserve leases a connection ({ send, eval }) that no other caller shares until the current scope closes; it then returns to the pool, unless a command on it failed, was interrupted, or is still running, in which case it is closed. The built-in reserved connections do not reconnect: a dropped socket fails the in-flight command and the connection leaves the pool.
Fragment · Type-checked
ts
import { Effect, Layer } from "effect"import { Redis } from "effect/persistence"// Imagine `redisClient` comes from ioredis or node-redis.interface RawClient { call(command: string, ...args: string[]): Promise<unknown> // Registers a listener and resolves to an unsubscribe function. subscribe(channel: string, listener: (message: string) => void): Promise<() => Promise<void>> // Opens another connection with the same settings. duplicate(): Promise<RawClient> // Closes the socket, rejecting commands still in flight. destroy(): void}declare const redisClient: RawClientconst sendWith = (client: RawClient) =><A = unknown>(command: string, ...args: ReadonlyArray<string>) => Effect.tryPromise({ try: () => client.call(command, ...args) as Promise<A>, catch: (e) => new Redis.RedisError({ cause: e }) })// Redis.make returns an Effect — provide it with Layer.effectconst RedisLayer = Layer.effect( Redis.Redis, Redis.make({ send: sendWith(redisClient), // One dedicated connection per reservation; `close` must fail in-flight commands. connect: Effect.tryPromise({ try: () => redisClient.duplicate(), catch: (e) => new Redis.RedisError({ cause: e }) }).pipe( Effect.map((connection) => ({ send: sendWith(connection), close: Effect.sync(() => connection.destroy()) })) ), pool: { maxConnections: 4, acquireTimeout: "5 seconds" }, // Scoped subscription: register the listener, unsubscribe when the scope closes, // and return an Effect that fails if the subscriber connection later breaks. subscribe: (channel, onMessage) => Effect.acquireRelease( Effect.tryPromise({ try: () => redisClient.subscribe(channel, (message) => onMessage({ channel, message })), catch: (e) => new Redis.RedisError({ cause: e }) }), (unsubscribe) => Effect.promise(() => unsubscribe()) ).pipe(Effect.as(Effect.never)) }))// With the Redis layer provided, the persistence modules pick it up:// Persistence.layerRedis// RateLimiter.layerStoreRedis(config)// PersistedQueue.layerStoreRedis(config)// Lua scripting: Redis.script takes (paramsToArgs, { lua, numberOfKeys })// Use .withReturnType<R>() to type the return value.const atomicIncrScript = Redis.script( // First arg: maps typed params to the Redis args array (key: string, amount: string) => [key, amount], { lua: ` local current = redis.call('GET', KEYS[1]) local next = (tonumber(current) or 0) + tonumber(ARGV[1]) redis.call('SET', KEYS[1], tostring(next)) return next `, numberOfKeys: 1 // constant — or pass a function (key, amount) => number }).withReturnType<number>()// Example: atomically increment a per-department merit-budget draw-down counterconst program = Effect.gen(function*() { const redis = yield* Redis.Redis const evalScript = redis.eval(atomicIncrScript) // First call: SCRIPT LOAD → EVALSHA. Subsequent calls: EVALSHA directly. // On NOSCRIPT error (Redis restart): automatically reloads and retries. const newTotal = yield* evalScript("budget:dept:engineering:drawn", "5000") console.log("total drawn this cycle:", newTotal)})// A blocking read on a leased connection, so other commands are not held up.const nextApproval = Effect.scoped( Effect.gen(function*() { const redis = yield* Redis.Redis const connection = yield* redis.reserve // returned to the pool when the scope closes return yield* connection.send<[string, string] | null>("BLPOP", "approvals:pending", "5") }))
redis.subscribe(channel) lives for the current scope and shuts its queue down when that scope closes. Reconnection is host-specific: the Node and Deno subscribers reconnect and re-subscribe after an interruption, so messages published during recovery appear as delivery gaps; the Bun subscriber does not reconnect — a dropped connection fails the dequeue and the caller must subscribe again. Redis pub/sub is fire-and-forget either way, so treat it as a wake-up signal and keep the source of truth in a durable store.
Note:Redis.make creates an internal Cache of loaded script SHAs. The first call to redis.eval(script)(...) issues SCRIPT LOAD and caches the SHA. Subsequent calls use EVALSHA directly. If Redis restarts and loses the script, the module detects the NOSCRIPT error and reloads automatically.
Reach for it when you want Redis backing for any persistence module, or when you need to run Lua scripts with automatic SHA caching and error handling.
Effect's test services make time, console output, randomness, and dependencies deterministic; @effect/vitest integrates those services with a test runner. The repository's documentation tools then compile and validate examples so docs can be treated like code rather than inert prose.
Official companions: Browse the release-matched authored AI documentation source for executable examples across Effect. LLMS.md is its generated single-file aggregate and begins with Effect's coding conventions.
Official guides:Devtools. These track Effect's main branch rather than this edition's audited release, so where they differ, this page and the tagged source win.
Pick the tool by the claim you need to prove. Each row is evidence for one kind of statement and for nothing beyond it; Testing an Effect Application turns the table into a full strategy.
Claim under test
Tool
It does not prove
A delay, timeout, retry spacing, or TTL behaves as specified
A virtual clock that replaces the real clock inside Effect. TestClock.adjust("1 hour") fast-forwards time: every fiber sleeping until that point wakes immediately in scheduled order. Tests that would take minutes in wall time complete in milliseconds.
Mental model. Every fiber calling Effect.sleep (or anything built on it: schedules, retries with backoff, timeouts) suspends and queues itself against a virtual timestamp. TestClock.adjust / TestClock.setTime advances the timeline; all fibers scheduled before the new mark run in order. The live clock is entirely absent.
Tip: Because a sleeping fiber semantically blocks, you must fork the work first, then advance the clock, then join. Advancing after joining a sleeping fiber will deadlock.
@effect/vitest automatically provides TestClock.layer() (plus TestConsole.layer) inside every it.effect block. Use it.live for the real clock.
Semantics worth knowing before a test hangs:
Fact
Consequence
Virtual time starts at 0, the Unix epoch.
Clock.currentTimeMillis and DateTime.now read 1970 until you call setTime; pin the date whenever a calendar rule is under test.
With TestClock.layer, adjust and setTime track a woken fiber's scheduled continuations and child work until it suspends, then inspect the next sleep. Standalone make does not install this tracking scheduler.
Multi-hop sleeps are included in the same advance, but tracking stops after live warningDelay with a busy warning; later sleeps can then register relative to the advanced time. This is not an external-callback or initial-readiness barrier: synchronize on a signal instead of counting turns — see Drive time instead of waiting.
A zero or negative sleep returns immediately.
It never becomes a scheduled wake-up, so there is nothing to adjust past.
A sleep that nobody advances logs a warning after warningDelay of live time (default "1 second").
The message "A test is using time, but is not advancing the test clock" means a missing adjust, not a slow test. It and the busy-fiber warning are written to the live console even while TestConsole captures ordinary output. Tune it with TestClock.layer({ warningDelay }).
Adjustments keep nanosecond precision, including after very large jumps.
Clock.currentTimeNanos is exact: a "365 days" adjust followed by 1.5 ms reads 31536000001500000n.
TestClock.withLive(effect) runs one effect on the real clock.
Use it for a wall-clock guard around a join (Effect.timeoutOption) or for a real fixture's readiness wait inside an otherwise virtual test.
Self-contained source · Type-checked
ts
import { assert, describe, it } from "@effect/vitest"import { Clock, Effect, Fiber, Option, Queue, Ref, Schedule } from "effect"import { TestClock } from "effect/testing"describe("TestClock — vesting & merit-cycle scenarios", () => { // Fast-forward an equity vesting cliff without real waiting. // After a 1-year cliff, all 25% of the first-year tranche should be vested. it.effect("vesting cliff: fiber wakes after 1 year of virtual time", () => Effect.gen(function*() { const vestedRef = yield* Ref.make(0) // Simulates the vesting service checking a cliff after 1 year. const vestingFiber = yield* Effect.forkChild( Effect.sleep("365 days").pipe( Effect.flatMap(() => Ref.set(vestedRef, 1000)), // 1 000 shares vest at cliff Effect.as("cliff-vested") ) ) // No real time passes — jump the virtual clock to just past the cliff. yield* TestClock.adjust("365 days") const result = yield* Fiber.join(vestingFiber) const vested = yield* Ref.get(vestedRef) assert.strictEqual(result, "cliff-vested") assert.strictEqual(vested, 1000) })) // Fast-forward through a merit-cycle retry schedule. // The merit service retries transient HRIS failures with exponential backoff. it.effect("merit-cycle retry: resolves in virtual time without sleeping", () => Effect.gen(function*() { const attempts = yield* Ref.make(0) // Retry up to 8 seconds of cumulative backoff (exponential from 1 s). const policy = Schedule.exponential("1 second").pipe( Schedule.upTo({ duration: "8 seconds" }) ) const fetchMeritBudget = Effect.gen(function*() { const n = yield* Ref.updateAndGet(attempts, (x) => x + 1) if (n < 3) return yield* Effect.fail("HrisUnavailable" as const) return { totalBudget: 500_000, cycleYear: 2025 } }) // Fork so we can drive the virtual clock independently. const fiber = yield* fetchMeritBudget.pipe( Effect.retry(policy), Effect.forkChild ) // Each advance triggers the next scheduled retry attempt. yield* TestClock.adjust("1 second") // attempt 2 yield* TestClock.adjust("2 seconds") // attempt 3 — succeeds const budget = yield* Fiber.join(fiber) assert.strictEqual(budget.totalBudget, 500_000) assert.strictEqual(yield* Ref.get(attempts), 3) })) // Pin the virtual clock to a known review-cycle start date. it.effect("sets absolute timestamp for merit-cycle deadline assertions", () => Effect.gen(function*() { // Pin virtual clock to 1 Jan 2025 00:00:00 UTC for deterministic assertions. const cycleOpen = new Date("2025-01-01T00:00:00Z").getTime() yield* TestClock.setTime(cycleOpen) // Advance 90 days to the Q1 submission deadline. yield* TestClock.adjust("90 days") const deadline = new Date("2025-04-01T00:00:00Z").getTime() assert.strictEqual(yield* Clock.currentTimeMillis, deadline) })) // A timeout is a claim about two instants: not yet at 29 s, fired at 30 s. it.effect("an unanswered HRIS lookup times out at exactly 30 seconds", () => Effect.gen(function*() { const lookup = Effect.never.pipe(Effect.timeoutOption("30 seconds")) const fiber = yield* Effect.forkChild(lookup) yield* TestClock.adjust("29 seconds") assert.isUndefined(fiber.pollUnsafe()) // still running yield* TestClock.adjust("1 second") assert.isTrue(Option.isNone(yield* Fiber.join(fiber))) })) // A recurring job: assert "nothing yet" as well as "exactly one per interval". it.effect("the payroll sync runs at once, then once per hour", () => Effect.gen(function*() { const runs = yield* Queue.unbounded<number>() const fiber = yield* Clock.currentTimeMillis.pipe( Effect.flatMap((startedAt) => Queue.offer(runs, startedAt)), Effect.repeat(Schedule.spaced("1 hour")), Effect.forkChild ) assert.strictEqual(yield* Queue.take(runs), 0) // the take is the handshake yield* TestClock.adjust("59 minutes") assert.isTrue(Option.isNone(yield* Queue.poll(runs))) // not early yield* TestClock.adjust("1 minute") assert.deepStrictEqual(yield* Queue.poll(runs), Option.some(3_600_000)) assert.isTrue(Option.isNone(yield* Queue.poll(runs))) // and only once yield* Fiber.interrupt(fiber) }))})
Make every time test two-sided. Asserting only the state after the adjustment accepts an implementation that fires early; assert the "not yet" instant as well, as the timeout and recurring-job tests do.
effect/testing has no crypto test service. Crypto is a set of family services in effect/crypto — SecureRandom, Digest, Mac, Aead, Signature, and the rest — and a test replaces exactly the ones the code under test requires, with an ordinary Layer.
Migration:effect/Crypto and effect/testing/TestCrypto were removed. Code that called Crypto.randomUUIDv4() now uses SecureRandom.uuidV4(), and crypto.digest("SHA-256", bytes) becomes Digest.digest(Digest.sha256, bytes). Replace TestCrypto.layer(seed) with a SecureRandom built from a seeded byte source (below) or with Layer.mock for the services a test touches. Crypto is no longer part of the runtime *Services bundles, so provide it explicitly in production too (NodeCrypto.layer, or one family layer such as NodeCrypto.layerDigest).
Self-contained source · Type-checked
ts
import { NodeCrypto } from "@effect/platform-node"import { Effect, Layer } from "effect"import { Digest, SecureRandom } from "effect/crypto"// A seeded, NON-cryptographic byte source (xorshift32). Each Layer build restarts the sequence.const seededBytes = (seed: number) => { let state = seed >>> 0 || 1 return (size: number): Uint8Array => { const bytes = new Uint8Array(size) for (let i = 0; i < size; i++) { state ^= state << 13 state ^= state >>> 17 state ^= state << 5 bytes[i] = state & 0xff } return bytes }}// Every SecureRandom operation (bytes, intBetween, shuffle, UUIDs, ULIDs) derives from randomBytes.const SeededRandom = Layer.sync(SecureRandom.SecureRandom, () => SecureRandom.make(seededBytes(42)))// Keep the real digest; replace only the randomness.const TestCryptoLive = Layer.merge(SeededRandom, NodeCrypto.layerDigest)// Or stub a service outright: members you omit die as unimplemented if called.const FixedDigest = Layer.mock(Digest.Digest, { digestHex: () => Effect.succeed("0".repeat(64))})const program = Effect.gen(function*() { const random = yield* SecureRandom.SecureRandom const digest = yield* Digest.Digest const id = yield* random.uuidV4() const bytes = yield* random.uuidV7({ format: "bytes" }) const hash = yield* digest.digestHex(Digest.sha256, bytes) return { id, hash }}).pipe(Effect.provide(TestCryptoLive))const _ = [program, FixedDigest]
SecureRandom.make(randomBytes) must receive a function returning a fresh array of exactly size bytes; values are drawn in evaluation order, so concurrent draws can reorder a seeded sequence. uuidV4 and uuidV7 are functions: call them with () for the lowercase hyphenated string or { format: "bytes" } for 16 bytes. UUIDv7 and ULID also read Clock and are monotonic per SecureRandom instance, so pin virtual time with TestClock (or it.effect) for fully reproducible output. @effect/vitest installs no crypto service; provide one explicitly. Never ship a seeded source, and for non-cryptographic application randomness use Random.withSeed.
A test implementation of the Effect Console service that captures output instead of printing it. All calls through Console.log, Console.error, etc. are recorded in memory for deterministic assertion via TestConsole.logLines and TestConsole.errorLines.
Mental model.logLines / errorLines return a flat array of every argument passed across all calls of that method. Three Console.log calls each passing one value yield a three-element array. it.effect provides TestConsole.layer automatically.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Console, Effect } from "effect"import { TestConsole } from "effect/testing"it.effect("captures comp-service audit logs for assertions", () => Effect.gen(function*() { // Simulate a compensation service emitting structured diagnostics. yield* Console.log("raise applied", { employeeId: "E42", delta: 4200 }) yield* Console.log("budget remaining", { pool: "eng", remaining: 95800 }) yield* Console.error("BandViolation", { employeeId: "E99", requested: 210000 }) // logLines is a flat array of all arguments from every Console.log call. const logs = yield* TestConsole.logLines const errors = yield* TestConsole.errorLines // Two Console.log calls — three arguments total (flat). assert.deepStrictEqual(logs, [ "raise applied", { employeeId: "E42", delta: 4200 }, "budget remaining", { pool: "eng", remaining: 95800 } ]) // One Console.error call — two arguments total (flat). assert.deepStrictEqual(errors, ["BandViolation", { employeeId: "E99", requested: 210000 }]) }))
Note:logLines returns a flat array of all individual arguments from every Console.log call so far. Each positional argument becomes its own element. If you log Console.log("a", "b") and then Console.log("c"), you get ["a", "b", "c"] — not an array-of-arrays.
Warning:TestConsole is the wrong seam for Effect.log*. The default logger prints through the Console service, so under it.effect a call such as Effect.logInfo("raise approved") does land in logLines — as a rendered prefix string such as "[00:00:00.000] INFO (#1):" followed by the message parts and the annotations object. That prefix renders the virtual time in the machine's local time zone and includes a fiber id, so asserting on it is brittle. Capture log records with a test Logger instead; Test logs without scraping stdout shows the helper.
Use when Effect code emits structured diagnostics via Console.* and you want to assert on output without parsing stdout or suppressing CI noise.
Effect's native, Schema-first property-testing engine. It is not a fast-check bridge: effect/testing/FastCheck, Schema.toArbitrary, and the fastCheck options in @effect/vitest do not exist, and the effect package does not depend on fast-check.
Mental model. You do not assemble generators from primitives. You describe the domain once as a Schema and derive the generator from it with Arbitrary.schema(schema); checks such as isBetween and isPattern become constructive constraints rather than rejection filters. Generated values are the schema's decoded Type. The small combinator set — map, filter, filterMap, flatMap (dependent generation), all (tuples, iterables, records), and Constant — composes derived arbitraries without introducing a second catalog of primitive constructors.
Self-contained source · Type-checked
ts
import { Arbitrary, Effect, Schema } from "effect"// Describe a raise recommendation as a Schema; the generator is derived from it.const RaiseRecommendation = Schema.Struct({ employeeId: Schema.NonEmptyString, currentSalary: Schema.Finite.check(Schema.isBetween({ minimum: 50_000, maximum: 300_000 })), raisePercent: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 0.15 }))})const raiseArb = Arbitrary.schema(RaiseRecommendation)// Sampling is an Effect: interruptible, seedable, and bounded.const samples = Arbitrary.sampleEffect(raiseArb, { count: 5, seed: 42 })// Property: the post-raise salary never drops and never exceeds the 15% cap.const check = Arbitrary.checkEffect( raiseArb, ({ currentSalary, raisePercent }) => { const newSalary = currentSalary * (1 + raisePercent) return newSalary >= currentSalary && newSalary <= currentSalary * 1.15 + 1 }, { runs: 200, seed: 42 })// checkEffect does NOT throw on falsification — it returns data to inspect.const report = Effect.gen(function*() { const result = yield* check switch (result._tag) { case "Passed": return `ok after ${result.runs} runs` case "Falsified": // shrunkInput is the smallest failing value found; replay reproduces it exactly. return `failed for ${JSON.stringify(result.shrunkInput)} — replay: ${result.replay}` case "Exhausted": return `too many discards (seed ${result.seed}); loosen the filter or make it constructive` case "ReplayMismatch": return `replay token no longer reproduces: ${result.reason}` }})const _ = [samples, report]
checkEffect accepts a pure predicate or an Effectful property. Returning false and failing the Effect are both shrinkable falsifications (a typed failure is preserved in Falsified.failure); defects and interruption are not converted and continue through the returned Effect. Arbitrary.formatCheckFailure(result) renders a non-passing result for a custom reporter. Everything is bounded: maxDiscards caps rejected candidates (reported as Exhausted, or SampleError when sampling), and maxShrinks caps the shrink search, returning the best input found so far.
Generation is size-scaled. size is a local complexity budget that a check grows toward as runs complete, and at the default an unconstrainedSchema.Int stays within roughly ±100 and an unconstrained Schema.String within about ten characters. Explicit Schema bounds are always honored regardless of size. So if a bug only appears for large values, say so in the schema (isBetween, isMinLength) or raise size — more runs alone will not reach it.
Three rules keep properties trustworthy. Treat generated values as immutable — the runner does not clone them, so mutation corrupts shrinking and replay. Make the property deterministic for a given input, because it may be evaluated repeatedly; a stateful property should acquire and release its own fixture inside each evaluation. And record a failure as an explicit regression test: a replay token reproduces the current failure, but it is an unstable-module artifact that is not guaranteed across upgrades, and it is unrelated to fast-check seeds and paths. Array shrinking drops prefixes and interior blocks while keeping the order of what remains, and composed values keep shrink candidates where possible. BigInt and BigDecimal generation covers a wide range of magnitude, precision, and exponent, with shrinking toward numeric boundaries.
concurrency (a positive integer, default 1) evaluates up to that many generated cases at once. Results are still processed in generation order, so for deterministic generators and independent, repeatable properties the outcome — failure, run and discard counts, shrinks, replay token — does not change with it; later cases may run speculatively and are interrupted before shrinking, which stays sequential, as does replay. Concurrent evaluations share the provided services, so they must not depend on shared mutable state.
Arbitrary.configureGlobal({ check, sample }) replaces the defaults checkEffect and sampleEffect fall back to, for executions that start after the call — set it once, outside any concurrent test, rather than per test. Pass {} to reset it. A replay token always keeps control of its own run regardless of configured defaults.
When a custom Schema.declare/instanceOf type is opaque to derivation, annotate it with toCodecArbitrary (a Schema.link to a generatable representation) — but first check whether it already has a toCodecJson/toCodec, which derivation falls back to automatically. A selective custom filter can contribute an arbitraryConstraint (for example { order: Order.Number, minimum: 0, exclusiveMinimum: true }) so generation constructs valid values instead of discarding invalid ones; the predicate stays authoritative.
import { Arbitrary, Effect, Schema } from "effect"const GrantShares = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 1_000_000 }))// Custom shrinking REPLACES the Schema-derived shrink tree for this arbitrary.const grantShares = Arbitrary.schema(GrantShares, { shrink: (shares) => (shares === 0 ? [] : [Math.floor(shares / 2)])})// Dependent generation: draw a comp band first, then a salary inside that band.const Band = Schema.Struct({ minimum: Schema.Int.check(Schema.isBetween({ minimum: 50_000, maximum: 100_000 })), spread: Schema.Int.check(Schema.isBetween({ minimum: 1_000, maximum: 50_000 }))})const bandAndSalary = Arbitrary.schema(Band).pipe( Arbitrary.flatMap((band) => Arbitrary.schema( Schema.Int.check(Schema.isBetween({ minimum: band.minimum, maximum: band.minimum + band.spread })) ).pipe(Arbitrary.map((salary) => ({ band, salary }))) ))// Wire side. toEncoded keeps only the encoded SHAPE — for FiniteFromString, any string —// so this is a decoder-fuzzing source, not a supply of valid payloads.const SalaryWire = Schema.FiniteFromStringconst fuzzInputs = Arbitrary.sampleEffect( Arbitrary.schema(Schema.toEncoded(SalaryWire)), { count: 20, seed: 1 })// Valid payloads come from encoding generated decoded values.const validPayloads = Arbitrary.sampleEffect(Arbitrary.schema(SalaryWire), { count: 20, seed: 1 }).pipe( Effect.flatMap((salaries) => Effect.forEach(salaries, (salary) => Schema.encodeEffect(SalaryWire)(salary)) ))const _ = [grantShares, bandAndSalary, fuzzInputs, validPayloads]
Reach for a custom shrink only when the derived counterexample is not meaningful in the domain. The callback returns the immediate simplifications of a failing value; every candidate is re-validated against the schema, invalid ones are skipped and still count against maxShrinks, and the function must be synchronous, deterministic, terminating, and free of mutation. It replaces derived shrinking rather than refining it: for the property shares < 1_000 over this schema, the derived shrinker reports the exact boundary 1000, while the halving shrinker above can stop above that boundary; its final value depends on the generated starting value.
Derivation is eager; discards are lazy.Arbitrary.schema throws at the call site when it cannot build a generator — a bare Schema.Never, contradictory bounds such as isBetween({ minimum: 10, maximum: 5 }), a declaration without a generatable representation, or a recursive schema with no finite path. A Never nested where another finite path exists is treated as an uninhabited branch instead of an error: Schema.optionalKey(Schema.Never) leaves the key out, Schema.Union([Schema.Never, S]) generates S, and Schema.Array(Schema.Never) generates []. A generator that can be built but rejects too many candidates fails later, as Exhausted from checkEffect or SampleError from sampleEffect. The first is a schema problem; the second is a filter problem.
size is local, not global. Every unconstrained string, collection, and object property observes the same size independently, so a wide struct still produces a large value at a small size; recursive branches share one recursion allowance.
Sequences of custom values use Arbitrary.array(item, { minLength?, maxLength? }). It shrinks by removing blocks, including prefixes and interior runs, while keeping the order and values of what remains, then shrinks individual elements, which suits command sequences for state-machine properties. Invalid length bounds throw a RangeError at the call. This approval-workflow property is falsified with the minimal history ["Reject", "Approve"]:
A derived arbitrary produces valid decoded Type values. That makes it the right input for invariants and useless for three other claims, each of which needs hand-written cases:
Claim
Why generation cannot show it
What to write instead
Malformed input is rejected with the right issue
every generated value already satisfies the schema
named encoded fixtures: bad brand pattern, impossible timestamp, wrong tag, missing required key
An omitted key takes its decoding default
generated values are decoded, so the key is always present
one encoded fixture per default, asserted with TestSchema.decoding()
A rule spanning several fields holds
the generator only knows what the schema states
put the rule in a schema check, or derive dependent values with Arbitrary.flatMap as above
Record the seed and the shrunk counterexample from any failure, then keep that input as a permanent example-based test: a regression example survives an engine upgrade, a replay token might not. The round-trip law worth asserting for a codec, and why decode(encode(x)) === x is the wrong one, lives in Schema — From External Input to Domain and Back.
Inside @effect/vitest, use it.prop, it.effect.prop, or it.live.prop. Inputs may be Schemas, native Arbitraries, or a mix — they are combined with Arbitrary.all — and non-passing results become test failures that print the shrunk input and replay token:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Schema } from "effect"// Schema-driven property test: any computed raise stays within the comp band.// CompBand: min 80 000, max 200 000. Raise capped at 15%.const SalarySchema = Schema.Finite.check(Schema.isBetween({ minimum: 80_000, maximum: 200_000 }))const RaisePctSchema = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 0.15 }))it.effect.prop( "computed raise always lands within the CompBand", [SalarySchema, RaisePctSchema], ([currentSalary, raisePct]) => Effect.gen(function*() { const newSalary = currentSalary * (1 + raisePct) assert.isTrue(newSalary >= 80_000, "below band minimum") assert.isTrue(newSalary <= 200_000 * 1.15, "above band maximum with raise") }), // Native check options live under `arbitrary` (formerly `fastCheck: { numRuns }`). { arbitrary: { runs: 500, seed: 42 } })// Named-key variant — destructure from an object record.it.effect.prop( "merit increase preserves ordering: higher rating yields higher raise", { base: Schema.Finite.check(Schema.isBetween({ minimum: 50_000, maximum: 150_000 })) }, ({ base }) => Effect.gen(function*() { const meetsRaise = base * 1.03 const exceedsRaise = base * 1.07 assert.isTrue(exceedsRaise > meetsRaise) }))
prop accepts either an array of schemas/arbitraries (positional) or an object record (named destructuring). Prefer a constructive check such as Schema.isBetween over an opaque Schema.makeFilter predicate for generated domains: an opaque filter works, but only as a bounded residual filter that can exhaust its discard budget.
Migrating from the fast-check bridge: replace Schema.toArbitrary(schema)(FastCheck) with Arbitrary.schema(schema); FastCheck.sample with Arbitrary.sampleEffect (numRuns → count); FastCheck.assert(FastCheck.property(...)) with Arbitrary.checkEffect and handle the result (numRuns → runs, path → replay, maxSkipsPerRun → maxDiscards, endOnFailure → maxShrinks: 0); and { fastCheck: { numRuns } } with { arbitrary: { runs } }. Raw fast-check arbitraries are no longer accepted by @effect/vitest. Seeds, distributions, and shrink results are not compatible, so re-record any saved failure. If a test truly needs fast-check, install it yourself and use it directly with Vitest. Effect's release-matched Arbitrary guide goes deeper.
Use when testing pure transformations, codecs, data-structure invariants, or any function where the claim is "this holds for all valid inputs."
Official guide: Schema to Arbitrary (its checkEffect option list is shorter than this module's, which also accepts size, maxDiscards, maxShrinks, and concurrency).
A class-based helper wrapping a Schema with ergonomic methods for asserting decoding, encoding, construction (make), and property-based round-trip verification.
Mental model. Create new TestSchema.Asserts(MySchema) as your test handle. It exposes .decoding(), .encoding(), and .make() — each returning an object with succeed(input, expected?) / fail(input, message) Promise methods, plus succeedEffect / failEffect Effect-returning variants that preserve required decoding or encoding services — all comparing with assert.deepStrictEqual internally. .arbitrary() returns generation-check helpers. verifyRoundTrip() (and its Effect variant verifyRoundTripEffect()) runs a full property-based round-trip, comparing each decoded value with the original through Schema.toEquivalence (custom equivalence annotations included), not structural deep equality.
Self-contained source · Type-checked
ts
import { Schema } from "effect"import { TestSchema } from "effect/testing"// A comp-band salary value: positive number branded as Salary.const Salary = Schema.Finite.pipe( Schema.check(Schema.makeFilter((n: number) => n > 0 ? undefined : "salary must be positive")), Schema.brand("Salary"))// --- decoding a PerformanceRating from a raw string ---const PerformanceRating = Schema.Literals(["exceeds", "meets", "below"])const dec = new TestSchema.Asserts(PerformanceRating).decoding()await dec.succeed("exceeds", "exceeds")await dec.succeed("meets") // identity when expected equals inputawait dec.fail(42, 'Expected "exceeds" | "meets" | "below"')// --- encoding a NumberFromString salary representation ---const SalaryFromString = Schema.FiniteFromStringconst enc = new TestSchema.Asserts(SalaryFromString).encoding()await enc.succeed(95000, "95000")// --- round-trip property test: encode → decode is lossless ---// FiniteFromString alone is not: -0 encodes to "0" and decodes to 0, and the// property check finds it. Salaries are positive, so constrain the domain first.const PositiveSalaryFromString = SalaryFromString.check(Schema.isGreaterThan(0))await new TestSchema.Asserts(PositiveSalaryFromString).verifyRoundTrip()// --- arbitrary generation sanity check ---new TestSchema.Asserts(PerformanceRating).arbitrary().verifyGeneration()// asserts Schema.is(PerformanceRating) for every natively generated value;// both verifiers accept Arbitrary.CheckOptions, e.g. { seed: 1, runs: 20 }
When the schema's decoder requires a service, pass a Context.Key and its implementation to .decoding().provide(key, impl) to inject the service into the decoding context before running assertions.
The static TestSchema.Asserts.ast.fields.equals(a, b) and TestSchema.Asserts.ast.elements.equals(a, b) compare the ASTs of two struct-field records or two tuple-element lists with deepStrictEqual. Use them to prove that a schema-building helper — a field mapper, a pick/omit wrapper, a generated model — yields the same definition as the hand-written schema. The field comparison walks every own key, including symbol and non-enumerable keys, and compares by AST rather than by schema instance: two separately constructed but equivalent field schemas are equal, while differing ASTs or distinct symbol keys are not.
Keep named encoded fixtures beside the generated checks.verifyRoundTrip() and arbitrary() start from valid decoded values; a .decoding().fail(...) case per rejection rule is what proves the decoder says no.
Use when authoring a new schema to pin down exactly what inputs decode or encode to — especially useful for custom transformations and branded types.
The official Effect test runner adapter for Vitest. It requires Vitest 5 (>=5.0.0 <6.0.0), wraps Vitest's it with Effect-aware variants that handle fibers, provides the test environment (TestClock + TestConsole), cleans up scopes, and surfaces failures with pretty-printed Cause traces. It re-exports everything from vitest.
Mental model. A thin Layer between Vitest and Effect tests. Key additions:
it.effect — runs an Effect, provides TestClock + TestConsole, opens a fresh Scope per test.
it.live — same but uses real runtime services (no TestClock substitution).
it.prop / it.effect.prop / it.live.prop — property-based tests driven by the native Arbitrary runner; inputs are Schemas, native Arbitraries, or a mix, with check options under { arbitrary: { runs, seed, … } }.
layer(L) — builds a layer once for a block of tests, sharing state across them, tears down in afterAll; { buildPerTest: true } builds it once per test instead.
beforeAll / beforeEach — Vitest's hooks, re-exported so a callback may return an Effect: it is run with a Scope that closes after the suite (beforeAll) or when the test finishes (beforeEach). The Effect must not require other services.
assert — Vitest's Chai-style assert, re-exported with the rest of vitest (assert.strictEqual, assert.deepStrictEqual, assert.isTrue, …); repo convention prefers this over Vitest's expect.
@effect/vitest/utils — structural helpers built on Node's assert and Effect's Equal: assertEquals (Equal.equals with a diff), assertSome / assertNone, assertSuccess / assertFailure for Result, and assertExitSuccess / assertExitFailure(exit, cause) for Exit.
makeMethods(it) — rebuilds it.effect / it.live / it.prop / layer on top of a Vitest test API extended with fixtures, so fixture values flow into Effect tests too.
Vitest fixtures work with Effect tests via makeMethods. A test receives the fixtures it destructures from its context; Vitest sets them up before the test and tears them down after the test's scope closes:
Self-contained source · Type-checked
ts
import { assert, makeMethods, test } from "@effect/vitest"import { Effect } from "effect"const it = makeMethods( test.extend("config", { scope: "file" }, () => ({ port: 3000 })))it.effect("reads the config fixture", ({ config }) => Effect.sync(() => { assert.strictEqual(config.port, 3000) }))
Vitest parses the destructured parameter names to decide which fixtures to set up, so a test that takes the whole context as one plain parameter ((ctx) => ...) once any fixture is defined fails with a FixtureParseError — destructure the fixture names instead. Property tests (it.prop, it.effect.prop) receive only the base test context and cannot request fixtures, though auto fixtures still run. it.effect.each passes the fixture-bearing context after the test case; named and anonymous it.layer blocks keep the fixtures too.
Runner behavior that affects what a result means:
Behavior
Detail
A failing test logs before it throws.
Each entry of Cause.prettyErrors is written with Effect.logError, then the Exit is rethrown to Vitest. Treat that text as a diagnostic, never as an assertion target.
A Vitest timeout interrupts the fiber.
The test's abort signal is passed to the runner, so the Effect is interrupted, its finalizers run, and the runner waits for them before the test finishes; a defect raised by a finalizer during that cancellation is reported alongside the timeout. A synchronous callback that never returns cannot be preempted.
A synchronous it.prop callback returns a boolean or void.
false (or a throw) falsifies the property; true and undefined pass. Returning an Effect or a Promise is rejected rather than silently passing — use it.effect.prop for Effect callbacks.
it.effect and it.live both open a Scope per test.
Scoped acquisitions made in the body are released when the test ends; wrapping the body in another Effect.scoped changes the lifetime under test.
Returning an Effect from plain it(...) runs nothing.
Vitest receives an object that is not a promise and reports the test green — even for Effect.fail. Always use it.effect; the floatingEffectInVitest diagnostic catches the slip.
Tester modifiers (it.effect.* and it.live.*):
Modifier
Use
Watch for
.each(cases)
one body per case; the case is the first argument, the test context (and any fixtures) is the second
—
.only, .skip
focus or park a test locally
never commit .only
.skipIf(condition), .runIf(condition)
gate on an environment fact
a silently skipped lane is reported green with zero evidence; make required infrastructure fail loudly instead
.fails
passes only when the Effect fails
asserts that it fails, not how; prefer an Exit assertion
it.flakyTest(effect, timeout?)
reruns a scoped Effect up to 10 more times within timeout (default 30 seconds), retrying on any failure including a defect, then dies
it hides nondeterminism instead of removing it; acceptable only for genuine external eventual consistency
Two properties are specific to Effect code and cheap to pin: building a program starts nothing, and its E and R are exactly what the contract says. Value-based tests pass whether or not either holds.
Self-contained source · Type-checked
ts
import { assert, expectTypeOf, it } from "@effect/vitest"import { Context, Effect, Schema } from "effect"class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { employeeId: Schema.String}) {}class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {}) {}class Hris extends Context.Service<Hris, { readonly salaryOf: (employeeId: string) => Effect.Effect<number, HrisUnavailable>}>()("app/Hris") {}const proposeRaise = Effect.fn("proposeRaise")(function*(employeeId: string, amount: number) { const hris = yield* Hris const salary = yield* hris.salaryOf(employeeId) if (amount > salary * 0.15) return yield* new BandViolation({ employeeId }) return salary + amount})// 1. Construction is inert: describing the program must not touch the dependency.it.effect("building a raise proposal performs no lookup", () => Effect.gen(function*() { let lookups = 0 const spy = Hris.of({ salaryOf: () => Effect.sync(() => { lookups++ return 100_000 }) }) const program = proposeRaise("emp-42", 5_000).pipe(Effect.provideService(Hris, spy)) assert.strictEqual(lookups, 0) // described, not started assert.strictEqual(yield* program, 105_000) assert.strictEqual(lookups, 1) // one run, one lookup }))// 2. Static contract: recovery removes ONLY the variant it names, and R is still open.const withFallback = proposeRaise("emp-42", 5_000).pipe( Effect.catchTag("HrisUnavailable", () => Effect.succeed(0)))it("proposeRaise keeps its static contract", () => { expectTypeOf<Effect.Success<typeof withFallback>>().toEqualTypeOf<number>() expectTypeOf<Effect.Error<typeof withFallback>>().toEqualTypeOf<BandViolation>() expectTypeOf<Effect.Services<typeof withFallback>>().toEqualTypeOf<Hris>()})// 3. A negative proof documents a guard rail. Keep it inside a function nobody calls.export const notRunnableYet = () => // @ts-expect-error Hris has not been provided, so the runner must reject the program // @effect-diagnostics-next-line missingEffectContext:off Effect.runPromise(withFallback)
Add the inertness test to every adapter around legacy code. An adapter that calls the Promise-returning function while building the Effect, or a constructor that hides a runner, returns correct values and still starts work too early; only the 0-then-1 counter sees it.
Type assertions are checked by the compiler, not by the runner. Vitest strips types, so expectTypeOf and @ts-expect-error prove something only when the test files belong to a project that CI type-checks (tsc --noEmit, or Vitest's typecheck mode). Effect.Success, Effect.Error, and Effect.Services extract the three channels.
A negative proof needs both suppressions when the language service is on. TypeScript and the missingEffectContext rule each report the unprovided service. @ts-expect-error must come first and the @effect-diagnostics-next-line directive must sit directly above the offending line; in the other order the directive is reported as having no effect.
Assert the inferred type, not an annotated one. An explicit annotation such as const p: Effect.Effect<number, BandViolation, Hris> = … rejects a wider inferred type but silently accepts a narrower one, and a type test written against an annotated value only tests the annotation. Use toEqualTypeOf on the un-annotated expression when exactness matters — for example to show that catchTag was used where a broad Effect.catch would also compile.
Use the top-level layer(L) export (or it.layer(L) for nesting) to build a service once and share it across an entire block. Appropriate for integration tests against stateful services where re-initialization per test would be expensive.
Self-contained source · Type-checked
ts
import { assert, it, layer } from "@effect/vitest"import { Array, Context, Effect, Layer, Ref } from "effect"interface RaiseRecord { readonly employeeId: string; readonly amount: number }class MeritCycle extends Context.Service<MeritCycle, { cycleYear: number }>()("MeritCycle") {}// A minimal in-memory raise-log service for integration tests.class RaiseLog extends Context.Service<RaiseLog, { record(employeeId: string, amount: number): Effect.Effect<RaiseRecord> readonly entries: Effect.Effect<ReadonlyArray<RaiseRecord>>}>()("comp/RaiseLog") { static readonly layerTest = Layer.effect( RaiseLog, Effect.gen(function*() { const store = yield* Ref.make(Array.empty<RaiseRecord>()) return RaiseLog.of({ record: Effect.fn("RaiseLog.record")(function*(employeeId, amount) { const entry: RaiseRecord = { employeeId, amount } yield* Ref.update(store, (xs) => [...xs, entry]) return entry }), entries: Ref.get(store) }) }) )}// One layer instance shared across all tests — torn down in afterAll.layer(RaiseLog.layerTest)("RaiseLog", (it) => { it.effect("starts with an empty audit log", () => Effect.gen(function*() { const log = yield* RaiseLog assert.deepStrictEqual(yield* log.entries, []) })) it.effect("records a raise and accumulates across tests (shared state)", () => Effect.gen(function*() { const log = yield* RaiseLog yield* log.record("E42", 4_200) const entries = yield* log.entries assert.strictEqual(entries.length, 1) const first = entries[0] assert.isDefined(first) assert.strictEqual(first.employeeId, "E42") })) // Nest a second layer that depends on the outer one. it.layer( Layer.effect(MeritCycle, Effect.succeed({ cycleYear: 2025 })) )("nested merit-cycle layer", (it) => { it.effect("has access to both the raise log and the cycle context", () => Effect.gen(function*() { const log = yield* RaiseLog assert.isDefined(log.record) })) })})
Warning: Tests inside a layer(...) block see the same service instance and its accumulated state. This is intentional for integration tests but dangerous if isolation is expected. For isolated state per test, pass { buildPerTest: true }, provide the layer inside each it.effect body with Effect.provide, or use a Ref reset in beforeEach.
layer(L, options?) accepts five options:
Option
Meaning
excludeTestServices
When true, TestClock and TestConsole are not merged into the block: the layer is built, and its tests run, on the live clock and the real console. Default false. Nested it.layer(...) blocks inherit the choice.
timeout
A Duration input applied to the hooks that build and close the layer. Give a real fixture room to start and to shut down.
concurrent
Named blocks only: overrides the enclosing suite's concurrency. An anonymous layer(L)((it) => …) always inherits it. Concurrent tests over one shared Layer need state that tolerates interleaving.
buildPerTest
When true, the layer is built for each test and released when that test finishes, while services from an enclosing layer block stay shared. A build failure fails only that test, blocks nested inside are built per test too, and timeout has no effect (the test's own timeout covers the build).
memoMap
A Layer.MemoMap to share already-built layers between separate layer(...) blocks. A nested it.layer(...) forks the parent's memo map on its own, so outer services are reused, not rebuilt.
Three consequences follow from how the helper is built:
The shared Layer is constructed on the virtual clock. By default layer(L) builds L with the test services provided, so a fixture that sleeps, polls for readiness, or applies an Effect.timeout while it acquires waits on a clock nobody advances, and the block hangs until the hook timeout. A Layer that only allocates in-memory state is unaffected.
The it handed to the block has no live tester. It offers effect, prop, flakyTest, and layer. Choose the clock for the whole block with excludeTestServices, or for one effect with TestClock.withLive.
A shared Layer that fails to build fails the suite, not the tests. The construction error is converted with Effect.orDie inside the block's setup hook; Vitest then reports one failed suite and marks the block's tests as skipped. Read the suite failure — a per-test count alone shows nothing red.
Fragment · Type-checked
ts
import { assert, layer } from "@effect/vitest"import { Context, Effect } from "effect"import type { Layer } from "effect"class PayrollDb extends Context.Service<PayrollDb, { readonly ping: Effect.Effect<"ok">}>()("test/PayrollDb") {}// A real fixture: starts a database, migrates it, and probes readiness with real timeouts.declare const PayrollDbFixture: Layer.Layer<PayrollDb>layer(PayrollDbFixture, { excludeTestServices: true, timeout: "60 seconds" })( "PayrollDb adapter against a real database", (it) => { it.effect("answers a probe within five real seconds", () => Effect.gen(function*() { const db = yield* PayrollDb // No TestClock in this block: the timeout below is wall-clock time. assert.strictEqual(yield* db.ping.pipe(Effect.timeout("5 seconds")), "ok") })) })
Situation
Clock choice
Application delays, retries, TTLs, schedules
default it.effect / layer(L) and TestClock.adjust
A real driver, server, or container inside the shared Layer
layer(L, { excludeTestServices: true })
One wall-clock wait inside an otherwise virtual test
import { assert, it } from "@effect/vitest"import { Effect, Schema } from "effect"// Schemas are converted to native Arbitraries automatically. Constructive checks// such as isBetween generate in-range values directly instead of discarding.// Property: applying a non-negative raise never decreases the salary.it.effect.prop( "applying a merit raise never decreases the salary", [ Schema.Finite.check(Schema.isBetween({ minimum: 50_000, maximum: 250_000 })), Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 0.20 })) ], ([baseSalary, raisePct]) => Effect.gen(function*() { const newSalary = baseSalary * (1 + raisePct) assert.isTrue(newSalary >= baseSalary) }))// Named-key variant — destructure from an object record.it.effect.prop( "bonus calculation is commutative across rating and base", { base: Schema.Finite.check(Schema.isBetween({ minimum: 0, exclusiveMinimum: true, maximum: 200_000 })), factor: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })) }, ({ base, factor }) => Effect.gen(function*() { assert.strictEqual(base * factor, factor * base) }))
Use for all Effect tests. Start with it.effect, graduate to layer(...) when integration state needs sharing, and use it.effect.prop whenever the claim is "this holds for all inputs."
Several modules ship their own test harness. Each removes one piece of infrastructure and keeps the rest of the pipeline real, which defines exactly what a green result covers.
one entity's handlers behind an in-memory RPC client
the cluster transport
routing across runners. It honors the entity layer's disableFatalDefects option: with that option set, a handler defect fails only its own call instead of every pending call on the client
durability across a restart, backend-specific limits
ConfigProvider.fromUnknown(...) via ConfigProvider.layer
Config parsing, defaults, redaction
environment variables
that the deployed environment sets those names
Classify a test by the boundary it crosses, not by the technology it mentions. Calling an HttpApi handler through HttpApiTest is a service test even though it says "HTTP"; an in-memory KeyValueStore test says nothing about Redis.
@effect/tsgo — external package (Effect-TS/tsgo), versioned separately from effect; this handbook validates with 0.70.0
A build of TypeScript-Go with the Effect language service embedded. It reports Effect-specific mistakes — a floating Effect, an unprovided requirement, error handling on an Effect that cannot fail, two copies of effect in one program — as diagnostics, and offers quick fixes and refactors for them. The same rules run in the editor, in tsc, and in a dedicated CLI, which is what makes them usable in CI and by coding agents: the feedback arrives before any test runs.
Mental model. The rules live in the compiler, not in a lint plugin bolted on afterwards. You register one tsconfig.json plugin entry (its name is @effect/language-service, for every front end), and then choose where the diagnostics surface.
sh
# Guided setup: adds the dependency, the tsconfig plugin entry, and editor hintsnpx @effect/tsgo setup# Non-interactive flags, for scripts and coding agentsnpx @effect/tsgo setup --help
@effect/tsgo needs a native TypeScript 7 install beside it (typescript 7, or an alias such as @typescript/native). The plugin entry looks like this — the three tsc options are the ones this handbook's validation project sets, and diagnosticSeverity is the per-rule knob:
make the editor use effect-tsgo as its TypeScript language server
Use it instead of plain tsgo, not beside it — two servers duplicate diagnostics and slow the editor. Adds quick fixes, hovers, and refactors such as asyncAwaitToGen and layerMagic.
tsc
effect-tsgo patch, usually from a prepare script
Patches the installed native TypeScript so ordinary tsc runs emit Effect diagnostics as TypeScript diagnostics. An unpatchedtsc stays silent about them. Exit-code impact is set by ignoreEffectSuggestionsInTscExitCode (default true), ignoreEffectWarningsInTscExitCode (false), and ignoreEffectErrorsInTscExitCode (false).
Dedicated CLI
effect-tsgo diagnostics --project tsconfig.json --strict --format text
Needs no patch. --strict makes emitted warnings fail the command; it does not enable disabled rules or change severities. --format is json, pretty, text, or github-actions; --file checks one file. This is the command that validates every example in this handbook.
Oxlint
effect-tsgo patch --oxlint
Experimental type-aware lint integration; this also patches TypeScript by default (--no-typescript opts out). Presets ship under @effect/tsgo/oxlint-presets: recommended, strict, correctness, antipattern, effect-native, style, and opt-in maintainers. Use compatible Oxlint/tsgolint versions from the release README.
The application-facing groups below cover correctness, anti-pattern, Effect-native, and style; maintainer rules are separately opt-in. Many rules are not errors until you raise them — most style and Effect-native rules default to suggestion or off, and effect-tsgo config opens an interactive configuration editor. The ones below map directly onto failures described elsewhere in this handbook:
an Effect that is built and dropped; a plain Vitest callback returning an Effect that never runs; leftover R or E at a boundary; yield without *; two Effect versions in one program; an API that no longer exists; a cast that narrows E or R
chained Effect.provide; interdependent layers passed to Layer.mergeAll; the global Error in E; recovery that can never run; an interior runner; try/catch around yield*; an implementation service leaking through a service method
ambient Date.now(), setTimeout, Math.random(), fetch, process.env, and console inside Effect code — exactly the dependencies TestClock, Random, HttpClient, Config, and TestConsole exist to control. Turn these on for application code that must be deterministic under test.
simplifications with a mechanical fix; opt-in reports of Effect.all / Effect.forEach calls without a concurrency option (which run sequentially) and of for loops that push yield* results into an array
Severity is per rule: diagnosticSeverity maps a rule name to "off", "suggestion", "message", "warning", or "error"; overrides applies different levels to file globs; and an @effect-diagnostics or @effect-diagnostics-next-line comment adjusts one file or one line. effect-tsgo config opens an interactive rule picker for an existing tsconfig.json. One rule deserves a project-level decision up front: unstableApiUsage warns on every API tagged @stability unstable, including effect/http, effect/sql, effect/rpc, effect/ai, and the other unstable area families. A project that builds on those modules sets "diagnosticSeverity": { "unstableApiUsage": "off" } (this handbook's validation does exactly that); a library that wants to stay inside the semver-covered surface leaves it on.
Run the diagnostics on test code too.floatingEffectInVitest is the static counterpart of the false green described under @effect/vitest: it("…", () => Effect.fail("boom")) passes at runtime and fails this check.
Pin it like any other toolchain dependency. Each release is built against specific TypeScript (and Oxlint) versions listed in its README; upgrade it together with TypeScript rather than independently.
Link out for option tables. The tool evolves faster than effect itself; the complete rule list and option reference live in its repository README, and Getting Started covers the project setup around it.
Development tooling. The packages/tools/ directory mixes public documentation/code-generation packages with private utilities used to maintain the Effect monorepo. The public tools in the audited release are @effect/openapi-generator, @effect/graphql-generator, @effect/docgen, and @effect/doctest; the rest of the list below is repository-internal.
An opinionated documentation generator (Node 22.19.0 or later) for Effect-style TypeScript libraries. The docgen CLI reads source modules and JSDoc, enforces configurable description/example/@since policies, typechecks and runs @example blocks, and emits Markdown/site material. It is zero-config by default (src → docs) or configured with docgen.json and its bundled schema.json.
Install with pnpm add -D @effect/docgen and run docgen. Supported documentation controls include @category, @example, @since, @deprecated, @internal, and @ignore; parser/example compiler options can point at strict project configs.
A Vitest/Vite integration that extracts marked TypeScript examples from JSDoc, Markdown, and MDX and runs every fence as an isolated test module. Mark a fence ts import.meta.vitest; an optional name="..." labels it. Trailing // => expectedExpression assertions use Effect's Equal.equals semantics.
Self-contained source · Runtime assertion
ts
import { Effect } from "effect"Effect.runSync(Effect.succeed(42)) // => 42
Fragment · Type-checked with fixture
ts
import * as Doctest from "@effect/doctest/Plugin"import { defineConfig } from "vitest/config"export default defineConfig({ plugins: [Doctest.plugin()], test: { include: ["test/**/*.test.ts"], includeSource: ["src/**/*.ts", "docs/**/*.{md,mdx}"] }})
The assertion transform handles a complete expression statement or a single initialized const; it does not implicitly await promises, run Effects, or consume iterators. Do those operations explicitly. @effect/doctest requires Vitest 5 and Vite 8.1.5+.
Other repository tools.
@effect/openapi-generator — Public tool. Given an OpenAPI spec file, generates Effect Schema type definitions, typed HTTP clients, or full HttpApi module skeletons. CLI: openapigen --spec api.yaml. Accepts JSON Patch files to pre-process the spec before generation; reports warnings to stderr. Output goes to stdout.
@effect/ai-codegen — Code-generation framework used internally to produce AI provider bindings (OpenAI, Anthropic, etc.) inside packages/ai. Wraps @effect/openapi-generator with provider-specific discovery, patching, and post-processing. Not intended for external use. CLI: effect-ai-codegen.
@effect/ai-docgen — Repository-internal compiler that combines the authored, ordered ai-docs/src directory tree into the aggregate LLMS.md document. It reads each directory's index.md, extracts title/description metadata from numbered TypeScript examples, skips fixtures, recurses into topic folders, and supports watch mode. CLI: effect-ai-docgen ai-docs/src -o LLMS.md.
@effect/jsdocs — JSDoc extraction and analysis toolkit. Parses Effect source files with the TypeScript compiler, validates JSDoc blocks against Effect house style (required tags, example shape, @since, etc.), emits structured JSDocResult objects. Used by CI to enforce documentation quality. CLI: effect-jsdocs.
@effect/bundle — Bundle-size testing infrastructure. Provides CLI commands for building fixture packages with Rollup, measuring tree-shaken output sizes, and comparing against a reporter. Prevents accidental bundle size regressions when publishing new Effect versions. CLI: effect-bundle.
Takeaway: Application tests usually start with @effect/vitest and the test services. Library authors add @effect/docgen and @effect/doctest when examples are part of the contract; the OpenAPI, AI, JSDoc, and bundle tools are specialized repository and code-generation infrastructure.
This page is the short retrieval layer for the handbook: one representative service, then a task-to-module map. Use search or the sidebar for the complete module treatment.
import { Context, Effect, Layer, Schema } from "effect"// 1. Errors are tagged schema classes.class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { reason: Schema.String}) {}// 2. Services are classes; the implementation is a static Layer.class CompService extends Context.Service<CompService, { readonly applyRaise: (employeeId: string, pct: number) => Effect.Effect<number, BandViolation>}>()("comp/CompService") { static layer = Layer.effect(CompService, Effect.gen(function*() { return CompService.of({ applyRaise: Effect.fn("CompService.applyRaise")(function*(employeeId, pct) { if (pct > 0.2) return yield* new BandViolation({ reason: "raise exceeds band max" }) return pct }) }) }))}// 3. Compose with gen; handle errors by tag; run at the edge.const program = Effect.gen(function*() { const comp = yield* CompService return yield* comp.applyRaise("emp_42", 0.08)}).pipe( Effect.catchTag("BandViolation", (e) => Effect.logError(e.reason).pipe(Effect.as(0))), Effect.provide(CompService.layer))
Note:Four habits the codebase enforces: use Effect.gen/Effect.fn (never async/await or try/catch inside them); use Clock/DateTime (never Date.now); write callbacks as lambdas — Effect.forEach(ids, (id) => loadBand(id)), not Effect.forEach(ids, loadBand), because forEach also passes the index and point-free passing can erase overloads and generics; and reach for an existing module before hand-rolling — there's almost certainly one for your problem.
The companion Choosing Effect Primitives page is the contrastive layer: it compares error channels, required services, ownership, backpressure, durability, distribution, and the situations where each plausible choice is wrong.
Decision
Detailed comparison
Where a fact may be collapsed: absence, failure, unknown, requirements, execution, lifetime
Tip: Most of what you import from "effect" is @stability stable and covered by semver. Exceptions such as Arbitrary, FileSystem, Path, ExecutionPlan, LayerMap, Graph, and ByteSize, plus advanced Schema APIs, carry explicit stability labels. Most subsystem APIs under "effect/<area>" are unstable and may change in minor releases; GraphQL, host/DNS resolution, and UDP APIs are experimental and may change in patches. See Stability and support for the distinctions. Pin exact versions, read the changelog, and keep each unstable or experimental import behind one app-owned capability.
This page is the reading protocol for coding agents and the tools that drive them. It says which generated artifact to fetch for which task, how to stay in Markdown instead of HTML, what the structured catalogs mean, how to cite a section, and what to do when the handbook does not answer. Humans are welcome too, but every rule below is written so an agent can follow it without judgment calls.
Every page of this site exists twice at the same path: the rendered HTML route and a Markdown twin with .md appended. /data/schema is a web page; /data/schema.md is the same content as plain Markdown. The landing page / is /index.md, and a section landing such as /deep-dives/ is /deep-dives/index.md.
Always request the twin:
It is one third the size of the rendered HTML and contains nothing but the page.
Its headings carry the same anchors as the HTML, so /data/schema.md#schemaissue and /data/schema#schemaissue name the same section.
Every internal link inside a twin already points at another twin, so following links never lands you on HTML.
The first line is an HTML comment naming the page, the audited Effect release, and the three agent entry points (llms.txt, the module index, and this guide). Treat it as provenance; nothing else is injected.
The HTML pages advertise the same thing for crawlers: each one carries <link rel="alternate" type="text/markdown"> to its twin and <link rel="describedby"> to llms.txt, and robots.txt repeats the entry points. If you are reading HTML, you have taken a wrong turn — append .md and fetch again.
Long twins (eight or more top-level sections) open with a generated Contents line listing every section with its anchor, so you can decide what to read before reading it.
Match the edition to the installed Effect version
The handbook is published as editions, one per Effect major.minor, each audited against one exact release. The site root always serves the newest edition; every edition, including the newest, is also served under its own path — /4.0/, /4.1/, /5.0/ — with the same relative layout, so /4.0/data/schema.md and /5.0/data/schema.md are the same page for different Effect versions.
Before reading anything else:
Read the installed version from node_modules/effect/package.json.
Take its major.minor and fetch that edition's llms.txt, for example /4.0/llms.txt for effect@4.0.3.
If that path is missing, fetch /versions.json at the site root. It lists every published edition with its effectVersion, audit date, status (latest or frozen), and the URLs of its llms.txt, module index, and catalog. Use the highest listed edition below yours within the same major; editions of different majors describe different libraries and are never interchangeable.
State the edition and audited release you used when you answer.
Upgrading, or reading code written against an older pin? Read the Release History entries above that version: each one lists what changed in Effect and links the section that now owns it.
Every edition's llms.txt opens with its own edition and release and has an Editions section linking to the others, so you can correct course from any entry point. A frozen edition is rebuilt from its git tag, never edited, so what you read there will not change under you; the HTML pages of a frozen edition show a banner pointing at the newest handbook, but the Markdown twins do not.
Start at llms.txt. It is a few thousand words, lists every page and bundle with its current word count, and maps common intents to the exact section that answers them. From there, pick by task:
Task
Fetch
Why
Get oriented, or plan work that spans several areas
effect-4-essentials.md
Every concise page and section in about a sixth of the full handbook: purpose, stability, and when to reach for it, each linking to the full section. Read it first, then fetch only the sections you need.
"Which primitive do I use for X?"
llms.txt → the Intent and primitive map, then the linked section
One hop to the canonical paragraph, with alternatives listed next to it.
Contrastive tables by error channel, lifetime, backpressure, durability, and distribution.
Look up one module by name
effect-4-modules.md (or .json)
Alphabetical and per-area list of every module section with import path, stability badge, and twin anchor.
Work inside one subsystem for a while
The matching domain bundle effect-4-{core,web,concurrency,distributed,ai}.md
All pages that subsystem needs, pre-concatenated, with cross-links already rewritten to twins.
Review or generate code across the whole library
effect-4-handbook.md (identical to llms-full.txt)
Every concise page in full, in reading order, plus compact deep-dive summaries. Large (about 300K tokens); use it only when the task genuinely needs every rule at once — otherwise start from the essentials.
Program against the handbook (tooling, RAG, evaluation)
Symptom → cause → fix tables, searchable by the exact diagnostic text.
Produce a complete program
A page under recipes/
Each recipe is a single runnable file that the harness executes with asserted output.
Understand how pieces compose into an application
A page under deep-dives/
Long-form; excluded from the aggregate and bundles on purpose. Fetch one only when the task needs the connected tutorial.
Budget roughly 1.3 tokens per word for prose pages and more for code-heavy pages; llms.txt gives the word counts so you can choose before fetching. Prefer one page over one bundle, the essentials over a bundle when you need breadth, and anything over the aggregate.
effect-4-catalog.json is the structured form of the handbook's selection guidance. Each entry in capabilities describes one thing an agent might reach for:
Field
Meaning
id
Stable identifier such as effect.program or ai.mcp-approval. Cite it in tooling; it does not change when prose moves.
kind
decision (choose between alternatives), module (one module's main job), or recipe (a complete program).
domain
The bundle family the entry belongs to; domains at the top of the file spells each one out.
symbols, imports
The exact exported names and the subpath to import them from. Root modules are also re-exported from the "effect" barrel.
stability
stable, unstable, or experimental — the module's @stability contract at the audited release.
tasks
Natural-language aliases for the intent. Match the user's words against these before matching symbol names.
summary, chooseWhen, avoidWhen, alternatives
The selection boundary, with alternatives naming other capability ids to compare against.
errorChannel, requirements, lifetime, platform
What lands in E, what R demands, how the value is scoped or cancelled, and whether it is portable or host-specific.
since
availableBy records the audited release in which the capability is known to exist. It does not claim the historical introduction release.
page, anchor
The canonical section. Fetch page with .md and jump to #anchor.
snippetIds
Ids into the top-level snippets array of runnable examples; empty means the entry points only at its reference section.
The handbook object at the top of every JSON artifact records the Effect version, tag, commit, and audit date the data was generated against. Check it before trusting cached copies.
effect-4-examples.json lists every fenced TypeScript example in the handbook with its source, heading, line range, sha256, sourceForm, and disposition. Source form answers what you must supply:
self-contained — no declared application values, local imports, or contextual fixture. This is complete source, not a guarantee of a runnable application: dependencies, host APIs, configuration, or external services may still be needed, and defining an Effect does not execute it.
fragment — supply the declared application values, local modules, or named fixture before using it.
illustrative — pseudocode or an intentional type error.
The rendered site and offline handbook show this source form above each TypeScript fence alongside its independent validation contract:
compile — must pass isolated strict TypeScript and strict Effect diagnostics; ambient declarations can still stand in for application values.
contextual — the exact fence passes the same checks inside one named tracked fixture (fixture), which supplies surrounding declarations the fence refers to. Expect to add those declarations yourself.
run — compiled and executed by the harness with an asserted result (runtimeCheckId). Recipes are run examples.
pseudocode — visibly labelled architectural sketches; never paste them as code.
invalid — intentionally wrong code that must produce one precise TypeScript diagnostic, shown to teach what the compiler rejects.
The inventory declares the checks each example must pass; it does not embed pass/fail results. Validation evidence is regenerated by the repository's pnpm docs:examples gate on every change.
Cite a section as its Markdown twin URL plus anchor, for example /foundations/core-runtime-execution.md#effect. Anchors are derived from the heading text — lower-case, with runs of non-alphanumeric characters replaced by a single hyphen — and a heading that repeats on one page gets a -1, -2 suffix in document order. The module index and the catalog already contain the correct anchors, so copy from them rather than slugifying by hand.
When quoting a code fence, quote the whole fence. The examples are validated as units; a trimmed fragment may drop the import or the type annotation that made it compile.
State the audited release when a claim could change between versions. Read the exact release and audit date from the header line of the fetched twin or from handbookRelease inside the JSON artifacts; do not infer a patch version from the edition URL.
The handbook covers the public surface of effect and the @effect/* packages at one audited release, with one representative example per module rather than a complete API reference. When it does not answer:
The installed package is the ground truth.node_modules/effect/AGENTS.md carries the maintainers' coding conventions and node_modules/effect/ai-docs/src their topic-organized examples; both match the version actually installed. Prefer them over any copy of the documentation that may describe a different version, this one included.
Read the declaration files. Every public module is a single .d.ts under node_modules/effect/dist/ (or the package's dist/), with JSDoc that includes the @stability tag and usually an example. For @effect/* packages the same applies under their own dist/.
Check stability before relying on it.unstable APIs may gain features in a patch release and break in a minor release; experimental ones may break in a patch release. The badges on this site were derived from the audited source, not from the import path, since Effect 4 has no unstable/ path segment.
Report drift. If the installed source contradicts the handbook, the handbook is wrong or stale. The twin header tells you the release it was audited against.
Paste this block into the project's AGENTS.md, CLAUDE.md, or equivalent and replace the host with the site you are reading. Everything it says is enforceable with a plain HTTP client.
md
## Effect 4 referenceUse the Effect 4 Handbook at https://HOST/ for Effect questions. Rules:1. Fetch Markdown, never HTML: append `.md` to any page path (`/` is `/index.md`).2. Use the edition for the installed version: read `node_modules/effect/package.json`, take `major.minor`, and prefix every path with it (`https://HOST/4.0/llms.txt` for effect 4.0.x). https://HOST/versions.json lists the published editions; never use an edition from a different major.3. Start at that edition's `llms.txt`. Use its "Intent and primitive map" to find the exact section; use its `effect-4-modules.md` when you already know the module name. Take page URLs from those lists — never guess a path.4. For breadth, read `effect-4-essentials.md` (every page and section in brief, each linked to the full text); otherwise fetch one page or one domain bundle (`effect-4-core.md`, `-web`, `-concurrency`, `-distributed`, `-ai`). Fetch the full `effect-4-handbook.md` only when the task needs every rule at once.5. Before writing code, check the "Effect 3 names that do not exist in Effect 4" list at the top of `llms.txt` (for example `Effect.catchAll` is `Effect.catch`, `Layer.scoped` is `Layer.effect`, and there is no `@effect/platform`).6. Prefer `sourceForm: "self-contained"` examples from the edition's `effect-4-examples.json` when you need complete source, and `run` recipes when you need asserted behavior. `compile` alone does not mean runnable; supply application values for fragments. Treat pseudocode as sketches and invalid examples as counter-examples.7. The installed `effect` package (`node_modules/effect/AGENTS.md`, `ai-docs/src`, and the `.d.ts` files) wins over the handbook when they disagree.8. Cite sections as `<edition>/<twin path>#<anchor>` and name the audited release from the twin's first line.
The repository also ships the same protocol as an installable skill at .agents/skills/use-effect-4-handbook/SKILL.md, for agent frameworks that load skills from a directory.
All of these are produced from the Markdown under docs/ by the repository build and published at the site root. None is edited by hand.
Artifact
Contents
llms.txt
The routing index: entry points, domain bundles with word counts, the intent and primitive map, and every page with its description and size.
llms-full.txt
Byte-identical to effect-4-handbook.md, published under the name the llms.txt convention expects.
effect-4-handbook.md
Every concise page in reading order plus compact deep-dive architecture summaries.
effect-4-{core,web,concurrency,distributed,ai}.md
Focused bundles; every capability-owning page appears in at least one.
effect-4-modules.md / .json
Every module section with import path, stability, page, and anchor.
effect-4-catalog.json
The capability catalog described above.
effect-4-examples.json
The example inventory described above.
<page>.md
The Markdown twin of each page, with header, optional contents line, and links rewritten to twins.
effect-4-handbook.html
A self-contained offline copy of the whole site for humans; agents should not fetch it.
versions.json
Every published edition — id, exact Effect version, audit date, latest or frozen, and the URLs of its llms.txt, module index, and catalog. Served at the site root and inside every edition.
robots.txt, sitemap.xml
Crawl policy pointing at the entry points above; the sitemap is emitted for production builds with a public URL.
This page records how the handbook has evolved: one entry per audited Effect release, newest first. Each entry names the release the handbook was audited against, the changes in Effect that a reader of the previous entry needs to know about, and what changed in the handbook itself.
It is a curated reader's changelog, not a copy of Effect's. Entries keep only what changes how you write or operate Effect code: behavior, types, stability, renamed options, span and metric names, and new public surfaces. Fixes that only made the implementation match what the handbook already described are left out. The per-package CHANGELOG.md files in the Effect repository stay the authoritative record of every change.
Reading it when you upgrade. Find the entry for the version you are pinned to, then read every entry above it. Each entry's items link to the handbook section that now owns the topic. Read that section rather than the summary line. Editions are published per major.minor (see Match the edition to the installed Effect version); a patch release updates its edition in place and gets its own entry here.
Edition 4.1 (patch update; full source audit). Tag effect@4.1.4, commit 289a53f7, published 2026-11-11. Baseline: effect@4.1.0, the previous full source audit. Range reviewed: every package changelog entry and all 253 commits covering published 4.1.1, 4.1.2, 4.1.3, and 4.1.4, which the 4.1.1–4.1.3 entries below recorded only as dependency refreshes. npm omits gitHead; the tarball integrity and npm provenance (build commit 289a53f7) match the release tag.
No existing module changed its module-level @stability. New modules and packages:
unstable: root Rational; effect/encodingJson5 and Jsonc; the new effect/jose family (Jwk, Jws, Jwe, Jwt, Jwks, JoseError); effect/rpc/OpenRpc; effect/cli/CommandSpec; effect/cluster/MessageRetention; effect/ai/WorkloadIdentity with provider modules in @effect/ai-anthropic, @effect/ai-openai, and @effect/ai-openrouter; the @effect/ai-amazon-bedrock package;
stable: Runtime.InterruptExitCode;
experimental: effect/aiAgUi, AgUiSchema, and AgUiServer; the @effect/platform-cloudflare package.
Upstream also clarified the contract: unstable APIs may gain features in a patch release. See Stability and support.
JOSE: algorithm-bound JSON Web Keys, compact JWS and JWE, schema-typed JWTs, and local or remote JWKS resolution with algorithm allow-lists (#9883). See JOSE: tokens and keys.
Exact fractions:Rational, with Schema.Rational, Schema.RationalFromString, and SchemaRepresentation.RationalReviver (#9990). See Rational.
Configuration formats:Json5.parse and Jsonc.parse return Result<unknown, EncodingError> (#9972). See Json5 and Jsonc.
OpenRPC:OpenRpc.fromRpcGroup generates an OpenRPC document from an RPC group (#10173). See OpenRpc.
CLI documentation specs:CommandSpec projects a command path into plain data, and Flag.annotate, Argument.annotate, and Param.annotate attach metadata (#10377). See CommandSpec.
Cloudflare cluster:@effect/platform-cloudflare runs cluster entities, workflows, durable queues, and singletons on Durable Objects, with optional Alchemy deployment (#7322). See Running on Cloudflare Durable Objects.
Message retention:MessageRetention.make deletes a persisted entity's completed requests after a retention age; custom MessageStorage drivers must implement deleteProcessed (#10267). See MessageRetention.
AI providers and protocols:@effect/ai-amazon-bedrock signs Converse requests with SigV4 or a Bedrock API key (#9980); WorkloadIdentity exchanges platform identity tokens for short-lived provider tokens (#10512, #10482); AG-UI serves an agent to frontends with client-executed tools (#9842). See Provider packages, WorkloadIdentity, and AgUiServer.
Telemetry names and wire-visible behavior
Span status:OtlpTracer and OtelTracer leave a successful span's status Unset instead of OK (#10440). Migration: rules matching status = OK must match status != ERROR. See What ends up on a span.
MCP spans:McpServer spans follow the OpenTelemetry MCP conventions ({method} {target} with mcp.* and gen_ai.* attributes) and continue a client's traceparent; tool spans no longer record arguments unless Toolkit.RecordToolArguments is set (#10304). See Tracing.
SQL transaction spans:BEGIN, COMMIT, ROLLBACK, savepoints, and connection waits are child spans of sql.transaction, replacing the effect.sql.transaction.* span events (#10213). See Transactions.
OTLP: metrics without a unit export an empty unit instead of "1" (#10385); idle log and trace exporters no longer keep a Node process alive (#10235). See OtlpMetrics and OtlpExporter.
Span redaction:HttpApi.RedactedNames declares query and header names to redact in client and server spans (#9995), and HttpClientError URLs use the redaction names active when the error is created (#10006). See HttpApi and HttpClientError.
JSON codecs at tool and stream boundaries: tool results, declared MCP tool failures, and HttpApiSchema.StreamSse data are encoded with their schema's JSON codec, so a Tool.dynamic tool without a success schema must return JSON (#10362, #10243, #10148). See Failure results and their wire format and HttpApiSchema.
SSE framing:Sse.encoder strips CR and LF from id and event and NUL from id (#10182). See Sse.
Exit codes:Runtime.InterruptExitCode lets a deliberate interruption choose its exit code instead of 130; RPC and MCP stdio servers now exit 0 after stdin closes (#10475). See Runtime.
Bun and Deno: servers answer 503 instead of 404 while no app is served (#10289), and enforce MaxBodySize on buffered reads (#10192). See Own the listener.
Behavior, types, and security
HTTP client:HttpClient.timeout fails a request that receives no response in time with a retryable TransportError (#10207); HttpClient.withScope now owns every request sent during the execution, including redirects, retries, and middleware requests (#10363). See Retries, time budgets, and cancellation and Response lifetimes and withScope.
HTTP server shutdown: a transferred request scope closes only after both the request and its body finish (#10366); Node closes WebSockets with code 1001 at shutdown and destroys connections left at the graceful timeout (#10405, #10360, #10300). See HttpEffect.
SQL transactions: a statement or nested transaction run from a fiber that outlives its transaction now fails instead of using the transaction's connection (#10433, #10434). See Transactions.
SQL driver types: driver clients extend SqlClient.Base instead of SqlClient, and providing a generic SqlClient layer no longer removes a driver service from requirements (#10387, #10403). Migration: provide the driver layer itself where a driver service is required. See The driver packages.
PostgreSQL values: an unregistered value that cannot be decoded fails only that query, naming the column (#10422). See Native client behavior.
Event log authentication: the server verifies the session signature before binding a signing key; authorizeIdentity receives signingPublicKey (#10185, #10211). See EventLogServerUnencrypted.
Resource limit: BigDecimal parsing rejects scales outside ±10,000, and scale alignment beyond 20,000 throws RangeError (#10188). See BigDecimal.
Ref equality: the identity Equal for Ref and MutableRef was reverted, so distinct refs with equal contents are Equal (#10247). See Ref.
Workflows and cluster:ClusterWorkflowEngine retries transient storage failures instead of recording defects, an interrupted child wakes its parent, and a runner that lost its shard cannot delete newer activity results (#10206, #10260, #10311, #10356, #10146, #10226); entity defect backoff is per entity (#10261). See ClusterWorkflowEngine and Entity.
Persistence:PersistedQueueoffer accepts deduplicate: "untilExecuted" (#10316); RateLimiter limits of 0 or less admit nothing and Redis keys are isolated (#10103, #10210); CircuitBreaker.execute gains onRejection and classifiers receive { probe } (#10142, #10169); the redis peer minimum is 5.1.0 (#10153). See PersistedQueue, RateLimiter, and CircuitBreaker.
RPC: handlers may fail with their server middleware's errors (#10418); discarded calls fail promptly on transport errors, and a custom client Protocol must reply to every accepted request (#10121, #10171). See RpcGroup and RpcClient.
AI and MCP:generateObject accepts allowEmpty (#10527); MCP Skills are served on every supported protocol revision (#10082, #10540); McpClient gains capabilities, discovery limits, and toolkit options (#10049). See LanguageModel, Skills, and McpClient.
CLI:Command.validate can fail with your own errors, which Command.run reports like handler failures (#10376). See Validating input across flags.
Schema: fields named after Object.prototype members match only own properties (#9612); isAnyOf accepts only union tags (#10355); SchemaBinary adds fixed-width integers and rejects non-numbers in number arrays (#10230, #10288); JSON Schema import adds experimental closeObjects (#10521). See Structs, SchemaBinary, and JsonSchema.
Time zones: named zones keep the supplied identifier, aliases included (#10439). See Time zones.
Completed the 4.1.0 → 4.1.4 source audit of every canonical page and deep dive; public-module and package coverage deficits are zero.
Added module sections for Rational, Json5, Jsonc, the six JOSE modules, OpenRpc, CommandSpec, MessageRetention, WorkloadIdentity, AgUiSchema, AgUi, and AgUiServer, plus entries for @effect/ai-amazon-bedrock and @effect/platform-cloudflare.
Corrected the Ref/MutableRef equality claims, the success span status, the HTTP server claim that every handler is interrupted on disconnect (apps run uninterruptibly unless they opt in), the withCookiesRef type, the redis and React scheduler peer ranges, the PostgreSQL unregistered-value behavior, and the OpenAiStructuredOutput scope.
Added migration notes for silently ignored v3 Schema concurrency, batching, and parseOptions annotations; withScope ownership; RPC middleware errors; MCP span names; and tool spans.
Added catalog capabilities and retrieval cases for exact fractions, JSON5/JSONC, exit codes, JOSE, message retention, Cloudflare clusters, AG-UI, and workload identity.
Updated @effect/tsgo from 0.67.7 to 0.70.0 and Vitest from 5.0.5 to 5.1.1, added the Bedrock and Cloudflare packages to the validation workspace, and repinned release-matched upstream links to effect@4.1.4.
This entry records a dependency and example-validation refresh, not a complete release-delta or source audit. Consult the upstream changelog for changes since 4.1.2; coverage of newly added APIs remains outside this update.
Tool-call JSON boundary: unresolved user-tool parameters are now typed Schema.Json, and Toolkit.handle decodes their JSON codec rather than the schema's ordinary encoded form (#10332). Decode Schema.toCodecJson(tool.parametersSchema) before typed policy checks, but pass the original JSON to handle. See Tool-call resolution and Mutation gates.
Updated effect and every pinned release-train @effect/* dependency from 4.1.2 to 4.1.3, including doctest, platform, SQL, AI, React, GraphQL, telemetry, and Vitest integrations.
Updated the separately versioned @effect/tsgo compiler tooling from 0.63.0 to 0.67.7; retained strict diagnostics and the existing advisory unstableApiUsage exception.
Repaired both application-gate examples to decode JSON before authorization and idempotency checks, without casting away the new parameter type.
Updated central release metadata, runtime-probe provenance, reproducible installation pins, exact release-age exclusions, and the workspace lockfile. The previous full source audit remains the baseline; see Version and validation scope.
This entry records a dependency-only refresh, not a complete release-delta or source audit. Consult the upstream changelog for changes since 4.1.0; coverage of newly added APIs remains outside this update.
Updated the validation package's effect and matching @effect/* dependencies to 4.1.2, with exact release-age exclusions and a regenerated workspace lockfile.
Kept @effect/tsgo at 0.63.0 and its existing diagnostic configuration unchanged. The full example suite is validated against the updated runtime packages.
Updated central release metadata and reproducible installation pins. The previous full source audit remains the baseline; see Version and validation scope.
Edition 4.1 (new edition; the 4.0 edition is frozen at effect@4.0.5). Tag effect@4.1.0, commit 9a91b192, published 2026-10-29. Baseline: effect@4.0.5 (published 2026-10-15). Range reviewed: all package changelogs, changesets, and 579 commits covering published 4.0.6, 4.0.7, and 4.1.0. npm omits gitHead; the package integrity, provenance, and published source were checked against the release tag.
Deep imports of nested internal modules are blocked by the package exports map (#9326). Migration: import only public entry points. See Getting Started.
Migration:effect/Crypto and effect/testing/TestCrypto are removed in favour of effect/crypto/*: SecureRandom, Digest, Aead, Cipher, Mac, Signature, Kdf, KeyAgreement, KeyWrap, KeyFormat, CryptoError, WebCrypto (#9126). This also supersedes the 4.0.5 TestCrypto and randomUUIDv4() notes.
Crypto is no longer bundled in the *Services layers. Provide NodeCrypto/BunCrypto/DenoCrypto/BrowserCrypto.layer (or a per-family layer*), or a core layerWebCrypto.
Tests use Layer.mock.
SqlMessageStorage, SingleRunner and encrypted event-log server storage now require Digest.Digest.
Persisted workflow IDs, idempotency keys and event-log encodings are unchanged.
Defects take precedence in mixed causes. Typed recovery (catch, catchTag, error-mapping recovery, retry) skips a cause that contains a defect and turns every typed error in it into a defect; error mapping maps every typed error in place (#9516, #9433). Use catchCause or catchDefect to handle such causes. See Recovery and mixed causes, Typed recovery and mixed causes.
Composed layers are memoized by identity again, as in v3. A composed layer shared by several parents is built once per MemoMap, including any Layer.fresh dependencies inside it (#9634). Wrap the composed layer itself in Layer.fresh for a separate copy. See What is shared and what is rebuilt.
Ref and MutableRef compare by reference (#9768). ArrayBuffers compare and hash by bytes (#9769). Migration:Exit.hasFails/hasDies/hasInterrupts and AsyncResult.isInterrupted are no longer type guards; narrow with Exit.isFailure (#9799). See Ref, Exit.
New small runtime APIs:
Effect.ignore({ log: "Unhandled" }) and its Stream/Channel variants (#9510);
Release failures nobody observes (RcMap/RcRef idle expiry, ScopedCache scans) are logged at UnhandledLogLevel (#9388). See Semaphore, RcMap.
Schedule.fibonacci now repeats the initial delay (100, 100, 200, 300 ms…), so later retries come sooner (#9917). Cron/Schedule.cron gain onDstOverlap for repeated local times (#9905). Duration gains formatIso/fromIso (exact units only) and toMicros (#9891, #9973). See Cron, Duration.
Upstream stream failures in Stream.run, peel and aggregate* bypass Sink.mapError/catch*/orElse and reach the caller unchanged (#9803). See Sink.
HTTP, HttpApi, and platform hosts
Migration:HttpMiddleware.xForwardedHeaders is now a function taking { trustedProxies } (an IpNetwork list), and applies X-Forwarded-* only from trusted peers. HttpServerRequest.toURL uses the new request.protocol, and the peer is request.peerAddress (#9701). Node originalUrl is absolute when a Host header is present; read paths from url (#9415). See HttpMiddleware.
Request data leaks less:
HttpClientErrortoJSON shows only the method and redacted URL (#9855);
HttpServerError messages carry only the path (#10011);
AWS SigV4 query parameters are redacted by default (#9903).
Migration:AiError.HttpRequestDetails and Response.HttpRequestDetails are removed, and NetworkError exposes method and url instead of request (#10010). See HttpClientError, AiError.
Migration:HttpClient.withCookiesRef takes a Ref<ReadonlyArray<Cookie>> (not Ref<Cookies>) and sends cookies only to the matching host, path and scheme. Seed it with Cookies.mergeIntoArray (#9614). Migration: received request methods are typed string; exhaustive switches need a default or HttpMethod.isHttpMethod (#8766). See HttpClient.
Headers gains typed HTTP-date and Retry-After parsing, with matching Schema codecs. Invalid or fractional Retry-After values are now ignored by retryTransient/withRateLimiter (#9709). Other additions:
FetchHttpClient fails with EncodeError on runtimes without streaming request bodies unless StreamBodyFallback is "buffer" (#9567). See HttpClient.
Raw HTTP/1.1 upgrades (HttpClientRequest.upgrade, HttpApiSchema.Upgrade) arrive. Custom HttpClientResponse implementations must add upgrade (#9339). Upgrade endpoints can declare 101 headers and buffered payloads, and can sit alongside ordinary success responses (#9751, #9945). Migration: hand-built HttpApiClient.Upgraded mocks need the UpgradedTypeId brand; narrow with HttpApiClient.isUpgraded. See Upgrades.
New HttpApi features:
streaming request payloads via StreamUint8Array/StreamNdjson, with maxBytes limits and HttpApiPayloadTooLarge (413) (#9575);
opt-in RFC 9457 Problem Details via HttpApiError.Problem and HttpApiMiddleware.layerProblemDetails (#9706);
Migration (deployment):@effect/platform-node, platform-node-shared, opentelemetry and docgen require Node ≥ 22.19.0 (#10084), and @effect/platform-deno requires Deno ≥ 2.9.3 (#9702).
Node WebSocket clients use the global WebSocket. ws moves to the new NodeWS module: replace NodeSocket.NodeWS and layerWebSocketConstructorWS with NodeWS.WebSocket and NodeWS.layerWebSocketConstructor, which also keeps backpressure and custom headers.
Migration (custom implementations):FileSystem.make inputs must provide lstat and readDirectoryEntries, and glob is now derived (#6428, #9438). Terminal.make inputs must provide size, a resize queue (#9639). FileSystem.glob is experimental, uses / separators, and no longer expands Node extglobs. See FileSystem, Glob, Terminal.
Migration: a single-valued CLI flag given twice now fails; use Flag.atLeast/atMost/between (#9872). -num=3 lexes as short flags; use --num=3 (#9287). New CLI APIs:
Command.validate (#9655) and Flag.withNegation (#9650);
CliOutput.Presenter (#6743) and TerminalCapabilities, which honours FORCE_COLOR/TERM=dumb (#8350);
Completions.fromCommand (#9976) and the CliError.userMessage annotation (#8349).
Help shows an INHERITED FLAGS section, and custom formatters must read HelpDoc.inheritedFlags (#9276). See CliOutput, TerminalCapabilities.
SQL, persistence, event log, cluster, and RPC
Migration:sql.insert and sql.updateValues require a non-empty array at the type level (#9453). The updateValues alias is escaped as an identifier, so pass it bare (#9759). fromFileSystem moves to effect/sql/MigratorFileSystem; adapter *Migrator modules still re-export it (#9157).
Migrations fail with a typed MigrationError (#9598).
Third-party drivers must set SqlClient.make({ driver }) (#9222).
New: SqlClient.afterCommit and BeginTransaction (#9289, #9576); sql.in([]) now compiles to an always-false (IN) or always-true (NOT IN) predicate (#9758); PostgreSQL acquireTimeout, onAcquire and poolStats (#9641, #9738, #9090).
Migration (persistence):Persistence on KeyValueStore now keys entries <storeId>:<key>, so every existing layerKvs entry becomes unreachable, including Chat.layerPersisted histories. Redis is affected only for store ids containing % or : (#9223).
Custom KeyValueStore.make stores must implement keys, and prefix(...) scopes size/isEmpty/clear (#9844).
The Redis PersistedQueue lock format changed: drain old workers and let their locks expire before starting upgraded ones (#9229).
Redis.make requires connect, and Redis.reserve leases dedicated connections for blocking commands (#9828).
Migration (wire): event-log writes are now acknowledged instead of echoed, and encrypted replication batches entries (#9477, #9479). Upgrade clients and servers together, and start encrypted servers on fresh storage. EncryptedEntry is now EncryptedBatch, and custom journals must add entriesById/writeRemoteAcks. SQL and IndexedDB journals migrate on first open (#9482). New: encrypted remote compaction (#9571), EventRow (#9523), EventLog.writeMany (#9452). See EventLogRemote, EventRow.
In calculateNextRunFromPrevious mode, ClusterCron runs through one executor entity per job. Read the scheduled time from ClusterCron.CurrentScheduledTime, not Entity.CurrentAddress; a failing run now blocks later runs while it retries (#9677).
Frozen runners lose PostgreSQL/MySQL shard locks after shardLockExpiration (#10037, #10093).
ShardingConfig.runnerJoinDebounce batches handoffs during surge deploys (#10073).
New ClusterMetrics series: shardReleaseDuration, shardsReleasing, entityMailboxSize[Max] (#9256, #9513, #9578, #9572).
Migration (wire): RPC calls with discard: true complete when the server acknowledges them. The SchemaBinary envelope fingerprint changed, so upgrade those peers together (#9182). The RPC NDJSON content type is application/x-ndjson; existing RPC HTTP peers stay compatible (#9562). New: RpcServeronDisconnect (#9688) and opt-in HTTP request batching (#9656). With disableFatalDefects, a synchronous handler throw fails only its own request (#9899). See RpcSerialization.
AI and MCP
Migration:DecideOptions.images is removed. Declare Decision.Image fields in the input schema; the new Decision.locate returns bounding boxes, and exhaustive switches need Locate cases (#9177). DecisionModel.decideSettled keeps valid answers alongside per-decision failures (#9437).
Migration: the new non-retryable AiError.InvalidResponseError needs a case in exhaustive AiErrorReason matches (#9430).
NetworkError.cause keeps the HttpClientError (#9984).
Migration: pass McpServer registration layers through the transport's registrations option, and capture construction-time services with Layer.unwrap (#9154). Unmet per-request services surface as McpRequest<"Requires", S> (#9856). New: McpServer.visibility (#9661), cacheHints (#9939), the in-memory McpTest.makeClient (#9657), and the experimental McpClient (#8862). See McpServer, McpClient.
Migration: the regenerated Anthropic Generated bindings move Files and Skills to their GA shapes (*Resource types, next_page paging). Remove the dated files-api/skills beta tokens from anthropic-beta.
The OpenRouter provider name is "openrouter".
OpenRouter defaults to strict schemas for OpenAI-family models.
Migration: drop explicit output type arguments from Schema.TaggedUnion.match/matchOrElse (#10061). Schema.Record rejects optional index-signature values; use Schema.UndefinedOr (#9864). Checks keep httpApiStatus annotations (#9775). New Schema APIs: crypto key schemas, isAscii, DurationFromIsoString, DateTimeUtcFromHttpDate, and the unstable toCodecGoJson (#9245). See Schema unions and records.
Migration:Toml.parse returns a Result with an EncodingError instead of throwing (#9537). Base64Url.decode rejects partial padding (#10076), and Yaml.parse supports << merge keys (#10051). NdjsonError gains a reason (#9575). Libraries exporting generic Data.taggedEnums now emit declarations that need effect ≥ 4.0.7 (#9834). See Toml, Yaml.
Migration: import NodeSdk/WebSdk from @effect/opentelemetry/NodeSdk and /WebSdk; the package root no longer re-exports them (#9689). Other telemetry changes:
OTEL_RESOURCE_ATTRIBUTES is percent-decoded and trimmed (#9997).
Calls on ended spans are ignored, so spans are not exported twice (#9815).
traceparent/b3 parsing rejects uppercase hex and malformed flags (#10086, #10085).
The new OtlpProxy forwards browser telemetry without exposing credentials (#9829).
Atoms gain skipInitialRun for hydrated or seeded atoms (#9522) and opt-in typed Reactivity.Keys (#9560). Atom.Serializable encodes to Schema.Json (#8763). See Hydration.
@effect/vitest changes:
beforeAll/beforeEach run returned Effects with a scope (#9675);
layer(..., { buildPerTest }) rebuilds selected services for each test (#9832);
Migration:it.prop rejects Effect/Promise returns; use it.effect.prop (#9384).
Started the 4.1 edition. The 4.0 edition is frozen at effect@4.0.5 (tag effect-4.0.5/2026-10-22) and stays published under /4.0/.
Added a Cryptography chapter covering every effect/crypto module, the host crypto layers, testing, and a migration table from Crypto.*. The site now has 66 pages: 53 concise pages and 13 deep-dive pages including their landing page.
Added module sections for Bytes, SemVer, SemVerRange, TextDiff, Glob, CommandLine, Csv, JsonArray, Tar, Xml, Zip, ProblemDetails, MigratorFileSystem, OtlpProxy, EventRow, CircuitBreaker, UserDirectories, TerminalCapabilities, McpClient, McpClientError, and McpTest. Every public module in the root barrel and the 22 effect/<area> families now has a concise heading.
Rewrote mixed-cause recovery across the foundations, the failure deep dive, troubleshooting, the decision guide, and review checklists to the defect-first rule. Corrected PersistedCache's handling of undecodable entries, CliError.DuplicateOption, Node's oversized-body response, sql.in([]), the claim that runtime aggregates include crypto, workflow compensation under layerMemory, and hydration ordering.
Added persistence, wire, and deployment migration warnings for store key layouts, Redis queue locks, RPC discard, event-log replication, forwarded headers, and minimum Node/Deno versions. Added capability routes and retrieval cases for cryptography, circuit breaking, MCP clients, and streaming archive codecs.
Repinned the validation workspace to 4.1.0 and @effect/tsgo 0.63.0. Updated the TOML probe to the Result contract, and turned the NodeSdk example into an isolated compile example.
Edition 4.0 (updated in place). Tag effect@4.0.5, commit 7f524e25, published 2026-10-15. Baseline: effect@4.0.2 (published 2026-10-07). Range reviewed: all package changelogs, changesets, and 191 commits covering published 4.0.3, 4.0.4, and 4.0.5. npm omits gitHead; the package integrity, provenance, and published source were checked against the release tag.
Experimental effect/graphql adds seven modules for typed client operations, middleware, HTTP/SSE and WebSocket subscriptions, partial results, pagination, and batching (#8979). It is not a GraphQL server executor. @effect/graphql-generator generates operations from documents and SDL/introspection schemas; 4.0.5 emits Struct schemas with named interfaces for ordinary object selections/inputs (#9171). HTTP endpoints can be resolved per request, with resolver batches partitioned by URL (#9150); identity-aware batchKeys are still required.
Experimental Host, Dns, and AddressResolver add host parsing, DNS queries, and endpoint resolution, with Node/Bun/Deno services (#8880). TLSA records and input constructors follow (#8953, #8970, #8973); host-file parsing and relative/FQDN conversion are available (#8992). DatagramSocket adds experimental UDP on those hosts (#8409). Experimental APIs may change in a patch release; see Stability and support.
TestCrypto.layer (removed in 4.1.0; see Deterministic crypto in tests) seeds random operations while delegating digests to the underlying platform Crypto (#8487). Migration:Crypto.randomUUIDv4 and randomUUIDv7 are now functions: call () for strings or ({ format: "bytes" }) for bytes (#8935).
Effect.Transaction exposes attempt number, retry reason, and timing metadata from inside a transaction body (#8166).
HTTP, platform boundaries, and SQL
HTTP spans, request inspection, and errors redact sensitive query values and URL credentials without changing the wire request. Migration: signed-URL names move from Headers.CurrentRedactedNames to UrlParams.CurrentRedactedNames; custom name lists replace defaults (#9136). UrlParams also accepts Redacted values, widening its public parameter and iterator types (#9160). See HTTP Client.
FileSystem.File.Info uses bigint for dev and Option<bigint> for ino, rdev, nlink, and blocks; account for this in serialization (#9112). File opens accept noFollow on supported POSIX hosts, and reads/writes accept explicit positions (#8900). Path.resolveWithin rejects rooted paths and lexical traversal escapes; it does not prevent symlink escapes (#9127).
WebSocket clients on Node/Bun accept handshake headers (#8978); TLS upgrades accept an explicit servername (#9010). See Sockets. Stdio.stderrIsTerminal detects stderr separately (#8938); Esc now cancels default Node/Bun/Deno terminal input unless shouldQuit overrides it (#8934).
SQL COMMIT failures propagate as typed SqlError when cleanup succeeds; failed cleanup preserves both failures as defects (#8892). Single-connection clients exclude competing statements for the whole statement/stream lifetime (#8927). PostgreSQL adds TCP keepAlive (#9120). See SQL.
RPC socket clients expose onPingTimeout, distinct from other disconnects (#8976); response-encoding failures reach ErrorReporter (#8943). See RPC.
MCP, AI, and durable execution
McpServer.layerHttpRequestScoped owns all server work within each POST for serverless hosts. It accepts only stateless adapters and has no sessions, subscriptions, or session termination (#9031). Long-lived layerHttp gains allowSubscriptions: false (#8924). Resource-template and prompt-completion schema services now appear in Layer requirements, so previously incomplete compositions can fail type checking (#9151, #9135).
With manual tool resolution, toolCallValidation: "deferred" returns model-generated calls with unknown parameters and possibly undeclared names. Strict validation remains the default; validate before authorizing or dispatching (#9008).
Decisions accept structured descriptions and score legends. Migration:Rate.criteria entries are { label, description } objects, not strings (#9124). OpenAI adds a Decisions provider; OpenAI-compatible response augmentation moves to the openai-compat metadata key (#9140). Regenerated OpenAI bindings also change public provider types (#9067); review the provider migration notes.
OpenAI treats unknown model names as reasoning models by default; set reasoningModel: false for custom non-reasoning names (#8980). OpenAI-compatible configuration removes unsupported store and conversation fields (#9011); provider-specific tool-call fields survive replay (#8916). See Provider packages.
Cluster SQL storage separates owner-connection migrations from application storage Layers (#8897). InterruptOnTermination opts RPCs into early entity interruption (#8963); shutdown hands shards off individually with bounded waits (#8941). Transactional replies publish only after commit or clean rollback, with local replies recoverable from storage (#8891, #9176). See Cluster.
Telemetry, data, time, and tooling
Cluster entity RPC spans now use only the entity type in their names; entity.id remains an attribute (#9094). Update name-based dashboards. See ClusterMetrics.
Built-in OTLP exporters accept opt-in gzip configuration, including per-signal environment overrides (#9139). Subsequent delta histograms omit cumulative extrema (#8987); 64-bit trace IDs are padded to 128 bits (#9117). OTel log records carry the active Effect span context (#9125). See Telemetry Export.
JSON Schema output for Schema.Int includes safe-integer bounds, and colliding bounds compact to the tighter one (#8956, #9081). Refresh snapshots rather than removing those constraints. SchemaError serializes compactly (#8895); tagged unions reject duplicate discriminator keys at compile time (#9103). StructWithRest accepts optional fields (#9020); see Schema unions and records.
Zoned DateTime.add/subtract apply hours and smaller units as elapsed time across DST; calendar units remain wall-clock operations (#9048). Duration conversions handle very large milliseconds and nanosecond scaling without the earlier precision/overflow failures (#9109, #9161, #8972). See Time.
TestClock.adjust/setTime track woken fibers across yields and child joins, so newly registered sleeps within the target interval are not skipped (#9172). Establish initial readiness explicitly; virtual time is not a general startup barrier.
Sse can dispatch empty named events for protocols such as GraphQL SSE (#8979); its encoder handles CR/CRLF data lines (#9096). Async-iterator stream timeouts stop even when next() never settles (#9106).
Match narrows only a matched array prefix and rejects unknown object-pattern keys (#9088, #9098). Mutable Array.match callbacks retain mutable non-empty array types (#9055).
The CLI gains Flag.withOptionalValue for --flag[=VALUE] (#9145), PowerShell completions (#8904), and CliOutput.displayWidth (#8982). Prompts honor NO_COLOR and acquire stdin only when needed (#8933, #8932).
Added GraphQL as a concise chapter, and topic-sized sections for DNS/host resolution, UDP, TestCrypto, transaction metadata, request-scoped MCP, and new operational options. The site now has 65 pages: 52 concise pages and 13 deep-dive pages including their landing page.
Removed redundant current-release numbers and audit dates from chapter prose. Chapters inherit the edition audit target; exact versions remain in release metadata, generated headers, reproducible installs, source links, and migration boundaries. The refresh skill preserves this policy.
Updated deep dives, the decision guide, cheat sheet, troubleshooting, review checklists, capability routes, and retrieval cases with the new selection boundaries. Experimental APIs are labelled separately from unstable ones.
Corrected stale claims about TestClock wakeups, mixed-cause retry, DecisionModel.Image.mediaType, workflow finalizer lifetime, and OTLP JSON spelling; pinned current source links and recipe installs to 4.0.5.
Corrected group-level Config defaults and secret-log safety, queue shutdown producer outcomes, semaphore fairness, stream batch timing, SQL commit-error routing, and ManagedRuntime cleanup ordering. Removed a transactional queue termination race and clarified Schema length bounds, codec widening, structural equality, and decimal rounding.
Repinned the tracked validation workspace to 4.0.5, TypeScript 7.0.2, @effect/tsgo 0.56.0, and Vitest 5.0.5. Added semantic probes for multi-hop virtual time, path traversal boundaries, and query-redaction override behavior; updated integer-schema expectations to the published contract.
Edition 4.0 (updated in place). Tag effect@4.0.2, commit 269a7c86, published 2026-10-07. Baseline: effect@4.0.0. Range reviewed: every 4.0.1 and 4.0.2 changelog entry across all packages.
Every module and directly importable export now carries an explicit @stability tag (#8770). Nineteen modules the handbook had badged stable are tagged unstable: FileSystem, Path, Terminal, Stdio, Crypto, PlatformError, ExecutionPlan, ErrorReporter, LayerMap, LayerRef, Graph, HashRing, ByteSize, Newtype, PartitionedSemaphore, TxChunk, ChannelSchema, TestConsole, and TestSchema (that last badge was already wrong in the 4.0.0 edition). No API is tagged experimental. See Stability and support.
Runtime, errors, and caching
Effect.retry no longer retries a cause that contains a defect or an interruption, even alongside a typed failure the policy would accept (#8799). See Failure, Retry, Fallback, and Interruption.
When an uninterruptible region fails while an interruption is pending, recovery handlers are skipped and the typed failure is dropped; the fiber exits interrupted, keeping any defects (#8652). See Fiber.
Config.orElse recovers only a pure ConfigError; a cause that mixes it with a defect or interruption propagates (#8808). See Configuration & Secrets.
Effect.cached, cachedWithTTL, cachedInvalidateWithTTL, and Cache treat interruption as abandonment: an interrupted computation is never cached, and it is interrupted only once every waiting caller has gone (#8719). cachedInvalidateWithTTL accepts a TTL computed from the Exit (#8734). See Caching & Batching.
Streams and STM
Stream.scan emits its seed for an empty stream (#8704). groupedWithin, aggregateWithin, and aggregate pause their schedule while idle (#8718). groupBy and partition substreams shut down their queue when the consumer stops early (#8857). See Streaming & Channels.
Waiting on TxSemaphore and TxReentrantLock is interruptible (#8805); PubSub rejects NaN and fractional capacities (#8790).
Telemetry names (update dashboards and alerts)
Interrupt-only spans end with status Unset and effect.fiber.interrupted: true instead of Ok (#8864).
OtlpMetrics exports a summary as one OTLP Summary metric named by its id instead of <id>_quantiles / _count / _sum (#8869).
With @effect/opentelemetry, a span without an Effect parent inherits the active OpenTelemetry span (#8586). See Observability.
SQL statement spans are named by db.namespace, server.address[:server.port], or db.system.name (falling back to sql.execute), record effect.sql.method, and transactions emit effect.sql.transaction.* events (#8866). See SQL.
RPC spans are named by the method tag with no default prefix and record rpc.system.name and rpc.method; pass spanPrefix to keep the old names (#8867). See RPC.
HTTP server spans capture no request or response headers unless HttpMiddleware.TracerHeaderFilter opts them in (#8873). See HTTP Server.
GenAI telemetry follows the current OpenTelemetry conventions: addGenAIAnnotations takes provider: { name } (the system option is removed), and Anthropic usage includes cached tokens (#8870). See AI & Language Models.
Interfaces and AI
HttpApi answers a response-encoding failure with 500 and reports it to ErrorReporter; request-decoding failures stay 400 and unreported (#8834). See HttpApi.
RPC socket clients accept pingInterval and pingTimeout (#8825).
Corrected every claim the delta made false (above), flipped the nineteen stability badges, and rewrote the stability tables in Orientation and Getting Started.
Replaced the dead Official Effect → Cookbooks navigation link: the tagged source has no cookbooks/ folder, and the only upstream cookbook is published as the official v4 Schedule cookbook.
pnpm docs:links now also checks the navigation menu, the VitePress config and theme, the README, and the agent skills, and names where each failing URL is linked from.
The recommended tsconfig.json targets ES2025 (with a matching lib), and the validation project compiles every example with that target.
Added six diagrams (fiber and Scope ownership, Layer build and teardown, Cause classification, stream demand and buffering, the durability ladder, and the HttpApi request lifecycle), each with alt text and a caption that carries its meaning in the Markdown twins.
Added effect-4-essentials.md: a generated digest of every concise page and section (about a sixth of the full aggregate), now the default broad read in llms.txt and the agent guide.
Examples are now executed, not only type-checked: 533 of 612 compile examples run to completion, pass under Vitest, or start as servers, and printed values with expected-output comments are asserted. This found and fixed three examples that failed when run: the ExecutionPlan example (it called Effect.runSync on a plan whose retry schedule is asynchronous), a TestSchema failure message, and a verifyRoundTrip example on Schema.FiniteFromString that fails for -0. New behavior probes back thirteen prose claims about caching, queues, scopes, Layers, fibers, races, retries, streams, and Config.
Telemetry Export now warns that importing from the @effect/opentelemetry root loads every module and needs every OpenTelemetry peer installed; import the one module you use by path otherwise.
Ran an end-to-end evaluation with ten coding agents against the live site (evals/agent-runs/2026-10-09/): all reached a relevant page and five of nine wrote code that passes strict TypeScript and Effect diagnostics and runs. The failures came from Effect 3 names, so llms.txt, the essentials digest, and Generated-Code Anti-Patterns now list the Effect 3 names that do not exist in Effect 4.
Added this Release History page; pnpm docs:check requires an entry for every audited release.
Validation: 714 fences, all passing strict TypeScript 7 and strict Effect diagnostics; new runtime probes for Stream.scan on empty streams, Effect.retry with defect causes, and pending interruption over a failed uninterruptible region.
Edition 4.0 (first edition). Tag effect@4.0.0, commit 67ba4e46, published 2026-10-01: the first stable release of Effect 4 and the baseline for every later entry.
Long-form guides build a working mental model across related Effect APIs. They complement the concise, module-by-module handbook chapters and include larger examples, operational guidance, and design tradeoffs.
Reactivity — From Atoms to Mastery — follow Reactivity, Atom, AtomRegistry, AsyncResult (including combined stale values), AtomRef, hydration, and React integration from the dependency graph through a complete Todos feature. It assumes the Effect/Layer basics and is designed for application developers building reactive clients or SSR UI.
Adopting Effect in an Existing TypeScript Codebase — audit a Promise-based service, pin its behavior with characterization tests, migrate leaf-first behind an unchanged contract, and keep exactly one seam where Promise meets Effect.
Anatomy of a Real Effect Application — compose domain schemas, errors, services, Layers, configuration, resources, observability, an entrypoint, shutdown, and tests into one application.
Owning Lifetimes — Startup, Readiness, and Shutdown — give every resource and fiber one owner, treat startup as a transaction, separate liveness from readiness and draining, shut down through one path, and bridge into non-Effect hosts without leaking work.
Schema — From External Input to Domain and Back — follow encoded input through decoding, domain modeling, transformations, HTTP/RPC/SQL/persistence boundaries, evolution, and property tests.
Testing an Effect Application — validate services, Layers, typed failures, virtual time, resources, fibers, HTTP boundaries, and integration seams without global mocks.
The Durability and Distribution Ladder — choose deliberately among Persistence, EventLog, Workflow, and Cluster, including delayed independent jobs, detached children, and explicit failure recovery.
Building a Production AI Capability — compose provider-neutral models, Schema-backed outputs and tools, strict or deferred validation boundaries, resilience, telemetry, testing, and MCP exposure.
Exposing an Effect Application over MCP — serve an existing Toolkit to AI clients over stdio and Streamable HTTP, distinguish long-lived dual-era from request-scoped stateless hosting, shape the catalog, authorize as an OAuth resource server, run human-in-the-loop round trips, and test the server in-process.
For quick lookup rather than a connected walkthrough, use the concise handbook, primitive chooser, and topic reference pages.
The concise topics remain the module-by-module lookup surface. Deep dives connect several modules into one mental model, retain the operational gotchas needed by the larger example, and link back to the concise reference for exhaustive API inventory. Authoring instructions live in the repository README.
A source-grounded tour of Effect 4's reactive state layer — the same primitives that power TanStack-Query-style data fetching, SSR hydration, and fine-grained UI state, but built natively on Effects, Streams, Layers, scopes, and typed errors.
The reactivity APIs are tagged @stability unstable, so pin compatible package versions and re-audit before upgrading.
For a compact module-by-module API reference, use the Reactivity & Atom handbook topic. This deep dive repeats only the details needed to connect those modules into an application-level mental model.
Before any API: hold two worlds in your head. You already live in the first one.
① Effect world — Pure descriptions: Effect, Stream, Layer. Nothing runs until executed. You write these already.
② Atom graph — A lazy dependency graph of reactive values. An Atom describes how to produce/refresh one cell of state.
③ Registry — The live runtime. AtomRegistry runs atom reads, memoises values, tracks deps, runs Effects, and disposes the unused.
④ View — Framework bindings subscribe to atoms in a registry: React hooks, Solid accessors, and Vue composables. SSR state crosses the boundary through Hydration.
Reactive state libraries you know — Jotai, Recoil, Zustand, TanStack Query — solve "derive values, cache async data, re-render on change." Effect 4's core reactivity modules put those graph and data-fetching primitives beside Effect and Stream, while satellite packages bind them to React, Solid, and Vue. Nodes can therefore inherit structured concurrency, interruption, typed errors, retries, and Layer-provided dependencies inside the state graph.
// These six foundational namespaces are under the core package. The same// barrel also exports AtomHttpApi and AtomRpc integrations.import { Atom, AtomRef, AtomRegistry, AsyncResult, Reactivity, Hydration,} from "effect/reactivity"// The React bindings ("AtomReact") are a sibling package:import { RegistryProvider, useAtom, useAtomValue, useAtomSet, useAtomSuspense, HydrationBoundary,} from "@effect/atom-react"
Caution: These modules are tagged @stability unstable and can change between releases. This guide describes the audited target above.
Takeaway: An Atom is a value, not a hook. Define atoms once at module scope. They are inert descriptions; a Registry brings them to life. This separation is what makes them testable, server-renderable, and shareable across frameworks.
Start at the bottom. Reactivity is a tiny service that does one thing: connect writes to dependent reads by key. It stores no values itself — it just remembers "who cares about key K" and fires them when K is invalidated.
Everything key-reactive in this layer bottoms out here: atoms that auto-refresh on a mutation, SQL queries that refetch after an insert, and typed-client invalidation. Ordinary writable/derived atom dependencies are tracked separately by AtomRegistry's graph.
import type { Effect, Queue, Scope, Stream } from "effect"// Reactivity is a Context.Service. Its methods (paraphrased):interface ReactivityService { // imperative register/fire (no Effect, no scope): registerUnsafe(keys: Keys, handler: () => void): () => void // returns unregister invalidateUnsafe(keys: Keys): void // effectful equivalents: invalidate(keys: Keys): Effect.Effect<void> mutation<A, E, R>(keys: Keys, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> // invalidate AFTER success query<A, E, R>(keys: Keys, effect: Effect.Effect<A, E, R>): Effect.Effect<Queue.Dequeue<A, E>, never, R | Scope.Scope> stream<A, E, R>(keys: Keys, effect: Effect.Effect<A, E, R>): Stream.Stream<A, E, Exclude<R, Scope.Scope>> withBatch<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> // coalesce invalidations}// Keys are either a flat array, or a record of "table -> ids":type Keys = ReadonlyArray<unknown> | Readonly<Record<string, ReadonlyArray<unknown>>>// ["todos"] -> coarse, whole-collection key// { todos: [id1, id2] } -> fires the "todos" key AND "todos:id1", "todos:id2"
The effectful combinators are the ergonomic surface. mutation wraps a write so its keys are invalidated only on success. query turns a read into a live Queue that re-emits whenever its keys change. The registration is torn down automatically when the surrounding Scope closes.
mutation + query (pipeable accessors)
Fragment · Type-checked with fixture
ts
import { Effect, Queue } from "effect"import { Reactivity } from "effect/reactivity"// a write that invalidates ["todos"] after it succeeds:const addTodo = (text: string) => Reactivity.mutation(insertTodo(text), ["todos"])// Effect<Todo, E, Reactivity | DbR>// a live read keyed on ["todos"]:const watchTodos = Effect.gen(function* () { const queue = yield* Reactivity.query(listTodos, ["todos"]) while (true) { const todos = yield* Queue.take(queue) // initial value, then every refresh console.log("todos now:", todos.length) }}) // requires Reactivity + Scope// run a batch of writes, fire each invalidation once at the end:const importMany = Reactivity.Reactivity.pipe( Effect.flatMap((r) => r.withBatch(Effect.all([addTodo("a"), addTodo("b")]))))
Source note:Reactivity stringifies string, number, bigint, and boolean keys and hashes other values with Hash.hash. The record form { todos: [id] } expands to both the table key todos and each todos:id key. Use that expansion for mutations; register detail reads directly on `todos:${id}` when they must avoid unrelated row invalidations. Query reruns are serialized: while one run is active, repeated invalidations coalesce into at most one pending rerun. A key list that names the same key twice is safe — the handler is stored once per key and scope cleanup tolerates the repeat.
Source note:Reactivity.Reactivity is the Context key and the service's branded interface ([Reactivity.TypeId]); there is no separate Reactivity.Service type to import. The ReactivityService interface above is a reading aid, not an export. Obtain an instance from Reactivity.layer or Reactivity.make rather than writing the object by hand. The same convention applies to LanguageModel, EmbeddingModel, and Chat.
Takeaway: You rarely call Reactivity directly in app code. It reappears below as the engine behind Atom.withReactivity and reactivityKeys — but understanding "keys connect writes to reads, no value caching" makes the rest click.
An Atom<A> is a description of one reactive value. Three flavours to start: a writable state cell, a derived computation, and (next chapters) Effect/Stream-backed atoms.
Atom.ts — the basics
Self-contained source · Type-checked
ts
import { Atom } from "effect/reactivity"// 1. A writable state cell — like useState, but defined ONCE at module scope:const count = Atom.make(0) // Atom.Writable<number>// 2. A derived atom. The `get` function reads other atoms and, by reading them,// declares them as dependencies. Re-runs automatically when they change:const double = Atom.make((get) => get(count) * 2) // Atom<number>// 3. Derived atoms compose — depend on as many atoms as you like:const summary = Atom.make((get) => `count=${get(count)} double=${get(double)}`)
That's the entire surface for pure state: Atom.make(value) for a source of truth, Atom.make((get) => ...) for anything derived. The dependency graph is implicit — reading an atom inside a read function subscribes to it. No dependency arrays.
The get passed to a read function is an AtomContext. Beyond get(atom) it can read without subscribing, await async atoms, manage its own lifecycle, and even write:
AtomContext powers
Self-contained source · Type-checked
ts
import { Effect, Option } from "effect"import { Atom } from "effect/reactivity"const a = Atom.make(1)const b = Atom.make(2)const c = Atom.make(3)const other = Atom.make(4)const asyncAtom = Atom.make(Effect.succeed(5))const optionAtom = Atom.make(Option.some(6))const action = Atom.fn((input: number) => Effect.succeed(input))const derived = Atom.make((get) => { get(a) // read + subscribe (re-run when `a` changes) get.once(b) // read WITHOUT subscribing (snapshot, no re-run) get.self<number>() // Option of this atom's previous value get.setSelf(123) // push a new value for THIS atom (async sources use this) get.addFinalizer(() => {}) // cleanup when this atom is disposed/refreshed get.mount(other) // keep `other` alive for this atom's lifetime get.subscribe(c, (v) => {/* side-effect on change */}) get.refresh(other) // request recomputation of another atom get.refreshSelf() // request recomputation of this atom const awaited = get.result(asyncAtom) // Effect that awaits success const snapshot = get.resultOnce(asyncAtom) // same, without subscribing const some = get.some(optionAtom) // Effect that awaits Some const someSnapshot = get.someOnce(optionAtom) const changes = get.stream(other) // Stream of registry values const successes = get.streamResult(asyncAtom) const actionResult = get.setResult(action, 7) // Effect that writes and awaits success when run void [awaited, snapshot, some, someSnapshot, changes, successes, actionResult] get.registry // the active AtomRegistry return get(a) + get.once(b)})
Every atom carries lazy and keepAlive metadata, tunable with copy-combinators. We'll use them properly once the registry is in play:
combinators (copy-on-write)
Self-contained source · Type-checked
ts
import { Atom } from "effect/reactivity"const a = Atom.make(0).pipe(Atom.keepAlive) // never auto-disposedconst b = Atom.make(0).pipe(Atom.setIdleTTL("30 seconds")) // dispose 30s after last useconst c = Atom.make(0).pipe(Atom.withLabel("myCounter")) // debug labelconst d = Atom.make((get) => get(a)).pipe(Atom.map((n) => n + 1)) // map a valueconst e = Atom.make({ x: 0, y: 0 }).pipe( Atom.withEquality<{ x: number; y: number }>( (left, right) => left.x === right.x && left.y === right.y, ))
Source note:Atom.make is heavily overloaded. With a plain value it returns Writable<A>; with a function it returns a derived Atom<A>; with an Effect or Stream it returns Atom<AsyncResult<A,E>> (chapters 4–5). autoDispose undoes keepAlive, setLazy controls eager rebuilding while mounted, and withEquality replaces the default Object.is comparison so comparator-equal values do not notify listeners or dependents.
Caution: An atom by itself does nothing — double above has never computed anything. It has no value until a registry reads it. That's next.
The registry is where atoms come alive. It stores each atom's current value in a node, wires up the dependency graph, runs Effects, notifies subscribers, and garbage-collects atoms nobody is using.
AtomRegistry.ts — read / write / subscribe
Self-contained source · Type-checked
ts
import { Atom, AtomRegistry } from "effect/reactivity"const count = Atom.make(0)const double = Atom.make((get) => get(count) * 2)const registry = AtomRegistry.make()registry.get(double) // 0 — computed on demandregistry.set(count, 5)registry.get(double) // 10 — recomputed because `count` changed// subscribe returns an unsubscribe function; immediate delivery is opt-in:const cancel = registry.subscribe( double, (v) => console.log("double =", v), { immediate: true },)registry.set(count, 10) // logs "double = 20"cancel()// other writes:registry.update(count, (n) => n + 1)registry.modify(count, (n) => [`was ${n}`, n + 1]) // [returnValue, nextValue]registry.refresh(double) // force recomputation
Without immediate, subscribe still builds the atom, so a derived or effectful atom that nothing has read yet starts computing and the listener hears its next change. get.subscribe, get.stream with withoutInitialValue, and React's useAtomSubscribe behave the same way.
This is the part that surprises people. Atoms are lazy and auto-disposed by default. If nothing subscribes to (or mounts) an atom, the registry drops its node after an idle tick — and the next read rebuilds it from its definition.
GC behaviour (from the test suite)
Self-contained source · Type-checked
ts
import { Atom, AtomRegistry } from "effect/reactivity"const counter = Atom.make(0)const r = AtomRegistry.make()r.set(counter, 1)r.get(counter) // 1await new Promise((res) => setTimeout(res)) // one idle tick passesr.get(counter) // 0 ← node was disposed, rebuilt from initial!// Keep state across idle periods when you need persistence:const kept = Atom.make(0).pipe(Atom.keepAlive)// ...or hold it explicitly for a scope:const release = r.mount(kept) // mounted => never idle-disposed// release() later
Source note: Auto-dispose keeps memory bounded automatically: a per-route data atom evaporates when you navigate away. Reach for keepAlive / setIdleTTL / mount only for state that must outlive its subscribers (a session, a cache you want warm).
Each atom maps to a Node exposing value(), Set-backed parents, children, and listeners, plus currentState() → "uninitialized" | "stale" | "valid" | "removed". You rarely touch nodes directly, but Hydration walks them. Dependency tracking remains intact when a node is invalidated during a batched rebuild.
The registry is also a Context.Service, so you can read/write atoms from inside ordinary Effects. Atom.get, Atom.set, Atom.refresh, Atom.getResult etc. all require the AtomRegistry service:
registry as a service
Self-contained source · Type-checked
ts
import { Effect } from "effect"import { Atom, AtomRegistry } from "effect/reactivity"const count = Atom.make(0)const program = Effect.gen(function* () { yield* Atom.set(count, 42) return yield* Atom.get(count) // requires AtomRegistry})program.pipe( Effect.provide(AtomRegistry.layer), // a fresh registry, disposed with the scope Effect.runPromise,)
Source note:AtomRegistry.make({ initialValues, scheduleTask, timeoutResolution, defaultIdleTTL }) tunes scheduling and GC. initialValues pre-seeds atoms — the hook React's RegistryProvider and test setups use to inject values/layers.
Takeaway: One registry = one isolated world of state. Make one per server request (SSR), one per React tree (the provider), one per test. Atoms are shared definitions; registries are the instances.
The moment an atom is backed by an Effect or Stream, its value is an AsyncResult<A, E>. This is the data type that makes loading/error/stale UI states first-class.
AsyncResult.ts — the shape
Self-contained source · Type-checked
ts
import type { AsyncResult } from "effect/reactivity"// The exact exported union has three variants, and every one carries `waiting`:type State<A, E = never> = AsyncResult.AsyncResult<A, E>// AsyncResult.Initial<A, E> — never asked yet// AsyncResult.Success<A, E> — { value, timestamp, waiting }// AsyncResult.Failure<A, E> — { cause, previousSuccess, waiting }// `waiting` is orthogonal to the variant: a Success can be `waiting: true`// (you have data AND a refresh is in-flight) — that's stale-while-revalidate baked in.
This two-axis design (variant × waiting) is the whole trick. A refresh doesn't throw away your data — it flips waiting to true on the existing Success, so your UI can show data and a spinner without bespoke state machines.
The is* guards above narrow. AsyncResult.isInterrupted (a failure whose cause is only interruption) returns a plain boolean and does not; check isFailure first when you need the Failure type.
Rendering: match, matchWithWaiting, and the fluent builder
Three idioms, increasing in power. match is the exhaustive 3-way switch. matchWithWaiting collapses Initial + waiting into one "loading" branch and splits failures into typed errors vs. defects — usually what a UI wants:
matchers
Self-contained source · Type-checked
ts
import { Data } from "effect"import { AsyncResult } from "effect/reactivity"class LoadError extends Data.TaggedError("LoadError")<{}> {}const result: AsyncResult.AsyncResult<ReadonlyArray<number>, LoadError> = AsyncResult.success([])// exhaustive 3-wayconst label = AsyncResult.match(result, { onInitial: () => "idle", onFailure: (f) => `failed`, onSuccess: (s) => `value: ${s.value}`,})// UI-shaped: loading vs typed error vs defect vs successconst ui = AsyncResult.matchWithWaiting(result, { onWaiting: () => "Loading…", onError: (e) => `Error: ${e.message}`, // your typed E onDefect: (d) => `Unexpected: ${d}`, // squashed non-error cause onSuccess: (s) => `Loaded ${s.value.length} rows`,})
The builder is a type-tracked fluent renderer: the compiler only exposes .exhaustive() once every possible case is handled, and it has tag-aware helpers like .onErrorTag:
AsyncResult.builder
Fragment · Type-checked
ts
import { Data } from "effect"import { AsyncResult } from "effect/reactivity"class NotFoundError extends Data.TaggedError("NotFoundError")<{ id: string }> {}class PermissionError extends Data.TaggedError("PermissionError")<{}> {}declare const result: AsyncResult.AsyncResult<ReadonlyArray<number>, NotFoundError | PermissionError>const rendered = AsyncResult.builder(result) .onInitial(() => "—") .onWaiting(() => "Loading…") .onErrorTag("NotFoundError", (e) => `Missing ${e.id}`) // narrow by _tag .onError((e) => `Error: ${e}`) .onDefect((d) => `Crash: ${d}`) .onSuccess((value) => `Got ${value.length}`) .orElse(() => "unreachable") // or .exhaustive() once all cases are covered
When the first non-success input is a failure, AsyncResult.all rebuilds its previousSuccess in the combined tuple or record shape, using every input's current or previous value. If any input has no value, there is no combined previous success. This matters when rendering stale combined screens after one request fails: the stale value must still contain all fields, not only the failing request's value.
AsyncResult.all
Self-contained source · Type-checked
ts
import { AsyncResult } from "effect/reactivity"const userResult = AsyncResult.success({ id: 1 })const settingsResult = AsyncResult.success({ theme: "dark" })const prefsResult = AsyncResult.success({ compact: true })// First non-success short-circuits; if all succeed you get a Success of the tuple/record,// marked `waiting` if any input was waiting:const combined = AsyncResult.all([userResult, settingsResult] as const)const named = AsyncResult.all({ user: userResult, prefs: prefsResult })
Takeaway:AsyncResult ≈ a typed RemoteData with a stale flag. You won't usually construct it by hand — atoms produce it — but mastering matchWithWaiting/builder is what makes your render code clean.
Now the payoff for being Effect-native. Back an atom with an Effect and it manages the fiber, scope, interruption, and result for you. Back it with a Layer via the default Atom.runtime factory and your atoms can use real services.
import { Data, Effect } from "effect"import { Atom } from "effect/reactivity"interface User { readonly id: number }class FetchError extends Data.TaggedError("FetchError")<{ cause: unknown }> {}const fetchUser = (url: string) => Effect.tryPromise({ try: async () => await fetch(url).then((response) => response.json()) as User, catch: (cause) => new FetchError({ cause }),})const anonymousUser: User = { id: 0 }const userId = Atom.make(1)// value type is AsyncResult<User, E>. The registry forks the effect in a scope,// sets Initial(waiting) -> Success | Failure, and interrupts it on dispose/refresh.const me = Atom.make(fetchUser("/api/me"))// Seed an initial value to skip the Initial state:const meSeeded = Atom.make(fetchUser("/api/me"), { initialValue: anonymousUser })// Depend on other atoms inside the effect — re-fetches when `userId` changes:const profile = Atom.make((get) => fetchUser(`/api/users/${get(userId)}`))
Source note: On refresh, an effect atom keeps its previous Success value but sets waiting: true until the new run resolves — automatic stale-while-revalidate. A Stream source updates the atom on every emission (last value wins), failing with NoSuchElementError if the stream ends empty.
Most real data access needs dependencies (an API client, a DB, config). Atom.runtime(layer) builds a runtime and hands you .atom, .fn, .pull, and .subscriptionRef constructors whose effects can require that layer's services. The default factory's Layer.MemoMap is itself an atom: derived runtimes share services inside one AtomRegistry, while separate registries remain isolated for SSR and tests. Use Atom.context({ memoMap }) only when you intentionally need custom or cross-registry memoization. If Layers are new, first read Services, Context & Layers.
service + runtime (mirrors the test idiom)
Self-contained source · Type-checked
ts
import { Clock, Context, Effect, Layer } from "effect"import { Atom } from "effect/reactivity"interface Todo { id: number; text: string; done: boolean }// An Effect 4 service:class Api extends Context.Service<Api, { readonly list: Effect.Effect<ReadonlyArray<Todo>> readonly add: (text: string) => Effect.Effect<Todo> readonly getById: (id: number) => Effect.Effect<Todo> readonly toggle: (id: number) => Effect.Effect<Todo> readonly prices: Effect.Effect<ReadonlyArray<number>>}>()("app/Api") {}const ApiLive = Layer.effect( Api, Effect.gen(function* () { return Api.of({ list: Effect.succeed([]), add: Effect.fn(function*(text: string) { const id = yield* Clock.currentTimeMillis return { id, text, done: false } }), getById: (id) => Effect.succeed({ id, text: `Todo ${id}`, done: false }), toggle: (id) => Effect.succeed({ id, text: `Todo ${id}`, done: true }), prices: Effect.succeed([]), }) }),)// Build the runtime atom ONCE from the layer:const runtime = Atom.runtime(ApiLive)// Derive an effectful atom that needs the Api service:const todos = runtime.atom(Api.use((api) => api.list))// ^ Atom<AsyncResult<ReadonlyArray<Todo>, never>>
The following short snippets continue to use this Api, runtime, and a registry from the same feature module; they focus on one constructor at a time.
A fn atom is a writable atom whose write value is the function argument. Writing an arg kicks off the Effect; reading the atom gives you the live AsyncResult. This is your "mutation" primitive — form submits, button actions, etc.
Atom.fn
Fragment · Type-checked with fixture
ts
import { Effect } from "effect"import { Atom } from "effect/reactivity"const searchEffect = (query: string) => Effect.succeed(query)const addTodo = runtime.fn((text: string) => Api.use((api) => api.add(text)))// ^ AtomResultFn<string, Todo, never> (a Writable<AsyncResult<Todo>, string | Reset | Interrupt>)// drive it from a registry (or from the React hooks covered below):registry.set(addTodo, "Buy milk") // runs the effect; async work exposes waiting, then Successregistry.get(addTodo) // AsyncResult<Todo>registry.set(addTodo, Atom.Reset) // back to Initialregistry.set(addTodo, Atom.Interrupt) // interrupt the in-flight fiber// Atom.fn options: initialValue, concurrent (don't cancel previous run)// runtime.fn additionally supports static reactivityKeys.const search = Atom.fn((q: string) => searchEffect(q), { concurrent: true })
Asynchronous executions expose a waiting state before completion. A synchronous effect can complete directly as Success without an observable waiting state.
There's also Atom.fnSync for synchronous functions (returns Option<A> before the first call, or a seeded value).
import { Atom, AtomRegistry } from "effect/reactivity"// A writable atom over a Stream. It pulls the first chunk, and each write pulls// the next — accumulating items by default. Great for "load more" / infinite scroll.declare const pagedStream: import("effect").Stream.Stream<Item>interface Item { readonly id: number }const feed = Atom.pull(pagedStream) // Writable<PullResult<Item>, void>const registry = AtomRegistry.make()registry.get(feed) // AsyncResult<{ items: NonEmptyArray<Item>; done: boolean }>registry.set(feed, undefined) // pull the next page
The exact success type uses a non-empty batch: { readonly done: boolean; readonly items: Array.NonEmptyArray<Item> }. The top-level constructor pulls once on first read and accumulates later chunks unless you pass { disableAccumulation: true }.
import { Atom } from "effect/reactivity"// Memoised factory: the SAME atom instance for the same arg (WeakRef-GC'd).// Essential — never call runtime.atom(...) inline in render with a new arg each time.const todoById = Atom.family((id: number) => runtime.atom(Api.use((api) => api.getById(id))))registry.get(todoById(1)) // stable atom for id=1
Atom.windowFocusSignal and refreshOnWindowFocus are safe in non-browser environments — when window is undefined they simply never fire. Supply a custom focus signal only when you want different focus semantics, not to avoid crashes. With revalidateOnFocus: true, freshness still respects staleTime; use "always" to force a refresh on every signal.
Atom.serializable only adds hydration metadata; it does not persist to browser storage. For real local persistence, create a runtime from @effect/platform-browser's BrowserKeyValueStore.layerLocalStorage and pass it to Atom.kvs with a schema, key, and default value.
Takeaway: Think in three roles: queries (runtime.atom(effect), read-only async state), mutations (runtime.fn(arg => effect), write-triggered), and derivations (Atom.make((get) => …) / map). Everything else is a combinator on top.
A different tool for a different job. AtomRef is a standalone, synchronous, observable cell — no registry involved. Reach for it for high-frequency, fine-grained local state: form fields, cursor positions, editor buffers.
The superpower is prop: a typed lens into one field that is itself a fully reactive AtomRef. Subscribers to a prop ref only fire when that field changes (equality-gated) — fine-grained updates without re-rendering the whole form.
prop lenses, map, collection
Self-contained source · Type-checked
ts
import { AtomRef } from "effect/reactivity"const form = AtomRef.make({ name: "", email: "" })const name = form.prop("name") // AtomRef<string> backed by form.namename.set("Grace") // updates form.name AND notifies both refsname.value // "Grace"const upper = name.map((n) => n.toUpperCase()) // ReadonlyRef<string>, derived// reactive collections of item refs:const todos = AtomRef.collection([{ text: "a" }, { text: "b" }])todos.push({ text: "c" })todos.toArray() // raw valuestodos.subscribe((refs) => {/* fires on insert/remove/item change */})
Source note:set is a no-op when the new value is Equal.equals to the current one — so derived/prop refs don't churn. Equality & hashing are based on the contained value.
Atom
AtomRef
Runtime
Needs an AtomRegistry
Standalone, none
Model
Lazy dependency graph, async-capable
Eager synchronous cell
Async
Effects/Streams → AsyncResult
Synchronous values only
Best for
App/query/derived state, data fetching
Fast local UI state, form fields, lenses
Takeaway: Use Atom for the reactive graph; drop to AtomRef when you want imperative, allocation-light, per-field reactivity that never touches the registry. In React they pair via useAtomRef / useAtomRefPropValue.
Now we close the loop from the foundation above. The reason Reactivity exists is so a mutation can invalidate keys and any query atom watching those keys refetches — automatically, with zero manual wiring.
Two halves: withReactivity on reads, reactivityKeys on writes
auto-invalidation loop
Fragment · Type-checked with fixture
ts
import { Atom } from "effect/reactivity"// READ side: a query atom that refreshes whenever ["todos"] is invalidated.const todos = runtime.atom(Api.use((a) => a.list)).pipe( Atom.withReactivity(["todos"]))// WRITE side: a mutation that invalidates ["todos"] on success.const addTodo = runtime.fn( (text: string) => Api.use((a) => a.add(text)), { reactivityKeys: ["todos"] })// Wire-up complete. Now:registry.set(addTodo, "Walk dog")// -> the effect succeeds// -> ["todos"] is invalidated through the Reactivity service// -> the `todos` atom refreshes itself (stale-while-revalidate)// No refetch() call, no cache keys to juggle.
Under the hood, withReactivity(keys) registers a handler that calls get.refresh(self) when the keys fire; reactivityKeys wraps the mutation's effect in Reactivity.mutation(effect, keys) so the keys invalidate after success. Both share the runtime's single Reactivity service.
import { Atom, Reactivity } from "effect/reactivity"// A per-item query listens only to its exact row key:const todoById = Atom.family((id: number) => runtime.atom(Api.use((a) => a.getById(id))).pipe( Atom.withReactivity([`todos:${id}`]) ))// The record form invalidates BOTH "todos" and "todos:<id>". A list listening// on ["todos"] and the matching detail both refresh; unrelated details do not.const toggle = runtime.fn( (id: number) => Reactivity.mutation( Api.use((a) => a.toggle(id)), { todos: [id] }, ),)
Do not register a detail query with { todos: [id] }: record keys always include the shared todos key, so every detail registered that way would refresh for every row mutation (and the matching detail handler can be reached through both expanded keys).
Caution: The runtime .fn option reactivityKeys is static. For keys computed from an argument, wrap the effect with Reactivity.mutation as above. Reads use Atom.withReactivity(keys) with the default factory or runtime.factory.withReactivity(keys) with a custom factory; runtime .atom has no reactivityKeys option.
Takeaway: This is the Effect-native answer to query invalidation: declare which keys a read depends on and which keys a write affects; the runtime does the bookkeeping. It composes with swr, optimistic, and families.
Server-render with real atom values, ship them in the HTML payload, and rehydrate on the client so the first paint is correct and interactive without a flash of loading. The contract is small: mark atoms serializable, then dehydrate on the server and hydrate on the client.
import { Schema } from "effect"import { Atom } from "effect/reactivity"// Attach a stable key + a Schema codec. Only serializable atoms are dehydrated.const username = Atom.make("").pipe( Atom.serializable({ key: "username", schema: Schema.String }))// The schema must encode/decode the atom's VALUE type (here: string).// For async atoms, you provide a codec for their AsyncResult value.
2. Dehydrate on the server, hydrate on the client
Hydration.ts
Fragment · Type-checked with fixture
ts
import { Hydration } from "effect/reactivity"// --- server: after rendering into a per-request registry ---const snapshot = Hydration.dehydrate(serverRegistry) // Initial results are ignored// serialize `snapshot` into the HTML (e.g. window.__ATOMS__ = ...)// --- client: preload BEFORE the atoms are first read ---Hydration.hydrate(clientRegistry, window.__ATOMS__)// encoded values are loaded by key via registry.setSerializable(...)
Source note:encodeInitialAs: "ignore" is the default; "value-only" emits the encoded Initial value. "promise" attaches a live resultPromise, so it is only suitable for a streaming transport that preserves promises—not JSON embedded in HTML. Hydration.toValues narrows dehydrated entries for transports that need the concrete record shape. hydrate applies values by key and notifies existing subscribers immediately. It does not consult dehydratedAt, but it does protect AsyncResult atoms already in the registry: an incoming Initial does not replace a non-Initial result, and an older Success (by its timestamp) does not replace a newer one. Plain values and failures are always applied, so packet ordering otherwise remains the caller's responsibility. A value that fails schema decoding is skipped and the atom computes on the client; a seeded effect or stream atom still runs on mount unless it was marked Atom.serializable({ key, schema, skipInitialRun: true }). dehydrate tolerates a bad codec: an atom whose current value fails to encode with a SchemaError is skipped and the rest of the registry is still emitted, so one mis-declared schema costs a client refetch rather than the whole SSR payload.
For an async atom, the serialization schema must cover the whole AsyncResult, not only its success value. Construct it with AsyncResult.Schema({ success: UserSchema, error: UserErrorSchema }).
For the codec model behind this boundary, use the handbook's concise Schema topic, then Effect's release-matched comprehensive Schema guide for the long-form treatment.
withReactivity preserves the underlying initial-value target, so a preloaded serializable atom still refreshes the correct source atom.
Some atoms must read differently on the server (no window, no Date.now() drift). Override their server-side read:
withServerValue
Self-contained source · Type-checked
ts
import { Atom } from "effect/reactivity"const startedAt = Atom.make(() => Date.now()).pipe( Atom.withServerValue(() => 0) // stable on the server -> no hydration mismatch)// For async atoms: Atom.withServerValueInitial keeps them Initial(waiting) on the server.// Read with Atom.getServerValue(atom, registry) when rendering server-side.
Takeaway: SSR = three verbs: serializable (opt in + give a codec), dehydrate (snapshot a registry), hydrate (preload another). The React layer wraps step 3 in a component (next).
The @effect/atom-react package connects atoms to components: a registry provider, a family of hooks built on useSyncExternalStore (SSR-safe), Suspense integration for AsyncResult, and a hydration boundary. This guide demonstrates React; the concise Reactivity & Atom topic lists the Solid and Vue equivalents.
import { HydrationBoundary, useAtomValue } from "@effect/atom-react"import * as ScopedAtom from "@effect/atom-react/ScopedAtom"import { Atom } from "effect/reactivity"// Each <Provider> instance owns its OWN atom — different subtrees don't share state:const Counter = ScopedAtom.make(() => Atom.make(0))function View() { const atom = Counter.use() return <span>{useAtomValue(atom)}</span>}// Render with: <Counter.Provider><View /></Counter.Provider>// SSR: feed dehydrated state into the nearest registry before children read.function Page({ dehydrated }: { dehydrated: any }) { return ( <HydrationBoundary state={dehydrated}> <TodoList /> </HydrationBoundary> )}
Source note: Hooks use useSyncExternalStore with a server snapshot (Atom.getServerValue). RegistryProvider creates one registry per subtree and lets you opt into defaultIdleTTL; the fallback RegistryContext uses 400ms. Provider disposal waits 500ms after unmount and is canceled if it remounts. Suspense promise caches are isolated per registry. HydrationBoundary hydrates brand-new atoms during render, but defers values for atoms already present until after commit — so a transition cannot update the current UI early.
Takeaway: Define atoms at module scope; useAtomValue/useAtom for sync state, useAtomSuspense + a Suspense boundary for queries, useAtomSet({mode:"promise"}) for mutations. Suspense always waits for Initial; a waiting state alone does not suspend unless suspendOnWaiting: true. A waiting Success is returned, while a Failure is returned only with includeFailure: true and otherwise throws Cause.squash. Pair with RegistryProvider (client) and HydrationBoundary (SSR).
Selectors are compared with the mapped atom's default Object.is equality. Keep selector functions stable (module scope or useCallback) when identity churn matters, because an inline selector produces a fresh mapped atom whenever the function identity changes.
AtomHttpApi and AtomRpc connect Effect's typed clients to the same registry, runtime, reactivity, retention, and hydration machinery. They are the high-level path when your data source already has an HttpApi or RPC contract.
Fragment · Type-checked with fixture
ts
import { AtomHttpApi, AtomRpc } from "effect/reactivity"// Given an HttpApi contract `Api` and an HTTP client layer `HttpClientLive`:const Http = AtomHttpApi.Service()("app/Http", { api: Api, httpClient: HttpClientLive,})const user = Http.query("users", "getUser", { params: { id: 1 }, reactivityKeys: { users: [1] }, timeToLive: "30 seconds", serializationKey: "1",})const saveUser = Http.mutation("users", "saveUser")// Given an RpcGroup `Rpcs` and client protocol layer `RpcProtocol`:const RpcClient = AtomRpc.Service()("app/Rpc", { group: Rpcs, protocol: RpcProtocol,})const profile = RpcClient.query("getProfile", { id: 1 }, { reactivityKeys: { profiles: [1] }, timeToLive: "30 seconds", serializationKey: "1",})const saveProfile = RpcClient.mutation("saveProfile")
Both services expose the underlying typed client and an atom .runtime. Their query options can add static reactivity keys, an idle TTL (or infinite keep-alive), and a stable hydration serialization key. Mutations accept reactivity keys with each write request. A streaming RPC query becomes a writable pull atom, so writing undefined requests the next chunk. The query builders preserve serialization and idle-retention metadata when reactivity wrapping is applied; separately, Atom.withReactivity preserves the hydration initial-value target.
What the typed atoms promise about results and errors
The generated atoms are thin: they call the typed client and hand you its result. Three rules keep rendering code honest.
Question
AtomHttpApi
AtomRpc
What is the success type?
Exactly the generated client's type for that endpoint and responseMode — decoded value, [value, response] tuple, raw response, header-wrapped value, or a Stream for SSE and binary-stream endpoints.
The RPC's success type; a streaming RPC becomes a pull atom.
What is in the typed error?
Endpoint errors plus middleware errors (server-declared and client-side).
RPC error, RpcClientError, and both error kinds of every middleware on the RPC.
Where do transport and decode failures go?
For the request: defects (render with onDefect). For a returned Stream: the stream's error channel — HttpClientError, Schema.SchemaError, Sse.Retry, Sse.SseError alongside the declared stream error.
In the typed error as RpcClientError.
How long is an unused query kept?
Omitted timeToLive → the registry's defaultIdleTTL; 0 → no idle retention; finite → that long; infinite → kept alive.
Same.
Two consequences for UI code. A component that reads an SSE query gets Success as soon as the stream exists; the interesting failures happen later, inside the stream, so the consumer (Stream.catch, or an atom built from that stream) must handle them. And a session-expiry middleware on an RPC shows up in the atom's error union, so an exhaustive AsyncResult.builder(...).onErrorTag(...) chain stops compiling until you add the case, which is the point.
AtomHttpApi also accepts per-call sseOptions (native SSE decode options; they are part of the query's family key) and dispatches endpoints of a topLevel group on the client root while you still address them by group identifier.
One small Todos feature ties the central primitives together: a service-backed runtime, a query atom with auto-invalidation, URL state, a serializable shared draft atom, Suspense rendering, and a registry-level test. This is the shape of real Effect 4 reactive code.
import { Clock, Context, Effect, Layer, Schema } from "effect"import { AsyncResult, Atom } from "effect/reactivity"interface Todo { id: number; text: string; done: boolean }export class TodoApi extends Context.Service<TodoApi, { readonly list: Effect.Effect<ReadonlyArray<Todo>> readonly add: (text: string) => Effect.Effect<Todo> readonly toggle: (id: number) => Effect.Effect<Todo>}>()("app/TodoApi") {}const TodoApiLive = Layer.effect(TodoApi, Effect.gen(function* () { // ...real HTTP client built from a Layer dependency... return TodoApi.of({ list: Effect.succeed([]), add: Effect.fn(function*(text: string) { const id = yield* Clock.currentTimeMillis return { id, text, done: false } }), toggle: (id: number) => Effect.succeed({ id, text: "", done: true }), })}))// 1) one runtime for the whole feature (services shared within each registry)export const runtime = Atom.runtime(TodoApiLive)// 2) QUERY: auto-refreshes when ["todos"] is invalidated; stays fresh for 15sexport const todosAtom = runtime.atom(TodoApi.use((a) => a.list)).pipe( Atom.withReactivity(["todos"]), Atom.swr({ staleTime: "15 seconds" }), Atom.withLabel("todos"),)// 3) MUTATIONS: invalidate ["todos"] on success -> the query refetches itselfexport const addTodo = runtime.fn( (text: string) => TodoApi.use((a) => a.add(text)), { reactivityKeys: ["todos"] },)export const toggleTodo = runtime.fn( (id: number) => TodoApi.use((a) => a.toggle(id)), { reactivityKeys: ["todos"] },)// 4) ancillary state: filter in the URL, draft marked for SSR hydrationexport const filter = Atom.searchParam("filter") // ?filter=activeexport const draft = Atom.make("").pipe(Atom.serializable({ key: "draft", schema: Schema.String }))// 5) DERIVED view model — recomputes when todos or filter changeexport const visibleTodos = Atom.make((get) => { const f = get(filter) return AsyncResult.map(get(todosAtom), (todos) => f === "active" ? todos.filter((todo) => !todo.done) : f === "done" ? todos.filter((todo) => todo.done) : todos )})
The draft is deliberately a registry-managed Atom: it is shared by the feature and carries hydration metadata. For a component-local form buffer that does not participate in the graph or cross an SSR boundary, use an AtomRef instead.
Define atoms at module scope. Never call Atom.make/runtime.atom inside render with fresh args — use Atom.family for parameterised atoms.
Lean on auto-dispose. Default lazy + GC keeps memory bounded. Add keepAlive/setIdleTTL/useAtomMount only for state that must outlive its subscribers.
Select narrowly.useAtomValue(atom, selector) subscribes to the mapped slice. Keep selectors stable, and remember their output uses Object.is unless you build an atom with custom equality.
Use AtomRef for purely local hot state. Form keystrokes and cursor moves that do not need graph dependencies, sharing, or hydration fit its prop lenses; use an Atom when that state deliberately participates in those capabilities.
Prefer reactivity keys over manual refresh. Let mutations invalidate; let queries refetch. Manual refresh is the escape hatch, not the default.
Mind error boundaries.useAtomSuspense throws Cause.squash(cause) on failure unless you pass includeFailure: true.
One registry per world. Per request on the server, per tree on the client, per test. Dehydrate/hydrate to bridge server→client.
Takeaway: You now have the full picture: Reactivity wires writes to reads · Atom describes reactive values · AtomRegistry runs & GCs them · AsyncResult models async state · AtomRef handles fine-grained local state · Hydration crosses the SSR boundary · AtomReact binds it to the view. Same primitives, from a counter to a production data layer.
Deep DivesPage 56 of 66
Adopting Effect in an Existing TypeScript Codebase
Most teams do not get to start over. They have a Promise-based service that works, callers that depend on its exact shape, and a list of production incidents that all sound alike: a request nobody could cancel, a failure nobody could tell apart from another failure, a batch job that opened four hundred connections. This guide takes one such service from a compensation platform and moves it to Effect without a rewrite, one verifiable step at a time.
Migrating an existing v3 codebase wholesale? This page is about learning to write and review idiomatic v4 code by hand. If you instead want to mechanically port an existing effect@3.x codebase, use the official Effect-TS/skills migration skill (npx skills add Effect-TS/skills, skill name effect-v3-to-v4): it drives a migrate-and-typecheck loop over migration/v3-to-v4.md instead of a manual read-and-rewrite pass. Prefer the skill for bulk migration; come back to this page for the judgment calls — seam placement, cancellation, test strategy — the skill does not make for you.
The route: audit what the signatures do not say, pin today's behavior, freeze the external contract, migrate leaf-first behind it, keep exactly one seam where Promise meets Effect, make adapters cancellable before adding policy, take the first testing win with Effect.provideService, graduate to Layers, then bound the fan-out and decide when you are done.
"It compiles" answers one question: do the values fit together? An operational audit asks what happens when the code runs, and it needs no Effect knowledge — it is a code-review checklist for any TypeScript function. Ask each question of the signature first, then of the body, and write down the gap between the two.
Question
What RaiseService answers
Where Effect makes the answer explicit
What can fail, and is it typed?
HRIS down, employee missing, malformed JSON (hidden by as Employee), band violation, payroll rejection. Promise<Employee> names none of them; a caller's catch receives unknown.
the E channel, tagged errors, Schema decoding
What does it depend on, and is that visible?
The constructor shows three collaborators; call sites show nothing. getEmployee also depends on the global fetch.
the R channel
Has work started by the time I hold the return value?
Yes. Calling approveRaise has already sent the HRIS request, so it cannot be retried, delayed, or composed as a value.
an Effect is a lazy description; a runner at the edge starts it
What does it hold open, and who releases it?
One HTTP exchange per call, ids.length of them in approveCycle. Nothing releases them if the caller stops waiting.
Scope, acquireRelease, finalizers
Can it be cancelled?
No. There is no AbortSignal anywhere, so a client disconnect or a caller-side timeout leaves the request and the payroll write running.
interruption, plus signal in every adapter
What happens under concurrency?
Promise.all starts every call at once. On the first rejection the batch rejects while the others keep running, payroll writes included.
Effect.forEach(..., { concurrency }); a failure interrupts the siblings
Where do logs, spans, and identifiers come from?
Nowhere.
Effect.fn("name"), log annotations
Is a retry safe?
Unknown: nothing says whether updateSalary is idempotent.
a Schedule owned by the operation that knows
Keep one honesty rule while filling in the table. Instrumentation can prove that work starts eagerly or that two failure paths are indistinguishable. It cannot prove that a timeout, retry, or telemetry policy is absent on purpose; a missing policy is a gap in the contract, so record it as a question for the owner, not as a bug.
Each row maps to a slot in Effect<A, E, R> or to a runtime guarantee. That mapping is the argument for adopting Effect here, and it tells you which rows to fix first: the ones behind last quarter's incidents.
Before touching RaiseService, write tests that describe what it does today, including the parts you intend to change. These are characterization tests: they assert ordering, fan-out, and start time, not just return values.
Use latches and counters, never elapsed time. A Promise you resolve by hand forces an interleaving; setTimeout(50) merely hopes for one.
Do not fix production code while characterizing it. A surprising assertion that passes is the point.
One observed symptom, one test. Each later step changes at most one of these assertions.
Example status — Contextual: a Vitest file; makeService builds the RaiseService above from controllable collaborators.
Fragment · Type-checked
ts
import { expect, it } from "vitest"interface Employee { readonly id: string readonly level: string readonly salary: number}declare const makeService: (deps: { readonly getEmployee: (id: string) => Promise<Employee> readonly updateSalary: (id: string, salary: number) => Promise<void> readonly notify: (message: string) => Promise<void>}) => { readonly approveRaise: (id: string, percent: number) => Promise<Employee> readonly approveCycle: (ids: ReadonlyArray<string>, percent: number) => Promise<ReadonlyArray<Employee>>}// A Promise the test resolves by hand: a latch, not a timer.const latch = <A>() => { let open!: (value: A) => void const promise = new Promise<A>((resolve) => { open = resolve }) return { promise, open }}const ada: Employee = { id: "e-1", level: "L4", salary: 120_000 }it("acknowledges the raise before the notification settles", async () => { const notified = latch<void>() const service = makeService({ getEmployee: () => Promise.resolve(ada), updateSalary: () => Promise.resolve(), notify: () => notified.promise // never opened during the call }) await expect(service.approveRaise("e-1", 0.04)).resolves.toMatchObject({ salary: 124_800 })})it("starts every HRIS call before any of them finishes", async () => { let inFlight = 0 let peak = 0 const gate = latch<Employee>() const service = makeService({ getEmployee: () => { peak = Math.max(peak, ++inFlight) return gate.promise.finally(() => inFlight--) }, updateSalary: () => Promise.resolve(), notify: () => Promise.resolve() }) const cycle = service.approveCycle(["e-1", "e-2", "e-3", "e-4", "e-5"], 0.04) expect(peak).toBe(5) // synchronously: all five started before the first `await` gate.open(ada) await cycle})
Both tests pass against the legacy code, and both describe behavior you will deliberately change. When a later step bounds the fan-out to four, the second test's 5 becomes 4 in the same commit. The diff of a characterization test is the documented behavior change.
Freeze everything a caller can observe: the class and method names, Promise-returning signatures, HTTP and CLI shapes, identifiers, storage formats, and the order of side effects. A step may change an internal contract — that is what the steps are for — but it changes one, says so, and updates the matching characterization test.
Two consequences shape everything below:
The Promise method stays callable. Add an Effect-returning function beside it and make the Promise method delegate. Callers migrate when they are ready; nothing breaks while they wait.
One keystone edit per step, verified cumulatively. After each step the whole suite runs, not just the new test.
Dependencies decide the order. Start where nothing else in your code is called, and move up only when the layer below returns Effects.
Stage
What moves
Why it is safe here
1
Pure values: Option for absence, Result for validation, Data classes, Duration
No runtime involved; usable from plain TypeScript today
2
Leaf adapters become lazy descriptions with one runner at the edge
Callers still see Promises
3
Typed failures replace throw new Error(...)
The facade converts them back into the rejections callers expect
4
Schemas at the boundaries replace as casts
Malformed data becomes a named failure instead of a latent crash
5
Services and Layers replace constructor wiring
Tests stop patching modules
6
Scoped resources, owned fibers, bounded fan-out
Lifetimes get owners
7
Shared state and queues
Only now, because they depend on all of the above
The first leaf is getEmployee. Pick the constructor by how the wrapped code reports failure: a Promise that can reject is Effect.tryPromise, and its thunk receives an AbortSignal that you pass straight through.
Example status — Contextual: the Effect version of the HRIS leaf.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"export class Employee extends Schema.Class<Employee>("comp/Employee")({ id: Schema.String, level: Schema.String, salary: Schema.Finite}) {}export class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", { employeeId: Schema.String, cause: Schema.Defect()}) {}export class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()("EmployeeNotFound", { employeeId: Schema.String}) {}export class HrisContractViolation extends Schema.TaggedError<HrisContractViolation>()( "HrisContractViolation", { employeeId: Schema.String, detail: Schema.String }) {}const decodeEmployee = Schema.decodeUnknownEffect(Employee)export const getEmployee = Effect.fn("Hris.getEmployee")(function*(baseUrl: string, employeeId: string) { // The request is created inside the thunk, so it is supervised from its first instant, // and `signal` aborts it when the calling fiber is interrupted. const response = yield* Effect.tryPromise({ try: (signal) => fetch(`${baseUrl}/employees/${employeeId}`, { signal }), catch: (cause) => new HrisUnavailable({ employeeId, cause }) }) if (response.status === 404) return yield* new EmployeeNotFound({ employeeId }) if (!response.ok) { return yield* new HrisUnavailable({ employeeId, cause: `status ${response.status}` }) } const body = yield* Effect.tryPromise({ try: () => response.json() as Promise<unknown>, catch: (cause) => new HrisUnavailable({ employeeId, cause }) }) return yield* decodeEmployee(body).pipe( Effect.mapError((error) => new HrisContractViolation({ employeeId, detail: error.message })) )})
Three audit rows now have answers, and nothing has run: the failures are named in the type — Effect<Employee, HrisUnavailable | EmployeeNotFound | HrisContractViolation> — the JSON is decoded instead of cast, and the request can be cancelled. One trap to carry along: JavaScript evaluates arguments eagerly, so Effect.succeed(Date.now()) reads the clock while the program is being built. Wrap side effects in Effect.sync, Effect.try, or Effect.tryPromise, and add one test that builds the Effect, asserts the spy was not called, runs it, and asserts exactly one call.
The legacy method keeps its name and its Promise. Its body becomes a single runner call, and that file is the only place in the codebase that is allowed to contain one.
Example status — Contextual:getEmployeeEffect is the Effect from the previous section, imported under another name.
Fragment · Type-checked
ts
import { Effect } from "effect"interface Employee { readonly id: string readonly level: string readonly salary: number}declare const getEmployeeEffect: ( baseUrl: string, employeeId: string) => Effect.Effect<Employee, { readonly _tag: "HrisUnavailable" | "EmployeeNotFound" | "HrisContractViolation" }>// Same name, same Promise, plus an optional signal that legacy callers may ignore.export const getEmployee = (baseUrl: string, id: string, signal?: AbortSignal): Promise<Employee> => Effect.runPromise(getEmployeeEffect(baseUrl, id), { signal })
Effect.runPromise rejects with the failure value itself, and the tagged errors above are Error subclasses, so a legacy catch (error) keeps working while new callers can branch on error._tag. If a caller inspects the old message text, restore it here with Effect.mapError; the facade is where the old contract is honored.
A runner in the middle of the code severs supervision. The first form below type-checks and returns the right value:
Example status — Contextual:loadBand stands for any Effect your code already has.
Fragment · Type-checked
ts
import { Effect } from "effect"declare const loadBand: (level: string) => Effect.Effect<number>// Wrong: `loadBand` now runs as an unrelated root fiber.export const bandViaInteriorRunner = (level: string) => Effect.promise(() => Effect.runPromise(loadBand(level)))// Unavoidable third-party callback? Forward the signal so interruption still arrives.export const bandViaBridge = (level: string) => Effect.promise((signal) => Effect.runPromise(loadBand(level), { signal }))// Right, whenever you control the code: stay in Effect and compose.export const band = (level: string) => loadBand(level)
In the first form, interrupting the outer fiber never reaches the inner one: its onInterrupt finalizer does not run, its requirements must already be closed, and its typed failure is flattened into a rejection. Timeouts, races, and graceful shutdown all stop at that line. The second form restores cancellation and nothing else; treat it as a bridge for callbacks you do not own.
Keep the seam in one place so it can shrink. Today it is Effect.runPromise inside the facade. Once services exist it becomes one ManagedRuntime, and when the last Promise caller is gone the facade is deleted and the entrypoint's runMain is the only runner left. A quick check that survives code review: Effect.run should appear only in entrypoints, host adapters, the facade, and tests.
Deadlines, races, and structured shutdown are only as good as the leaves. Effect.timeout interrupts the fiber; if the adapter ignored its signal, "interrupted" means "abandoned but still running", and a retry then stacks a second request on top of the first. So the order is fixed: cancellation first, policy second.
Rules for every adapter, whatever it wraps:
Create the Promise inside the thunk and pass the supplied signal to fetch, the driver, or the SDK.
For callback APIs, return a cleanup Effect from the Effect.callback registration, or register listeners with { signal }.
Keep cancellation as cancellation. An interrupted tryPromise exits as an interruption, not through catch; do not convert it into HrisUnavailable, or a retry policy will retry a caller who left.
Do not start a wall-clock timer inside the adapter. Let Effect.timeout own the deadline so TestClock can drive it.
Example status — Contextual: the policy that becomes safe once both adapters can be cancelled.
Fragment · Type-checked
ts
import { Effect, Schedule } from "effect"declare const getEmployee: ( employeeId: string) => Effect.Effect<{ readonly salary: number }, { readonly _tag: "HrisUnavailable" | "EmployeeNotFound" }>declare const updateSalary: ( employeeId: string, salary: number) => Effect.Effect<void, { readonly _tag: "PayrollRejected" }>// Reads are repeatable, so the read owns a retry: each attempt gets two seconds,// and only an unavailable HRIS is worth another attempt.export const getEmployeeWithPolicy = (employeeId: string) => getEmployee(employeeId).pipe( Effect.timeout("2 seconds"), Effect.retry({ schedule: Schedule.exponential("100 millis").pipe(Schedule.jittered), times: 3, while: (error) => error._tag === "HrisUnavailable" }) )// The payroll write gets a deadline and no retry: nothing has established that it is idempotent.export const updateSalaryWithDeadline = (employeeId: string, salary: number) => updateSalary(employeeId, salary).pipe(Effect.timeout("5 seconds"))
Take the first testing win with Effect.provideService
The use case needs its collaborators. In Promise code they arrive through a constructor, and tests reach past it to patch modules or globals. In Effect they are requirements: declare each one as a Context.Service, yield* it, and the type lists what is still unwired.
You do not need a Layer graph to benefit. A service value that already exists — above all a test fake — is provided with Effect.provideService, and each call removes exactly one identifier from R.
Example status — Contextual: the use case and its first test, run with Vitest 5 and @effect/vitest.
The real workflow ran with no network, no module patching, and no shared mock state, and the fake recorded what it received, which proves the seam is real rather than merely declared. Fakes obey the same contract as live implementations: they fail with Effect.fail(new EmployeeNotFound(...)), never with throw, or the test exercises a different failure channel than production.
Do the inverse nowhere: an Effect.provideService(Hris, liveHris) inside approveRaise would make R look clean while hard-wiring production I/O into a reusable function. Live implementations are provided at the application edge and fakes at the test edge.
Graduate to Layers when construction becomes a graph
provideService stops being enough when an implementation needs configuration, state, an effectful constructor, another service, or a lifetime. That is what a Layer is for: Layer.succeed for a ready value, Layer.effect for everything else. The Layer's build owns the Scope, so a connection acquired with Effect.acquireRelease inside it is released when the application shuts down.
Example status — Contextual: the production wiring and the final shape of the seam.
RaiseService kept its name, its method, and its Promise. Its constructor lost its dependency bag because the runtime now supplies them, and it gained an optional signal that a host forwards from the request. Creating a ManagedRuntime per call would rebuild AppLive every time; create it once per host.
shutdown() is not a formality: runtime.dispose() closes the runtime's own scope, which interrupts and waits for every fiber the runtime started through runFork/runPromise before the returned Promise resolves. A host that calls dispose() and immediately exits still lets in-flight requests finish their finalizers; a host that never calls it leaks the Layer's resources on process exit. This is also why building AppLive only once matters for a different reason than performance: the Layer graph's MemoMap is shared across chained or nested Effect.provide calls on the same fiber lineage (see Anatomy of a Real Effect Application), so a stray second provide of the same Layer value inside the runtime's lifetime reuses the live instance rather than opening a second one — but two genuinely separate ManagedRuntime.make(AppLive) calls do not share anything, and are exactly as wasteful as the sentence above says.
Separately, the Effect runtime now keeps the process alive on its own while a fiber is suspended on something like Deferred.await — a bare Effect.runPromise(program) no longer exits early just because the event loop looks idle. That lowers the cost of forgetting runMain, but it does not replace it: NodeRuntime.runMain (and its Bun/Deno equivalents) still install SIGINT/SIGTERM handling, map the final Exit to a process exit code, and report unhandled errors, none of which the keep-alive timer does by itself.
approveCycle is the last audit row. Promise.all has no Effect equivalent that behaves the same way, and that is deliberate: Effect.all and Effect.forEach are sequential unless you ask for concurrency, and they stop on the first failure by interrupting the work still in flight.
Example status — Contextual:approveRaise is the use case with its services already provided.
Results come back in input order. At most four HRIS and payroll calls are in flight, and because the adapters are cancellable, a failure in one stops the others instead of orphaning them. If the batch should report every outcome instead, that is a different contract: Effect.forEach over Effect.result(approveRaise(...)), or Effect.partition.
This step changes observable behavior, so the second characterization test changes with it — expect(peak).toBe(5) becomes an assertion that the peak never exceeds 4 — and the fire-and-forget notification gets the same treatment. Decide who owns it (Effect.forkScoped inside a Layer, or a queue with a worker), then rewrite the first test to say what the new owner guarantees.
Every step above is the same move with a different noun: keep something explicit on the inside, and collapse it exactly once, at a boundary that owns the decision.
Kept explicit inside
Collapsed at
Collapsing anywhere else causes
Absence (Option)
the display or serialization edge that picks the fallback
undefined checks scattered through the domain
Expected failure (E)
the handler that maps it to a response, with Effect.match or Effect.catchTags
a generic 500, or a swallowed error
Unknown data
one Schema decode at ingress
as casts and re-validation in every function
Requirements (R)
one provide at the edge, or fakes at the test edge
hidden live dependencies
Execution
one runner per owned edge
severed supervision
Units (Duration, branded ids)
the interop call that needs a bare number or string
This guide turns Effect's core primitives into one application shape: domain values are Schemas, expected failures are tagged errors, behavior lives behind services, Layers own construction and cleanup, and the runtime is called only at an application edge.
An Effect application is easiest to reason about as four concentric boundaries:
Domain — schemas, domain values, and expected errors. It knows nothing about databases, HTTP, or process startup.
Capabilities — service interfaces such as EmployeeRepository or AuditLog. Business logic depends on these interfaces through the Effect requirement channel.
Implementations — Layers that construct capabilities from configuration and lower-level services, and own any acquired resources.
Edges — an HTTP server, CLI, worker, test, or framework adapter that provides the completed Layer graph and runs the Effect.
Dependencies point inward. Domain logic never calls Effect.runPromise, reads process.env, creates an SDK client, or chooses a database driver. Those decisions belong at the outer edge.
Example status — Illustrative: the names are a project layout, not library API.
text
src/ domain/ Employee.ts # Schema values and tagged domain errors services/ EmployeeRepository.ts # capability only Compensation.ts # use-case service layers/ EmployeeRepositoryMemory.ts EmployeeRepositorySql.ts AppConfig.ts api/ Api.ts # transport contract, safe for clients to import Handlers.ts # server implementation AppLive.ts # production Layer graph Main.ts # the only process-runtime edgetest/ Compensation.test.ts
Separate files are useful because they enforce ownership. They are not a reason to create a service for every helper: keep pure calculations as ordinary functions and introduce a service when behavior needs substitution, lifecycle, configuration, or another Effect capability.
The domain schema should describe both the runtime value and the representation that crosses a boundary. A branded identifier prevents accidental mixing, a class gives the domain a named value, and tagged schema errors stay typed and serializable.
Example status — Runnable: this block runs with the published effect package.
Decode unknown data at ingress and pass decoded values inward. Do not make every service re-parse the same object, and do not replace validation with as Employee. See Schema — From External Input to Domain and Back for the full boundary journey.
Context.Service describes what domain logic may do. Its methods return Effects so success, expected failure, and required dependencies remain visible in their types.
The implementation is a Layer. Naming a dependency-free implementation layerNoDeps makes the eventual wiring graph readable; a convenient layer may provide a normal production dependency when there is one unambiguous default.
Example status — Contextual: place this after the domain definitions above. Every library import used by the block is included.
The use-case implementation reads EmployeeRepository once while its Layer is built. Callers see only the Compensation requirement; they do not know whether the repository is memory, SQL, or an HTTP client.
A Layer's build runs in a Scope. Effect.acquireRelease acquired inside Layer.effect is therefore released when the Layer is torn down, including after failure or interruption. Read configuration during construction rather than throughout business logic, and keep secrets redacted until the concrete client requires their raw value.
Example status — Contextual: this is the production implementation of an application capability. AuditClient represents a third-party SDK supplied by the application.
Do not acquire a resource outside Effect and then merely place it in a Layer: the Layer cannot finalize what it does not own. Conversely, do not wrap an already-managed Layer in a new manual Scope. Compose it and let one outer runtime close the graph.
Effect.acquireRelease registers its release only after the acquire effect succeeds, so an acquire that opens two handles and fails on the second leaves the first one open with no finalizer. Give every handle its own bracket. When a later acquisition fails, the Layer's Scope unwinds and the earlier releases run, newest first. The same rule covers a Layer build that fails halfway: whatever was already bracketed is released; whatever was opened outside a bracket leaks.
Example status — Contextual:openLedger and openArchive stand for two SDK connections supplied by the application.
A release effect has error type never, so a fallible close() forces a decision at the point of registration. Effect.promise turns a rejected close() into a defect; wrap it with Effect.tryPromise(...).pipe(Effect.ignore) when a failed close is only worth a log line, and bound it with Effect.timeoutOption when shutdown must not wait on a dead peer. Finalizers run uninterruptibly, so an unbounded finalizer is an unbounded shutdown.
Build named Layer values and reuse them. Layer memoization is based on Layer object identity inside a build, so recreating an equivalent expression is not the same as sharing the same value. Composed layers are memoized too: a Layer.provide / provideMerge / mergeAll result referenced from several parents is built once per memo map, not once per path.
Example status — Contextual: it uses the services defined above and supplies an application seed.
Use Layer.provide(dependency) when the dependency is an implementation detail and should disappear from the output. Use Layer.provideMerge(dependency) only when callers genuinely need both services. Layer.merge combines independent outputs. Avoid exposing every low-level service “just in case”; the remaining requirement type should describe the application's public capabilities.
There is one composition root per executable or host instance — the HTTP server, the payroll worker, the CLI, and each test harness have their own — not one per repository. A root has six duties, and nothing else in the codebase should perform them:
Define the top-level program, or the bridge a foreign host calls into.
Assemble the Layer graph from named feature Layers.
Install configuration and observability before the Layers that depend on them acquire anything.
Bind the graph to its owner's lifetime: a process, a ManagedRuntime, or a test scope.
Hand the closed program to the platform runner or host bridge.
Dispose the graph and report how the program ended.
A higher-level use case composes an existing use case through its service; it does not reach through to that use case's repository. Keep feature graphs open — a feature Layer may still require SqlClient — and close them only here. A universal layers.ts that exports every Layer, or a global service locator, erases exactly the ownership this section is about.
“Built once” is a claim about a fiber's lineage, so name it. Every Effect.provide forks a child memo map from whatever memo map is already in the ambient fiber context, or starts a fresh one if there is none. That makes sharing broader than “nested builds only”: program.pipe(Effect.provide(AppLive), Effect.provide(AppLive)) now builds AppLive once, because the second provide inherits the memo map the first one just added to context, and a provide nested inside a live build of the same Layer value — including an effect run through a ManagedRuntime made from it — reuses the live instance for the same reason. What still builds twice is two invocations with no shared lineage — two separate Effect.runPromise calls, or two fibers forked before either one's provide has run. Provide the application Layer once at the root regardless, and prove sharing with an acquisition counter rather than by reading the code. Layer.fresh(layer) rebuilds that one layer fresh everywhere it is referenced — but a shared composed layer shares everything inside it, including dependencies wrapped in Layer.fresh, so wrap the composed layer itself in Layer.fresh when you need a separate copy. A shared build runs on the first requester's fiber; if that fiber is interrupted, every requester waiting on the same build sees the interruption. Likewise Effect.provide(layer, { local: true }) builds an entire provide call against an isolated local memo map; neither is a fix for a type error, because both duplicate pools, caches, and subscriptions.
Official guide: Layer Memoization. Memoization is keyed on Layer object identity and shared across chained and nested Effect.provide calls via the ambient memo map; Layer.fresh and { local: true } are the deliberate opt-outs.
For a one-shot program, provide the Layer and pass the resulting Effect to the host runtime. For a server or permanent background process represented as Layers, Layer.launch keeps the graph alive until interruption. NodeRuntime.runMain and its Bun/Deno equivalents install process signal handling and map the final Exit to process termination.
Example status — Contextual: this is an application entrypoint and requires @effect/platform-node at the same release line as effect.
Fragment · Type-checked with fixture
ts
import { NodeRuntime } from "@effect/platform-node"import { Effect } from "effect"import { AppLive, program } from "./AppLive.ts"// One-shot command or batch:program.pipe(NodeRuntime.runMain)// A long-running app would instead launch its server/background Layer:// Layer.launch(ServerLive.pipe(Layer.provide(AppLive))).pipe(NodeRuntime.runMain)
When Hono, Express, a UI framework, or another callback-driven host owns execution, construct one ManagedRuntime for the application Layer, reuse it for every callback, and dispose it during host shutdown. Creating one runtime per request defeats Layer sharing and leaks resources if it is not disposed.
Example status — Contextual:handleRequest is the callback exposed to the external host.
That is the minimal shape. A real host callback also forwards the host's cancellation, in both hops. Every ManagedRuntime runner except runSync / runSyncExit accepts Effect.RunOptions; passing the host's AbortSignal as { signal } turns a client disconnect into fiber interruption, so finalizers run and pool slots come back. Check an already-aborted signal before invoking the runner: its initial synchronous prefix can execute before it checks that signal. That is hop one. Hop two lives in the adapters: an Effect.tryPromise thunk receives Effect's own AbortSignal and must hand it to fetch or the driver. Drop either hop and the caller is gone while the work keeps its socket, connection, and rate-limit budget. When a framework offers a disconnect hook instead of a signal, abort an AbortController from that hook and pass its signal.
Example status — Contextual:AppLive stands for the application Layer assembled above.
Fragment · Type-checked
ts
import { Context, Exit, ManagedRuntime } from "effect"import type { Effect, Layer } from "effect"class Compensation extends Context.Service<Compensation, { readonly approveRaise: (employeeId: number, percent: number) => Effect.Effect<number>}>()("handbook/Compensation") {}declare const AppLive: Layer.Layer<Compensation>const runtime = ManagedRuntime.make(AppLive)export const handleRequest = async (request: Request): Promise<Response> => { // Hop one: the host's signal interrupts the fiber that serves this request. const exit = await runtime.runPromiseExit( Compensation.use((service) => service.approveRaise(42, 0.05)), { signal: request.signal } ) if (Exit.isSuccess(exit)) return Response.json({ baseSalary: exit.value }) // The client went away: nobody reads this response, but it must not be logged as a fault. if (Exit.hasInterrupts(exit)) return new Response(null, { status: 499 }) return new Response(null, { status: 500 })}export const shutdown = () => runtime.dispose()
For serverless and edge hosts, prefer the HTTP adapter's layer-backed Web handler. Retain and call its dispose function; it owns the constructed Layer graph. An HttpRouter-based entrypoint builds its own router inside a layer memo map forked just for that entrypoint, so a shared stateful service — a connection pool, a cache — must be provided outside the entrypoint and passed in, not assembled inside it; otherwise each entrypoint silently gets its own instance. The detailed choices live in HTTP Server.
This compact capstone keeps the same boundaries in one file: Schema values, tagged errors, a repository capability, a use-case service, a replaceable Layer, and one runtime call at the edge.
Example status — Runnable: no ambient declarations or external services are required.
The in-memory Layer is not “test code inside production logic.” It is one implementation of a stable capability. A SQL implementation can replace it without changing Deposits or its callers.
Test the use case with a small Layer graph. Use a fresh in-memory Layer per test when isolation matters; layer(...) deliberately shares one built graph across its whole block. Pick the cheapest seam that proves the behavior: Effect.provideService(Service, fake) for a focused unit test with a ready-made fake, a test Layer when the fake needs state, configuration, or a lifetime, and the live graph only at the application edge.
Example status — Contextual: place this beside the runnable capstone and execute it with Vitest 5 and @effect/vitest.
An application test should prove observable behavior and important lifetime semantics, not merely that a Layer builds. Add focused tests for typed failures, cleanup after interruption, retry decisions, and boundary round-trips where those are part of the contract.
Most production surprises in an Effect application are a policy with two owners: a timeout inside an adapter and around the use case, a second connection pool built by a stray provide, a retry loop in the client and in the workflow. Give each cross-cutting concern exactly one owning value, provide it in one place, and test it through that owner.
Concern
Owning value
Where it is provided
How it is tested
Time
the Clock reference
default at the root; nowhere else
TestClock.layer() plus TestClock.adjust
Recurrence
one named Schedule per operation
passed to Effect.retry / Effect.repeat by the service that owns the operation
virtual time; assert the attempt count
Deployment inputs
one Config program, read during a Layer build
ConfigProvider.layer(...) at the root
ConfigProvider.fromUnknown({ ... })
Capacity
one shared Semaphore or Pool, created in a Layer
the Layer that owns the bottleneck
peak in-flight counter, decremented in Effect.ensuring
Execution
one platform runMain, or one ManagedRuntime per host
Decode unknown input once at each ingress; keep decoded domain values inside.
Define expected errors as specific tagged values. Do not turn every failure into a defect.
Keep pure calculations as functions; use services for replaceable or effectful capabilities.
Give resource acquisition to the Layer that owns its lifetime and verify finalization.
Name and reuse shared Layer values; use Layer.fresh only when a second instance is intentional.
Hide implementation dependencies with Layer.provide; expose only capabilities callers need.
Read config and unwrap secrets at the concrete integration boundary, not in domain logic.
Add spans with Effect.fn("qualified.name"), and log/measure once at the boundary that owns an operation. Reach for the untraced Effect.fnUntraced only inside a hot loop or library-internal helper where the span itself would dominate the cost.
Run the runtime only at an entrypoint, framework adapter, or test edge.
Use one long-lived ManagedRuntime per external host integration and always dispose it.
Forward the host's AbortSignal into every runner call, and Effect's signal into every Promise adapter.
Prefer host runMain for Effect-native processes so signals interrupt the root and close scopes.
Give every acquired handle its own acquireRelease, and decide up front what a failing release means.
Keep one composition root per executable; provide the application Layer once and count acquisitions to prove sharing.
Quarantine platform packages and leaf effect/<area> imports behind small application-owned services, so an upstream rename touches one file and tests provide a fake instead of patching globals. Framework-level unstable modules such as HttpApi or SqlClient are used directly and managed by pinning and re-auditing.
Build a fresh test Layer for isolated tests; use shared Layer test blocks only deliberately.
The essential architecture is small: Schema defines what crosses boundaries; services define what the application can do; Layers decide how and for how long; one outer runtime makes it happen.
Deep DivesPage 58 of 66
Owning Lifetimes — Startup, Readiness, and Shutdown
Behavioral claims marked probed describe the tracked runtime probes; consult the validation results for the current release run.
Every service is three programs: the one that starts it, the one that serves, and the one that stops it. Only the middle one is usually written on purpose. This guide follows one HR-platform service — a raise-approval worker with a payroll database pool, a telemetry exporter, and an intake loop — and makes the other two explicit: who owns each thing, in what order it comes up, what "ready" means, and what a single shutdown looks like on every host.
Effect's boundary rule is "keep it explicit inside, collapse it at an edge that owns the decision". Lifetimes are the second recurring shape, and one reading habit covers Scope in R, the fork variants, Layer sharing, and queue termination alike. For every resource, fiber, and runtime, ask:
Who closes it? Exactly one named scope. "The process, eventually" is not an owner.
What bounds it? A capacity when it fans out, a deadline when it waits.
What runs when it loses? Interruption, a failed sibling, a closed scope — the cleanup path, not the happy path.
A missing answer is a design defect, not a detail to fill in later.
Before any lifecycle code, list every long-lived thing. This is the ledger for the running service:
Thing
Acquired by
Lifetime
Owner scope
Release, and its bound
Proof after release
Telemetry exporter
Telemetry.layer
application
root Layer scope
flush final batch, 3 s
last batch visible downstream
Payroll DB pool
PayrollDb.layer
application
root Layer scope
pool.end(), 5 s, then logged and ignored
a new query is rejected
Intake loop fiber
ApprovalConsumer via forkScoped
application
that Layer's scope
interrupted at once
no job taken after close
Admitted approval jobs
intake loop via FiberSet.run
request
the consumer's FiberSet
drained 10 s, survivors interrupted
FiberSet.size is 0
Export temp file
makeTempFileScoped
operation
Effect.scoped around the export
deleted on scope close
path does not exist
payroll-cli child process
spawner.spawn
operation
scope around the spawn
SIGTERM, forceKillAfter 2 s
process group gone
Readiness flag
Readiness Layer
application
root scope, acquired last
flipped to "draining" first
probe answers "not ready"
Four lifetimes cover almost everything: operation (a temp file, a transaction, a subprocess), request or session (a subscription, an upload, an admitted job), application instance (a pool, a listener, an exporter), and foreign host instance (a plugin's ManagedRuntime). Choose the narrowest one that is still valid:
Do not request-scope something expensive and shareable. A pool per request is a connection storm. It belongs to the application instance.
Do not application-scope request identity. A principal, a tenant, or a trace context stored in a Layer leaks into the next request.
A Layer describes construction; it does not prove the right scope exists. A Layer provided inside a request handler, and not already built by the enclosing graph, is acquired and released once per request. Where it is provided decides its lifetime.
Work that must outlive its request is transferred, never detached. Hand it to a named, Layer-owned supervisor with a capacity and a shutdown path (shown below). forkDetach "so it survives interruption" produces a fiber that nothing closes, bounds, or observes.
Effect.acquireRelease does not pick an owner — it adds Scope to the requirements, and the type stays honest until someone discharges it. Each discharge is a lifetime decision:
Example status — Contextual:openPool and runPayroll stand for application code.
Fragment · Type-checked
ts
import { Context, Effect, Exit, Layer, Scope } from "effect"interface Pool { readonly close: Effect.Effect<void>}declare const openPool: Effect.Effect<Pool>declare const runPayroll: (pool: Pool) => Effect.Effect<number>// Unowned: the requirement says an owner is still missing.const pool: Effect.Effect<Pool, never, Scope.Scope> = Effect.acquireRelease(openPool, (p) => p.close)// Owner = this operation. The pool closes when the payroll run ends, however it ends.const oneRun: Effect.Effect<number> = Effect.scoped(Effect.flatMap(pool, runPayroll))// Owner = the application instance. Layer.effect takes the Scope; the pool lives as long as the graph.class PayrollPool extends Context.Service<PayrollPool, Pool>()("app/PayrollPool") { static layer: Layer.Layer<PayrollPool> = Layer.effect(PayrollPool, pool)}// Owner = something you manage by hand (a session, a tenant). You now owe exactly one close.const session = Effect.gen(function*() { const scope = yield* Scope.make() const sessionPool = yield* Scope.provide(pool, scope) return { sessionPool, end: Scope.close(scope, Exit.void) }})
If Scope reaches your entrypoint's R, do not make the error go away with whatever compiles. Decide which of the three owners above is right.
A service that is half up is worse than one that is down: it holds connections, passes liveness, and serves errors. Treat startup as all-or-nothing, in this order: stay closed to traffic → acquire in dependency order → probe through the assembled graph → install intake → publish ready last.
Layers already implement the transactional part. Dependencies build first; a Layer's release is registered only after its acquisition succeeds; if a later Layer fails, everything already acquired is released in reverse and the build fails with the original error (probed — see the second test below). The same holds when a signal arrives mid-startup: the build is interrupted, acquired resources are released, and "ready" is never published because the readiness Layer was never reached (probed).
Example status — Contextual:createPool stands for a driver.
Fragment · Type-checked
ts
import { Context, Data, Effect, Layer } from "effect"class PayrollDbUnreachable extends Data.TaggedError("PayrollDbUnreachable")<{ readonly cause: unknown}> {}interface DriverPool { readonly query: (sql: string) => Promise<unknown> readonly end: () => Promise<void>}declare const createPool: (url: string) => DriverPoolclass PayrollDb extends Context.Service<PayrollDb, DriverPool>()("app/PayrollDb") { static layer = (url: string) => Layer.effect( PayrollDb, Effect.gen(function*() { const pool = yield* Effect.acquireRelease( Effect.sync(() => createPool(url)), // A finalizer cannot fail, so choose the policy here: bounded, then logged and ignored. (pool) => Effect.tryPromise(() => pool.end()).pipe( Effect.timeoutOption("5 seconds"), Effect.ignore({ log: true }) ) ) // Probe THROUGH what was just built. Failing here closes the pool and fails the whole graph, // before any listener or consumer exists. yield* Effect.tryPromise({ try: () => pool.query("select 1"), catch: (cause) => new PayrollDbUnreachable({ cause }) }) return pool }) )}
One acquireRelease per allocation. The release is attached when acquiresucceeds. An acquire effect that opens a pool and then a lock, and fails on the lock, leaves a pool with no finalizer. Split it in two (the earlier one unwinds when the later one fails) or make the acquire roll back its own partial work. The same rule applies inside a Layer.effect body.
Liveness, readiness, and draining are different questions
Probe
The question
Answer comes from
May it check dependencies?
Cost of a wrong answer
Liveness
Should this process be restarted?
The event loop answers at all
No — a database blip would restart the whole fleet at once
Restart loops, or a wedged process kept alive
Readiness
Should traffic be routed here?
phase === "ready"
Only indirectly: startup already probed them
Requests sent to a process that cannot serve
Draining
Is it finishing, and should it be left alone?
phase === "draining" — not ready, still live
No
New work admitted during shutdown, or a drain cut short by a restart
Model the phase as one value with exactly two writers, and make those writers a Layer that is acquired last and released first:
It becomes "ready" only after every dependency, probe, and intake Layer below it has succeeded.
It becomes "draining" before anything else starts to close, so a load balancer stops routing while the listener still answers.
There is no "stopped" value to store: once the root scope has closed, the only reader left is the host, and what it reads is the Exit.
If your platform needs time to notice "not ready" (a load balancer's deregistration interval), sleep for that interval inside the readiness release. It is the one unconditional wait in the sequence; every other wait ends as soon as the work does.
Closing the root scope is the shutdown. Not a stop() method beside it, not an array of callbacks: one operation, idempotent because a scope closes once. Its sequence is the acquisition sequence reversed, so you design shutdown by designing dependencies — stop intake → drain in-flight work with a bound → interrupt survivors → release resources in reverse order:
Layer.provide and Layer.provideMerge build the provided Layer first, so the consumer depends on the pool and therefore stops before the pool closes.
Inside one Layer, finalizers run in reverse registration order: register the survivor-interrupting owner first, the bounded drain second, the intake fiber last.
Peers inside Layer.mergeAll have no promised order between them. If order matters, express it as a dependency.
Example status — Runnable: the complete service, driven through a scope the program owns so the same graph runs unchanged under NodeRuntime.runMain(Layer.launch(AppLive)).
Self-contained source · Type-checked
ts
import { Context, Effect, Exit, FiberSet, Layer, Queue, Ref, Scope } from "effect"const say = (line: string) => Effect.sync(() => console.log(line))// Application-instance resources: one Layer each, so each has its own finalizer.class Telemetry extends Context.Service<Telemetry, { readonly record: (event: string) => Effect.Effect<void>}>()("app/Telemetry") { static layer = Layer.effect( Telemetry, Effect.acquireRelease( say("telemetry: exporter started").pipe(Effect.as({ record: (_event: string) => Effect.void })), () => say("telemetry: final batch flushed") ) )}class PayrollDb extends Context.Service<PayrollDb, { readonly applyRaise: (approvalId: string) => Effect.Effect<void>}>()("app/PayrollDb") { static layer = Layer.effect( PayrollDb, Effect.gen(function*() { yield* Telemetry yield* Effect.acquireRelease(say("db: pool opened"), () => say("db: pool closed")) return { // "stuck" stands in for a statement that never returns. applyRaise: (approvalId) => approvalId === "stuck" ? Effect.never : Effect.sleep("20 millis") } }) ).pipe(Layer.provide(Telemetry.layer))}// Lifecycle state: written by exactly two places, read by probes and intake.type Phase = "starting" | "ready" | "draining"class Lifecycle extends Context.Service<Lifecycle, Ref.Ref<Phase>>()("app/Lifecycle") { static layer = Layer.effect(Lifecycle, Ref.make<Phase>("starting"))}class ApprovalInbox extends Context.Service<ApprovalInbox, Queue.Queue<string>>()("app/ApprovalInbox") { static layer = Layer.effect(ApprovalInbox, Queue.bounded<string>(16))}// Intake: the owner of every admitted job.const ApprovalConsumer = Layer.effectDiscard( Effect.gen(function*() { const db = yield* PayrollDb const inbox = yield* ApprovalInbox const handle = (approvalId: string) => db.applyRaise(approvalId).pipe( Effect.andThen(say(`job ${approvalId}: applied`)), Effect.onInterrupt(() => say(`job ${approvalId}: interrupted, row lock released`)) ) // Runs 3rd at shutdown: whatever is still in flight is interrupted, and awaited. const inFlight = yield* FiberSet.make() // Runs 2nd: admitted work gets a bounded chance to finish. yield* Effect.addFinalizer(() => FiberSet.awaitEmpty(inFlight).pipe( Effect.timeoutOption("100 millis"), Effect.andThen(FiberSet.size(inFlight)), Effect.flatMap((left) => say(`consumer: drain finished with ${left} job(s) still in flight`)) ) ) // Runs 1st: intake stops, so the set can only shrink. yield* Effect.addFinalizer(() => say("consumer: intake stopped")) yield* Effect.forkScoped( Effect.forever(Effect.flatMap(Queue.take(inbox), (approvalId) => FiberSet.run(inFlight, handle(approvalId)))) ) yield* say("consumer: intake started") }))// Readiness: acquired last, released first.const Readiness = Layer.effectDiscard( Effect.gen(function*() { const phase = yield* Lifecycle yield* Effect.acquireRelease( Ref.set(phase, "ready").pipe(Effect.andThen(say("lifecycle: ready"))), () => Ref.set(phase, "draining").pipe(Effect.andThen(say("lifecycle: draining"))) ) }))const AppLive = Readiness.pipe( Layer.provideMerge(ApprovalConsumer), Layer.provideMerge(Layer.mergeAll(PayrollDb.layer, ApprovalInbox.layer, Lifecycle.layer)))// A host-neutral harness: build the graph in a Scope we own, use it, close it.const program = Effect.gen(function*() { const scope = yield* Scope.make() const context = yield* Layer.buildWithScope(AppLive, scope) const inbox = Context.get(context, ApprovalInbox) yield* Queue.offerAll(inbox, ["apr-1", "apr-2", "stuck"]) yield* Effect.sleep("50 millis") yield* say("host: shutdown requested") yield* Scope.close(scope, Exit.void) yield* say(`host: stopped, phase = ${yield* Ref.get(Context.get(context, Lifecycle))}`)})Effect.runPromise(program)
text
telemetry: exporter starteddb: pool openedconsumer: intake startedlifecycle: readyjob apr-1: appliedjob apr-2: appliedhost: shutdown requestedlifecycle: drainingconsumer: intake stoppedconsumer: drain finished with 1 job(s) still in flightjob stuck: interrupted, row lock releaseddb: pool closedtelemetry: final batch flushedhost: stopped, phase = draining
Read the second half against the ledger: every row's release happened, in the order the dependencies demand, and the stuck job lost its row lock before the pool that holds the connection went away. An in-memory inbox still loses whatever it holds at the end; when that matters, the intake must be durable — see The Durability and Distribution Ladder.
Let the platform runner deliver the signal; application code never calls process.exit(). NodeRuntime.runMain (and the Bun and Deno equivalents) turns SIGINT and SIGTERM into interruption of the main fiber, which closes the root scope. The process exits only after teardown: 0 for success, 130 when the Cause holds only interruptions, otherwise the error's [Runtime.errorExitCode] or 1. A component that ends the program on purpose by interrupting the main fiber can annotate that interruption with Runtime.InterruptExitCode to exit with its own code instead of 130 — see Runtime; a real signal arriving alongside still yields 130.
A repeated signal does not force an exit (probed: SIGTERM, SIGINT, SIGTERM during a slow finalizer still ran it to completion and exited 130). Forced termination is the orchestrator's SIGKILL, which no finalizer survives — so every finalizer needs its own bound.
Add the bounds up. Deregistration wait + drain + child forceKillAfter + pool close + exporter flush must fit inside the platform's grace period (Kubernetes: terminationGracePeriodSeconds, 30 by default) with room to spare.
Two built-in bounds to know.NodeHttpServer stops accepting on scope close, lets in-flight requests finish, and after gracefulShutdownTimeout (20 seconds unless you pass one) interrupts the handlers that remain; the client of an interrupted handler received a 503 (probed). Only interruptible handlers stop there: HttpRouter routes are interruptible unless added with uninterruptible: true, but an effect served directly with HttpServer.serve runs uninterruptibly unless wrapped in Effect.interruptible, and shutdown waits for it past the timeout. Connected WebSocket clients get a 1001 (Going Away) close frame as soon as shutdown starts, and upgraded connections still open when the timeout expires are destroyed. The server waits for connections, not only responses, so a keep-alive client can hold the close open past the last response — about three seconds against a fetch client in the probe — and the budget should assume the full timeout. A scoped child process is awaited without any bound unless the command sets forceKillAfter — see ChildProcessSpawner.
In a container, make sure the signal arrives. A shell-form entrypoint makes the shell PID 1 and Node never sees SIGTERM. Use the exec form or an init that forwards signals.
When Express, Hono, a UI framework, or a plugin API owns invocation, the root scope is a ManagedRuntime, and the same sequence has to be written by hand on the host side, because the host — not a Layer — owns intake. Three probed facts shape the protocol:
dispose() is not a drain. It interrupts every fiber the runtime started while the Layer scope closes — in the probe a request's finalizer was still running when the pool was released. Stop admission and wait for in-flight work first; then dispose. A second dispose() is a no-op, and a run after disposal dies with ManagedRuntime disposed.
The first run pays for the Layer, and a failed build is permanent. The build runs once; its failure is replayed to every later call. Warm the runtime at boot (runtime.runPromise(Effect.void)) so a broken deployment fails its start-up probe, and treat that failure as fatal rather than something the next request retries.
Cancellation crosses two hops.runtime.runPromise(effect, { signal }) turns the host's abort into interruption; inside, Effect.tryPromise((signal) => …) must hand Effect's signal to the SDK. An already-aborted signal still runs the Effect's synchronous prefix, so check signal.aborted before calling the runtime.
Never start an interior detached runner. An Effect.runFork(...) or forkDetach inside a service method, written so that "the audit write survives the request", creates a fiber that shutdown cannot interrupt and that keeps using a pool after the Layer released it. Transfer the work to an owner that outlives the request instead:
Example status — Contextual:deliverAuditEvent stands for the real delivery.
Fragment · Type-checked
ts
import { Context, Effect, Layer, Queue } from "effect"declare const deliverAuditEvent: (event: string) => Effect.Effect<void>class AuditOutbox extends Context.Service<AuditOutbox, { readonly enqueue: (event: string) => Effect.Effect<void>}>()("app/AuditOutbox") { static layer = Layer.effect( AuditOutbox, Effect.gen(function*() { // What bounds it: a full outbox pushes back on requests instead of growing without limit. const pending = yield* Queue.bounded<string>(1_000) // Who closes it: this Layer's scope — the application instance, or the ManagedRuntime. yield* Effect.forkScoped( Effect.forever(Effect.flatMap(Queue.take(pending), deliverAuditEvent)) ) return { enqueue: (event) => Effect.asVoid(Queue.offer(pending, event)) } }) )}
The request returns as soon as enqueue does; the delivery fiber belongs to the Layer, appears in the ledger, and stops in order. Give it the same bounded drain as the consumer above if losing queued events at shutdown is not acceptable.
The business code is the same in every row. What changes is who owns the runtime, when it is disposed, and where cancellation of one unit of work comes from.
Host
Who owns the runtime
When it is disposed
What cancels one unit of work
Node, Bun, or Deno server process
The platform runMain; the root scope is Layer.launch(AppLive)
SIGINT, SIGTERM, or the main Effect ending → scope close → exit code
The server adapter interrupts the request fiber when the client disconnects; scope close interrupts the rest
Serverless or Web-standard handler
Module scope: { handler, dispose } from HttpRouter.toWebHandler
When the platform calls your shutdown hook — possibly never. Design so that losing the isolate loses nothing
A non-persisted pagehide interrupts the main fiber; completion of asynchronous cleanup is not guaranteed
Whatever signal or fiber handle the UI callback holds
CLI
The platform runMain around Command.run
The command finishing, or Ctrl+C
Ctrl+C: interruption, or a typed QuitError inside a prompt
Worker thread
The parent's scope around Worker.run
Parent scope close → close message → five-second grace → terminate() (Node and Bun adapters)
The parent interrupting run; a dead worker fails it with WorkerError
Test
The scope of it.effect or it.layer
End of the test or suite
The test's own interruption, and timeouts driven by TestClock
Before choosing a serverless or edge row, get five answers from the platform: are isolates reused, can invocations overlap, what abort or deadline does a request carry, may work continue after the response, and is a shutdown hook awaited? On such a host the module-level graph amortizes acquisition across invocations of a reused isolate, which is the right trade for a pool — but it must not capture request data, must not assume dispose runs, and must not keep serving after a failed build. A request-owned scope gives deterministic cleanup and is wrong for anything expensive to create. What each host can and cannot promise is tabulated in Platform & Runtime Hosts.
A lifetime claim is testable, and the oracle is always the same: live state before close, terminal state after. Build the graph in a scope the test owns, assert what is up, close the scope, then assert the order and that every acquisition has its release. Use a handshake (Deferred) wherever the test must know work is in flight, and TestClock wherever it must know a bound — a sleep proves neither.
Example status — Runnable in Vitest: all three are tracked runtime examples with @effect/vitest.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Data, Deferred, Effect, Exit, Fiber, FiberSet, Layer, Ref, Scope } from "effect"import { TestClock } from "effect/testing"// A recording resource: the test double for a pool, an exporter, or a listener.const recorded = (events: Ref.Ref<ReadonlyArray<string>>, name: string) => Layer.effectDiscard( Effect.acquireRelease( Ref.update(events, (all) => [...all, `+${name}`]), () => Ref.update(events, (all) => [...all, `-${name}`]) ) )class ProbeFailed extends Data.TaggedError("ProbeFailed")<{}> {}it.effect("releases in reverse order and leaks nothing", () => Effect.gen(function*() { const events = yield* Ref.make<ReadonlyArray<string>>([]) const App = recorded(events, "listener").pipe( Layer.provide(recorded(events, "pool")), Layer.provide(recorded(events, "exporter")) ) const scope = yield* Scope.make() yield* Layer.buildWithScope(App, scope) // Live state BEFORE close: everything is up, nothing has been released. assert.deepStrictEqual(yield* Ref.get(events), ["+exporter", "+pool", "+listener"]) yield* Scope.close(scope, Exit.void) // Terminal state AFTER close: dependents first, and every + has its -. assert.deepStrictEqual( yield* Ref.get(events), ["+exporter", "+pool", "+listener", "-listener", "-pool", "-exporter"] ) }))it.effect("a failed startup releases what it acquired and keeps the first failure", () => Effect.gen(function*() { const events = yield* Ref.make<ReadonlyArray<string>>([]) const Probe = Layer.effectDiscard(Effect.fail(new ProbeFailed())) const App = Probe.pipe(Layer.provide(recorded(events, "pool"))) const exit = yield* Effect.exit(Layer.launch(App)) assert.deepStrictEqual(exit, Exit.fail(new ProbeFailed())) assert.deepStrictEqual(yield* Ref.get(events), ["+pool", "-pool"]) }))it.effect("drains for at most the bound, then interrupts survivors before the pool closes", () => Effect.gen(function*() { const events = yield* Ref.make<ReadonlyArray<string>>([]) const started = yield* Deferred.make<void>() const stuckJob = Deferred.succeed(started, undefined).pipe( Effect.andThen(Effect.never), Effect.onInterrupt(() => Ref.update(events, (all) => [...all, "job interrupted"])) ) const Worker = Layer.effectDiscard( Effect.gen(function*() { const inFlight = yield* FiberSet.make() yield* Effect.addFinalizer(() => FiberSet.awaitEmpty(inFlight).pipe(Effect.timeoutOption("5 seconds")) ) yield* FiberSet.run(inFlight, stuckJob) }) ).pipe(Layer.provide(recorded(events, "pool"))) const scope = yield* Scope.make() yield* Layer.buildWithScope(Worker, scope) yield* Deferred.await(started) // a handshake, not a sleep const closing = yield* Effect.forkChild(Scope.close(scope, Exit.void)) yield* TestClock.adjust("4999 millis") assert.deepStrictEqual(yield* Ref.get(events), ["+pool"]) // still draining yield* TestClock.adjust("1 millis") yield* Fiber.join(closing) assert.deepStrictEqual(yield* Ref.get(events), ["+pool", "job interrupted", "-pool"]) }))
Give each of these its own test: a request that succeeds, fails with a typed error, dies, or is interrupted; a resource that fails to acquire as the first one and as a later one, after earlier resources are already open; a stop signal that arrives mid-startup; shutdown requested twice, or from two fibers at once; a drain that empties in time and one that runs out its deadline; a failing finalizer followed by finalizers that must still run; and a second instance started once the first has fully shut down.
Recording resources are the cheapest of three fidelities, and each proves less than it seems:
Fidelity
Proves
Does not prove
Recording resources (above)
Order, balance, bounds, and that survivors are interrupted
That a real driver, socket, or OS honors the release
Real adapters, test-owned scope
The port can be re-bound, the lock re-acquired, the pool rejects use after close
Signal handling, exit codes, packaging
Built artifact in a subprocess
Readiness flips, SIGTERM drains, the exit code is 130, bundled workers still load
Other operating systems — a POSIX signal test says nothing about Windows
Tests at every level own and close what they open and exit without force flags; a suite that needs --forceExit has found a leak.
Every resource, long-lived fiber, and runtime is a row in a ledger with an owner, a bound, a release, and a proof. No row says "the process".
Scope never reaches the entrypoint's R by accident; each discharge (Effect.scoped, Layer.effect, a hand-made scope) is a chosen lifetime.
One acquireRelease per allocation; every finalizer has a bound and a stated policy for its own failure.
Startup probes through the assembled graph and fails before any intake exists. Readiness is acquired last and released first.
Liveness never checks dependencies. Readiness is false while starting and while draining.
Shutdown is closing one scope: intake stops, in-flight work drains within a deadline, survivors are interrupted and awaited, resources release in reverse.
Order that matters is a dependency, not a convention between mergeAll peers.
The sum of all shutdown bounds fits inside the platform's grace period; child processes set forceKillAfter.
Signals reach the process (exec-form entrypoint), the platform runMain handles them, and application code never calls process.exit().
A foreign host gets one warmed ManagedRuntime, a synchronous admission flag, a forwarded AbortSignal, and one memoized stop → drain → dispose.
No interior runFork or forkDetach; work that outlives a request is handed to a Layer-owned, bounded supervisor.
Lifetime tests assert live state before close and terminal state after, use handshakes and TestClock, and exit without force flags.
Effect Schema is most useful when it owns a complete boundary, not just an isolated validation call. This guide follows one value from untrusted JSON, form, or query input into a domain model, through application logic, and back to a JSON-safe representation.
Carrier — unknown JSON, text, FormData, URLSearchParams, a database row, or an RPC payload.
Codec — a Schema.Codec<Type, Encoded, DecodingServices, EncodingServices> that validates and transforms in both directions.
Domain value — the decoded Type, which application code can trust.
Application logic — services accept domain values and return domain values or typed errors; they do not cast unknown data.
Representation — encoding validates the outbound value and turns it into the exact carrier/storage shape.
The important distinction is Type versus Encoded. Schema.DateFromString has Type = Date and Encoded = string; Schema.FiniteFromString has Type = number and Encoded = string. A plain Schema.Date validates an in-memory Date but does not by itself claim that the wire contains an ISO string.
Answer eight questions before writing the schema
A boundary schema is a small contract. Write the answers down (a comment above the schema is enough) before choosing combinators:
Producer and trust — who creates this input, and why is it trusted or not?
Encoded — the exact wire shape, including which keys may be absent, null, or undefined.
Type — the value application code wants to hold.
Decode behavior — normalization, defaults, and any service the decoder needs.
Encode behavior — what is written back, and what is lost if decoding normalized.
Failure detail — first error or all errors, and whether rejected input may be reported.
Excess-key policy — strip or reject (parse options).
Equivalence — the relation under which a round trip is expected to hold.
Separate schemas for one concept are legitimate when representation or disclosure differs (a public DTO and a persisted row). Join them with a named, tested mapping or a shared field set — never with as, an object spread that happens to type-check, or a duplicated field list.
The same Schema can be run in several styles. Pick at the boundary rather than forcing the whole application into one error representation.
Surrounding code
Runner
Failure shape
Effect program
decodeUnknownEffect / encodeUnknownEffect
typed SchemaError channel
Pure branching
decodeUnknownResult / encodeUnknownResult
Result
Optional probe
decodeUnknownOption or .makeOption
Option
Validated trusted edge
decodeUnknownSync / encodeUnknownSync
throws SchemaError
Promise-only host
decodeUnknownPromise / encodeUnknownPromise
rejected Promise
Prefer the Effect runner inside services. Use a throwing runner only at an edge that already communicates through exceptions, and catch there. A schema whose getters use services or asynchronous work can only run through the Effect runner.
Warning:Effect.sync(() => Schema.decodeUnknownSync(S)(input)) compiles, has error type never, and turns bad input into a defect that no Effect.catchTag("SchemaError", ...) can handle. Malformed input is an expected boundary outcome: keep it in the typed channel with Schema.decodeUnknownEffect.
Suppose an API accepts a grant request as JSON. The external timestamp is text; the domain wants a Date. The identifier is a positive branded integer, and shares are a non-negative safe integer.
Example status — Runnable: the block decodes a JSON request into a typed value.
The decoded type does not contain unknown, and grantedAt is already a valid Date. Invalid JSON, missing keys, a non-integer id, negative shares, and invalid date text all fail in the Schema error channel before business logic runs.
Do not parse with JSON.parse, cast the result, and then validate selected fields later. Schema.fromJsonString(schema) composes parsing and validation into one reversible codec.
Sometimes the transport contract and domain value happen to have the same fields. They still have different responsibilities: a request describes what an external caller may submit; a domain class describes what the application owns after acceptance.
Keep domain-only fields, generated identifiers, and invariants out of the incoming schema. Construct the domain value after policy succeeds.
Example status — Contextual: it uses EmployeeId and CreateGrantRequest from the preceding block.
Fragment · Type-checked with fixture
ts
import { Clock, Effect, Schema } from "effect"const GrantId = Schema.String.check(Schema.isMinLength(1)).pipe( Schema.brand("GrantId"))class Grant extends Schema.Class<Grant>("handbook/Grant")({ id: GrantId, employeeId: EmployeeId, shares: Schema.Natural, grantedAt: Schema.Date, recordedAt: Schema.Date}) {}class GrantPolicyViolation extends Schema.TaggedError<GrantPolicyViolation>()( "GrantPolicyViolation", { employeeId: EmployeeId, reason: Schema.String }) {}const acceptGrant = Effect.fn("acceptGrant")( function*(request: CreateGrantRequest) { if (request.shares === 0) { return yield* new GrantPolicyViolation({ employeeId: request.employeeId, reason: "a grant must contain at least one share" }) } const now = new Date(yield* Clock.currentTimeMillis) const id = yield* Schema.decodeUnknownEffect(GrantId)( `${request.employeeId}:${request.grantedAt.toISOString()}` ) return new Grant({ id, employeeId: request.employeeId, shares: request.shares, grantedAt: request.grantedAt, recordedAt: now }) })
Schema validation answers “does this input have the required shape and local constraints?” Domain policy answers “may this operation happen now?” Keep that distinction visible. A current-budget lookup or uniqueness check is application behavior, not a synchronous field validator.
A database row is a third representation of the same concept, with its own rules: snake_case columns, integer booleans, exact numerics delivered as text, driver-specific timestamps. Two shortcuts cause most storage bugs: using the decoded domain type as the row type (a cast at the driver), and assuming the HTTP encoding is also the storage encoding.
Give the row its own schema wherever naming or representation differs, and reuse the field schemas (ids, brands, checked numbers) so each rule is defined once.
Decode rows inside the repository. A malformed row then fails at the storage boundary — before any service sees it — with a diagnostic that names the field and the rule.
Encode on the way in with the same schema, so the write path cannot drift from the read path.
Example status — Contextual: the block type-checks on its own; selectGrantRows stands for a query supplied by the application.
Fragment · Type-checked
ts
import { Effect, Schema, SchemaTransformation } from "effect"const EmployeeId = Schema.Int.check(Schema.isGreaterThan(0)).pipe( Schema.brand("EmployeeId"))// SQLite-style boolean column: 0 | 1 on disk, boolean in the domain.const BooleanFromBit = Schema.Literals([0, 1]).pipe( Schema.decodeTo( Schema.Boolean, SchemaTransformation.transform({ decode: (bit) => bit === 1, encode: (flag) => (flag ? 1 : 0) }) ))// The row is its own Encoded form: snake_case keys, integer booleans, exact numeric text.const GrantRow = Schema.Struct({ employeeId: EmployeeId, // the same field schema the API contract uses shares: Schema.Natural, strikePrice: Schema.BigDecimalFromString, // NUMERIC as text; never through a float cancelled: BooleanFromBit, grantedAt: Schema.DateFromString}).pipe( Schema.encodeKeys({ employeeId: "employee_id", strikePrice: "strike_price", grantedAt: "granted_at" }))declare const selectGrantRows: ( employeeId: number) => Effect.Effect<ReadonlyArray<unknown>>// Decode inside the repository: a bad row fails here, naming the field and the rule.const findGrants = Effect.fn("GrantRepository.findGrants")( function*(employeeId: typeof EmployeeId.Type) { const rows = yield* selectGrantRows(employeeId) return yield* Schema.decodeUnknownEffect(Schema.Array(GrantRow))(rows) })
Exact numeric text is also bounded: Schema.BigDecimalFromString rejects a scale beyond ±10,000 digits (BigDecimal scale limits), so a hostile "1e-99999999" in a row or request fails as a SchemaError instead of costing a huge allocation later.
SqlSchema wires this decoding into query helpers, and Model derives the select, insert, update, and JSON variants from one definition when the shapes differ only per operation.
Schema.Date validates a runtime Date, but Date is not a JSON value. Schema.toCodecJson(domainSchema) derives a JSON-safe representation for supported values such as Date, BigInt, Uint8Array, maps, sets, classes, and Option. Compose that representation with fromJsonString when the carrier itself is JSON text.
Example status — Contextual: this round-trips the Grant class above through JSON-safe data and JSON text.
Fragment · Type-checked with fixture
ts
import { Schema } from "effect"const GrantJson = Schema.toCodecJson(Grant)const GrantJsonText = Schema.fromJsonString(GrantJson)declare const grant: Grant// Domain Grant -> JSON string. Dates become canonical JSON-safe values.const text = Schema.encodeUnknownSync(GrantJsonText)(grant)// JSON string -> validated Grant instance.const restored = Schema.decodeUnknownSync(GrantJsonText)(text)console.log(restored instanceof Grant) // trueconsole.log(restored.recordedAt instanceof Date) // true
Do not assume JSON.stringify(domainValue) is the inverse of parsing it. Native JSON loses Date, BigInt, Map, Set, class identity, and other domain semantics. A canonical codec states and tests the reversible representation.
Custom declared types can attach a toCodecJson annotation. JSON Schema generation reuses that representation, keeping runtime serialization and published contracts aligned. A bare declaration without a toCodecJson or toCodec annotation still derives: JSON-native values can encode unchanged, while non-JSON values such as URL instances fail with Expected JSON value. JSON Schema generation emits an unconstrained {} for a bare declaration. Derivation alone does not prove a usable representation, so test the encode direction of every custom type.
The domain Schema should not change just because the carrier changes. Derive a carrier codec around it.
FormData and URLSearchParams contain string-like leaves and use bracket notation for nested values. First derive the domain's StringTree codec, then wrap it with the carrier decoder.
Example status — Runnable: modern Node and browsers provide both Web-standard carrier classes.
This same StringTree model powers Config.schema. For plain JSON input, use fromJsonString; for already-parsed unknown JSON, decode the underlying Schema directly. Do not route every carrier through JSON text merely because JSON is familiar.
A codec has a decode and an encode direction. A transformation that lowercases an email address on decode but cannot reconstruct the original spelling is not an isomorphism. That may be fine for an ingress-only parser, but it is a poor choice for a Schema later used to persist or round-trip the value.
Use Schema.decodeTo(target, transformation) for explicit two-way conversion. SchemaTransformation.transform is for total conversion; SchemaGetter.transformEffect is for a direction that may reject or needs a service. When a conversion is honestly decode-only — a digest, a lowercased lookup key — say so with SchemaGetter.forbiddenEncoding as the encode leg, so encoding fails with a clear issue instead of inventing a value. Test both directions for every custom transformation.
Example status — Runnable: a two-way floating-point conversion, not a lossless codec over its full accepted domain.
The sample round-trips, but Schema.Int alone does not make division and multiplication by 100 exact: 9_007_199_254_740_990 cents decodes to 90071992547409.9 and encodes back to 9_007_199_254_740_991. In the other direction, Schema.Finite accepts fractional-cent values such as 1.234, which encode to 123 cents and decode to 1.23. Retain integer minor units throughout, or use BigDecimal with an appropriate string codec for exact decimal money. If using number, constrain and test both domains against the precision you promise; do not infer reversibility from the presence of both functions.
The same ownership question applies to every carrier narrower than its Type: Schema.DurationFromMillis cannot round-trip a nanosecond-precision duration, while DurationFromNanos and DurationFromString can. Pick the codec by the precision you promise (Effect data types at the boundary).
Official guide: Schema Transformations (it may still spell transformEffect as transformOrFail). The official guides track Effect's main branch rather than a specific tagged release, so where they differ, this page and the edition's tagged source win.
High-level Schema runners fail with SchemaError, whose .issue is a structured SchemaIssue tree. Keep that tree while code needs field paths or localization; format it only at the transport/UI edge.
Example status — Runnable: the decoder collects all field failures and returns Standard Schema-style path/message objects.
Use first-error mode for fast machine-to-machine rejection when extra detail has no value. Use { errors: "all" } for forms and batch imports where returning all actionable problems saves a round trip. reportInput can retain rejected values in issues, so enable it deliberately around sensitive data.
Do not catch a decoding failure and replace it with an arbitrary default unless compatibility policy explicitly permits that. Schema.catchDecoding is powerful precisely because it weakens the boundary.
Wording is a separate decision from structure. Put text that belongs to the contract on the schema (message, expected, identifier, messageMissingKey, messageUnexpectedKey — see Custom error messages); put text that belongs to one UI, or translation keys, in the formatter's leafHook / checkHook (SchemaIssue).
Keep "malformed" and "does not match" as different outcomes
Some boundaries both parse a document and evaluate it: a payroll export checked against its declared totals, an HRIS webhook checked against a partner contract. They have two failures with different owners and different policies. Malformed input means the producer is broken — retrying is pointless and the alert goes to the integration owner. A well-formed document that does not match is a business signal — it may be retried after a correction and the alert goes to the domain owner. Collapse both into "validation failed" and bad configuration looks like a failing partner, or the reverse.
Example status — Runnable: the block defines both outcomes and the function that separates them.
Self-contained source · Type-checked
ts
import { Effect, Schema } from "effect"class MalformedPayrollFile extends Schema.TaggedError<MalformedPayrollFile>()( "MalformedPayrollFile", { message: Schema.String }) {}class PayrollTotalsMismatch extends Schema.TaggedError<PayrollTotalsMismatch>()( "PayrollTotalsMismatch", { declaredCents: Schema.Int, actualCents: Schema.Int }) {}const PayrollFile = Schema.Struct({ declaredTotalCents: Schema.Int, lines: Schema.Array( Schema.Struct({ employeeId: Schema.NonEmptyString, netCents: Schema.Int }) )})const acceptPayrollFile = Effect.fn("acceptPayrollFile")(function*(input: unknown) { // Outcome 1: not a payroll file at all. Fix the producer; do not retry. const file = yield* Schema.decodeUnknownEffect(PayrollFile)(input).pipe( Effect.mapError((error) => new MalformedPayrollFile({ message: error.message })) ) // Outcome 2: a well-formed file whose content is wrong. A signal for finance. const actualCents = file.lines.reduce((sum, line) => sum + line.netCents, 0) if (actualCents !== file.declaredTotalCents) { return yield* new PayrollTotalsMismatch({ declaredCents: file.declaredTotalCents, actualCents }) } return file})
Degenerate-but-valid input stays valid: a file with no lines and a declared total of zero is a correct file, not a malformed one. Reserve the malformed outcome for input the schema cannot read.
Schema.toJsonSchemaDocument for value contracts: config validation, structured-output prompts, cross-language codegen of a payload;
Arbitrary.schema (from effect/Arbitrary) for generated test inputs;
Schema.toEquivalence for domain-aware equality;
Schema.toFormatter for readable values;
Schema.toIso for an optic between a Schema value and its isomorphic representation;
Schema.toStandardSchemaV1 for Standard Schema consumers.
Annotations such as title, description, examples, and constraints should live on the definition that owns them. Derived artifacts then change together instead of drifting as parallel documents.
Derive each artifact from the model that owns its facts. A value schema knows a shape; it does not know methods, paths, parameter locations, status codes, per-endpoint errors, security, or media types. Those live on the assembled HttpApi, so the OpenAPI document is projected from it with OpenApi.fromApi, which reuses your schemas for the payload parts. JSON Schema describes the Encoded side, is open to extra properties by default, and names $defs after identifier annotations — see JsonSchema.
Example status — Contextual: it uses CreateGrantRequest from the first example. Generation uses Effect's native Arbitrary module; there is no fast-check bridge.
Fragment · Type-checked with fixture
ts
import { Arbitrary, Effect, Schema } from "effect"const jsonSchema = Schema.toJsonSchemaDocument(CreateGrantRequest)const equivalent = Schema.toEquivalence(CreateGrantRequest)const arbitrary = Arbitrary.schema(CreateGrantRequest)console.log(jsonSchema.schema)console.log(equivalent( { employeeId: 42 as EmployeeId, shares: 10, grantedAt: new Date(0) }, { employeeId: 42 as EmployeeId, shares: 10, grantedAt: new Date(0) }))// checkEffect returns a structured result instead of throwing on falsification.const generationCheck = Arbitrary.checkEffect(arbitrary, Schema.is(CreateGrantRequest), { runs: 100 }).pipe( Effect.map((result) => result._tag === "Passed" ? "ok" : Arbitrary.formatCheckFailure(result)))
Generated examples prove that the arbitrary produces accepted Type values; they do not by themselves prove every business invariant or a decode/encode round trip. Add properties for the claims your codec makes.
Once encoded values are persisted or exchanged with another process, the Encoded side is a durable contract. Treat changes differently:
Adding a required field breaks old data unless decoding supplies a deliberate default.
Renaming a key requires a compatibility transformation or migration.
Changing a tag, representation identifier, or union discriminant changes dispatch.
Tightening a check can make previously valid stored values unreadable.
Changing only the in-memory Type may still change encoding if a transformation changes.
The technique for a changed representation: accept old and new shapes on the encoded side, decode both into the one domain Type, and encode only the new form. A union of codecs does exactly that — every member decodes to the same Type, and because encoding tries members in order, putting the new form first means only the new form is ever written. Pin representative old values as regression fixtures so tightening a check cannot silently orphan stored data.
Example status — Runnable: legacy rows stored whole dollars as a JSON number; current rows store exact decimal text.
Self-contained source · Type-checked
ts
import { BigDecimal, Schema, SchemaGetter } from "effect"const LegacyWholeDollars = Schema.Int.pipe( Schema.decodeTo(Schema.BigDecimal, { decode: SchemaGetter.transform((dollars: number) => BigDecimal.fromBigInt(BigInt(dollars))), encode: SchemaGetter.forbiddenEncoding // the old form is read, never written }))// New form first: encoding tries members in order.const StoredSalary = Schema.Union([Schema.BigDecimalFromString, LegacyWholeDollars])const SalaryRow = Schema.Struct({ employeeId: Schema.NonEmptyString, baseSalary: StoredSalary })const legacy = Schema.decodeUnknownSync(SalaryRow)({ employeeId: "e-1", baseSalary: 185000 })const current = Schema.decodeUnknownSync(SalaryRow)({ employeeId: "e-1", baseSalary: "185000.50" })console.log(Schema.encodeUnknownSync(SalaryRow)(legacy)) // { employeeId: "e-1", baseSalary: "185000" }console.log(Schema.encodeUnknownSync(SalaryRow)(current)) // { employeeId: "e-1", baseSalary: "185000.5" }
For a renamed key, keep the wire name stable with Schema.encodeKeys while the domain name changes, or accept both shapes with the same union technique during a migration window. Use withDecodingDefaultKey for a genuine backward-compatible default, not to hide corrupt input. For long-lived persisted schema descriptions, use SchemaRepresentation with stable identities and the required revivers. For SQL table evolution, pair schema changes with Migrator rather than hoping runtime decoding performs a database migration.
Runnable capstone: request to domain to JSON and back
The capstone decodes a request, applies domain policy, constructs a domain class, encodes it through the canonical JSON codec, and restores the class. It uses Clock so time remains controllable in tests.
Example status — Runnable: copy the block into a TypeScript file and run it with Node 26+.
A boundary test should cover valid decoding, invalid decoding, encoding, round-trip behavior, and compatibility examples. If the codec needs services, provide them in the test just as the application does.
Example status — Contextual: it tests the capstone definitions with @effect/vitest and virtual time.
Fragment · Type-checked with fixture
ts
import { assert, it } from "@effect/vitest"import { Effect, Result, Schema } from "effect"import { TestClock } from "effect/testing"it.effect("round-trips an accepted grant", () => Effect.gen(function*() { yield* TestClock.setTime(new Date("2026-08-12T12:00:00.000Z").getTime()) const grant = yield* accept( `{"employeeId":42,"shares":4000,"grantedAt":"2026-08-12T10:00:00.000Z"}` ) const text = yield* Schema.encodeUnknownEffect(GrantJsonText)(grant) const restored = yield* Schema.decodeUnknownEffect(GrantJsonText)(text) assert.isTrue(restored instanceof Grant) assert.strictEqual(restored.recordedAt.toISOString(), "2026-08-12T12:00:00.000Z") }))it("rejects malformed boundary data", () => { const result = Schema.decodeUnknownResult(RequestJsonText)( `{"employeeId":0,"shares":-1,"grantedAt":"not-a-date"}`, { errors: "all" } ) assert.isTrue(Result.isFailure(result))})
The claim a codec makes is about round trips, and three different laws hide under that name:
Law
Holds when
Notes
decode(encode(t)) is equivalent to t
encoding loses nothing
compare under a named equivalence — Equal.equals for Schema.Class values, or Schema.toEquivalence(schema) — never ===, because decoding builds fresh instances
encode(decode(e)) equals e
decoding does not normalize
false for trimming, URL canonicalization, timestamp precision, legacy-form upgrades; do not demand it there
Idempotence after the first pass: with first = decode(encode(t)), decode(encode(first)) is equivalent to first
for every correct codec
the law worth asserting by default: it tolerates one normalization and still catches drift
Example status — Runnable: a property over schema-derived values; checkEffect returns a structured result instead of throwing.
Self-contained source · Type-checked
ts
import { Arbitrary, Effect, Equal, Schema } from "effect"class ReviewLink extends Schema.Class<ReviewLink>("handbook/ReviewLink")({ employeeId: Schema.NonEmptyString, portal: Schema.URLFromString, openedAt: Schema.DateTimeUtcFromString}) {}const roundTrip = (value: ReviewLink) => Schema.decodeUnknownSync(ReviewLink)(Schema.encodeSync(ReviewLink)(value))const stableAfterFirstPass = Arbitrary.checkEffect( Arbitrary.schema(ReviewLink), (sample) => { const first = roundTrip(sample) const second = roundTrip(first) return Equal.equals(first, second) // true, while first === second is false }, { runs: 100, seed: 11 }).pipe( Effect.map((result) => result._tag === "Passed" ? "ok" : Arbitrary.formatCheckFailure(result)))
A schema-derived generator has two blind spots, and both need hand-written fixtures. It produces valid decoded values, so it can never exercise key omitted → default, an explicit falsy value that must survive, or malformed wire input; keep a handful of named encoded fixtures for those (a bad brand pattern, a malformed URL, an impossible timestamp, an invalid explicit default, one representative row per legacy form). And it knows only the schema: a cross-field business rule must be a schema check, or a residual Arbitrary.filter, which spends the discard budget. Record the seed and the shrunk counterexample when a property fails, and keep a regression example per representation bug. The per-requirement proof table and the four-case minimum are in Testing schemas with TestSchema.
Write down the carrier and the domain Type; choose a Codec when they differ.
Decode unknown input once at ingress and never recover trust with a cast.
Choose the excess-property policy per boundary ("ignore" strips, "error" rejects), pass it at the call site, and test it; use the same choice for generated JSON Schema.
Inside an Effect, decode with decodeUnknownEffect; a throwing decoder wrapped in Effect.sync turns bad input into a defect.
Keep "malformed input" and "valid input that does not match" as separately tagged outcomes.
Use Finite, integer/range checks, and brands where the domain is narrower than JavaScript's primitive.
Keep local shape validation in Schema and stateful business policy in services.
Model request/update/select variants explicitly; do not make one giant optional DTO serve every operation.
Give a stored row its own encoded form, reuse the field schemas, and decode rows inside the repository.
Encode outbound and persisted values through the Schema rather than raw JSON.stringify.
Derive a canonical JSON or StringTree codec for non-native values.
Preserve SchemaIssue until the UI/transport boundary chooses a formatter.
Enable all-errors and rejected-input reporting only where their detail is useful and safe.
Annotate the owning Schema so JSON Schema, docs, generators, and errors share metadata.
Test decode, encode, and round trip independently, including representative old stored values; assert idempotence after the first pass under a named equivalence.
Test every default three ways: omitted, explicit falsy, explicit invalid.
Treat the encoded side of an API, RPC, event, or persisted value as a versioned contract.
The central rule is simple: unknown data becomes trustworthy only by decoding, and domain data becomes portable only by encoding. One Schema should own both directions.
Reliable Effect code does not ask only “did it throw?” It distinguishes an expected domain failure from a defect, an interruption, a timeout, an exhausted retry policy, and a failed alternative implementation. This guide follows one operation through those choices.
An Effect<A, E, R> exposes two channels in its type and two additional runtime outcomes:
Success A — the operation produced its value.
Expected failure E — a domain or integration condition callers are expected to handle.
Defect — an unexpected bug or violated invariant, preserved in Cause rather than E.
Interruption — cooperative cancellation, also preserved in Cause.
Effect.catch and catchTag(s) handle the typed error channel. A Cause with no typed failure — a pure defect or a pure interruption — passes straight through them. A Cause is a flat list of reasons, and when it holds a typed failure and a defect, they do not recover either: the typed failure is turned into a defect and the whole Cause propagates (see Typed recovery and mixed causes). catchCause can see every reason, but reaching for it too early often erases the distinction the runtime is maintaining for you.
Not every unpleasant outcome belongs in E at all: a correct negative answer ("not eligible", "no band on file") is a success value. Designing the error model has the channel-selection table and a worksheet to fill in before writing error classes.
Errors should carry the facts needed to decide recovery. Avoid a single ApplicationError { message } that forces retry, HTTP, and telemetry code to parse text.
Example status — Runnable: this block defines and selectively handles domain errors.
The error union is a protocol. Composing effects infers the union of their E types, and Effect.gen stops at the first failure, so the signature of a use case lists exactly the failures that can still escape it. Keep variants stable at service and transport boundaries, and map low-level errors into domain/integration errors at the layer that owns the dependency — Effect.mapError is the operator for that translation. Do not leak every driver or SDK error through every use case. The cause field makes HrisUnavailable an internal error: a Schema.TaggedError encodes every field, so declaring this class on an HTTP or RPC endpoint would publish the wrapped error's name and message. Translate to a public variant with safe identifiers at that edge.
Route each variant to the layer that decides its policy
Before choosing a catch operator, write down which boundary owns the policy for each variant. For the three errors above:
Variant
Owner
Policy at that owner
InvalidRaise
the API edge
reject the request; never retried
EmployeeNotFound
the use case that knows whether absence is acceptable
recover to an alternative, or let the edge answer 404
HrisUnavailable
the retry boundary around the HRIS call
bounded backoff while retryable, then typed for the caller
a violated invariant
nobody; it is a defect, not a member of E
reported once at the process edge
When one boundary must classify the whole union, make the classification exhaustive so that adding a variant fails compilation exactly where policy must change. Here the retry boundary owns "is this transient?".
Example status — Contextual: the exhaustive classifier drives the retry predicate.
Completeness is mechanical: the compiler proves every tag has a row, not that the row is right. Classifying an error union compares Match.exhaustive, Match.tagsExhaustive, and a satisfies Record<...> table.
Recovery belongs where the fallback has business meaning:
A repository maps “row absent” into EmployeeNotFound because it owns storage semantics.
A use case may turn EmployeeNotFound into a domain alternative if absence is acceptable there.
An HTTP handler maps unhandled domain errors to statuses because it owns transport semantics — a terminal fold, shown below.
The process edge reports any remaining Cause and chooses an exit code.
Every handler should be one of four things: recover (a truthful value for the handled condition), translate (mapError at an abstraction boundary), compensate (undo, then re-fail), or observe. Use tapError or tapCause to observe without recovering. Use Effect.result when the outcome itself is data. Use orDie only when a typed failure is genuinely unrecoverable at and above that boundary; it converts the error into a defect and removes it from E.
Accept orDie only through a gate. All three must hold:
Validated construction makes the failure impossible, or a process owner deliberately makes a startup failure fatal.
No caller could recover, retry, compensate, or translate it.
Nothing else of value can travel in the same Cause: on a typed failure with only interruptions beside it, orDie replaces the whole Cause with one Die and the interruption disappears. (A defect beside the typed failure is kept; the typed failure joins it as a second Die.)
orDie is never a way to shrink a union that is inconvenient to handle.
Example status — Contextual: the application handles only the failure it owns and leaves infrastructure failure typed.
After catchTag, only HrisUnavailable remains in the error channel. That shrinking union is useful evidence: the type shows exactly which policy has and has not been applied.
Selective recovery keeps a workflow alive. The terminal owner does something different: it must produce exactly one ordinary shape — an HTTP response, a CLI summary, a worker acknowledgement — so it folds both channels with Effect.match (or matchEffect when the handlers log or record metrics).
Example status — Contextual: after the fold E is never, which documents that this boundary has accounted for every expected failure.
Lower layers should not fold: a repository that turns HrisUnavailable into a "success" DTO has stolen the retry and status decisions from every caller. The fold sees typed failures only, so a defect still reaches the process edge; matchCause is the variant that also folds defects and interruption, with the same caution as catchCause.
Effect.retry(schedule) re-runs the entire wrapped Effect. It does not roll back external state. Before adding retry, answer three questions:
Is this failure transient?
Is the operation safe to repeat, or protected by an idempotency key/transaction?
What bounds attempts and elapsed time?
A Schedule receives the error as input. Use Schedule.while to reject permanent failures, a backoff for spacing, and upTo or another schedule for a hard bound. upTo({ times: n }) counts recurrences after the initial attempt, so the wrapped Effect may run n + 1 times.
Example status — Contextual: this is a production-shaped retry policy for the HrisUnavailable error above.
Schedule.min([backoff, spaced(cap)]) selects the faster delay while either schedule continues, which caps an otherwise growing backoff. Schedule.max has the opposite continuation rule: it continues only while every schedule continues and selects the slowest delay. Review the Schedule decision table rather than guessing from the names.
Do not put a logging side effect inside the retried operation merely to count retries: it also runs on the first attempt and may duplicate higher-level logging. Schedule.tap observes retry decisions directly.
Build the attempt inside the retried Effect.Effect.retry re-runs an Effect, not a Promise. If a Promise is started once and the retried Effect merely awaits it, every "retry" replays the same settled rejection and the foreign call runs exactly once; call the Promise-returning function inside Effect.tryPromise({ try: (signal) => ... }) so each attempt starts new work. Retry the transient operation, not the whole use case around it.
Effect.retry does not retry a defect. If the Cause that ended the attempt has no typed failure, or holds a Die beside one that the while predicate would accept, Effect.retry stops: a pure defect or interruption passes through unchanged, and in a mixed [Fail, Die] cause the typed failure is converted to a defect before the cause propagates (see Typed recovery and mixed causes). This is almost always correct: a defect is a bug and should not be silently restarted. A typed failure recorded beside an interruption only is still retried like any typed failure. When a crashed attempt should genuinely be retried, decide that explicitly with Effect.catchCause before applying the retry policy. Similarly, Effect.repeat and Effect.schedule now preserve defects raised inside their finalizer steps rather than discarding them.
For simple policies Effect.retry also accepts an options object, { times, while, until, schedule }, as used in the classifier example; Scheduling & Time owns the Schedule API inventory.
A GET-like read is usually naturally repeatable. A payment, email, queue publish, or remote database write is not. If a write can fail after the external system commits but before the caller observes success, a retry can duplicate it.
Example status — Contextual: the stable operation id lets the external service deduplicate repeated delivery.
The downstream system must enforce idempotency for operationId; merely sending the field is not enough. A local SQL transaction can make local writes atomic, but it cannot atomically commit an unrelated remote API. Use an outbox, durable Workflow Activity, or an idempotent remote operation when the crash boundary crosses systems; Transactional write with an outbox works through the local half.
Effect.retry followed by a separate catchTag cannot tell "the policy ran out" from "the first failure was never retryable", and it discards the schedule's output. Effect.retryOrElse(effect, schedule, orElse) states "retry by policy, then degrade" in one combinator: the fallback receives the last typed error and the schedule's final output. It takes a Schedule, not the options object.
Example status — Contextual: after two recurrences the live lookup gives way to the last published snapshot.
Timeout is a cancellation policy. Effect.timeout(effect, duration) interrupts the operation if the deadline wins and fails with TimeoutError; a source failure that arrives before the deadline is preserved unchanged. timeoutOption represents expiry as Option.none — only the expiry, so source failures stay in E; use it when a timeout genuinely means "absent". timeoutOrElse({ duration, orElse }) supplies another Effect, and it finishes interrupting the source, finalizers included, before it evaluates the fallback, so the two never overlap.
Choose the fallback carefully: a timeout does not prove the remote side did nothing. The same idempotency rule applies if the fallback or caller retries a write.
Example status — Runnable: timeout interrupts the loser and the scoped finalizer still runs.
Interruption is cooperative at Effect boundaries. Finalizers are uninterruptible by default so cleanup can finish. Use uninterruptible sparingly around the smallest commit region; a large uninterruptible operation makes shutdown and timeouts unresponsive. uninterruptibleMask lets setup/commit stay protected while restore(effect) re-opens cancellation around slow work. Core Runtime & Execution covers the mechanics, including forwarding the AbortSignal so that an interrupted attempt really stops its network call.
"What bounds attempts and elapsed time?" has two different answers depending on operator order, and production code usually wants both:
timeout before retry is a per-attempt budget. Each attempt is interrupted at its own deadline, and TimeoutError becomes an input to the retry policy — it is retried only if the policy classifies it as retryable.
timeout after retry is a whole-operation budget. It caps the entire sequence, delays included, and interrupts whichever attempt or sleep is in flight when it expires.
Example status — Contextual: a two-second budget per attempt inside a ten-second budget for the operation.
Fragment · Type-checked
ts
import { Cause, Effect, Schedule, Schema } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { operation: Schema.String, retryable: Schema.Boolean }) {}declare const fetchRoster: Effect.Effect<ReadonlyArray<string>, HrisUnavailable>const guardedRoster = fetchRoster.pipe( Effect.timeout("2 seconds"), // per attempt: E is now HrisUnavailable | TimeoutError Effect.retry({ // The policy must say whether a timed-out attempt is worth repeating. while: (error) => Cause.isTimeoutError(error) || error.retryable, times: 3, schedule: Schedule.exponential("200 millis").pipe(Schedule.jittered) }), Effect.timeout("10 seconds") // whole operation, backoff included)
A per-attempt timeout on a write has the same hazard as any other retry of a write: the interrupted attempt may already have committed remotely.
Concurrent Effects can fail together, and finalizers can fail while another operation is already failing. Cause keeps every one of those reasons — typed failures, defects, and interruptions — instead of forcing them into one exception. A Cause<E> is a flatreasons array of Fail, Die, and Interrupt values; there are no sequential or parallel nodes to walk. Cause.combine(left, right) concatenates two causes and drops reasons that are equal by value.
Use Effect.exit when code needs to inspect how an Effect ended without failing. Use Cause.pretty for diagnostics; hasFails / hasDies / hasInterrupts for whole-cause questions; findError (a Result) or findErrorOption (an Option) for the first typed failure, and findDefect for the first defect; and the is*Reason guards when looping over cause.reasons. Cause.squash is a last-mile bridge to an exception-shaped API; it collapses the list to a single value, so do not use it as the application's internal error model.
Example status — Runnable: the value distinguishes typed failure from successful completion without catching defects broadly.
Do not catchCause(() => Effect.void) around a long-running service. That swallows defects and can turn interruption into an accidental restart loop. Recover specific typed failures inside the loop and let unexpected causes terminate the owner. When a boundary does recover at the Cause level, it propagates what it does not own with Effect.failCause(cause) — the same cause, unchanged.
Every typed-channel operator starts from the same lookup: find the first Fail reason in the flat Cause, then look at what sits beside it.
No Fail reason (a pure defect, a pure interruption): the Cause passes through untouched. This is the case people have in mind when they say "catch does not catch defects".
A Fail reason that the selector does not match (catchTag("Other", ...)): the original Cause is re-raised, every reason intact.
A Fail reason beside a Die: the operator does not recover. It converts every typed error to a defect, keeps reason order and any interruptions, and propagates — so reasons [Fail(e), Die(d)] come out as [Die(e), Die(d)] and the handler never runs.
A Fail reason beside interruptions only: the handler runs and its result becomes the entire outcome; the interruption is dropped.
The defect rule applies to Effect.catch, catchTag / catchTags, catchIf, catchFilter, catchReason(s), orDie, orElseSucceed, firstSuccessOf, match / matchEffect, result, option, ignore, and retry (a mixed Cause is not retried; it propagates after the first attempt). mapError is not recovery: it maps every typed error in place and preserves defects, interruptions, and order. catchDefect is the mirror image: it looks for the first Die and, when it recovers, drops a typed failure recorded beside it. Only the firstFail is inspected, so catchTag("B", ...) does not fire for reasons [Fail(A), Fail(B)].
Mixed causes are not exotic. They arise whenever outcomes combine: a failing operation whose finalizer then dies, a concurrent sibling whose cleanup dies while it is being interrupted, an Effect.race in which every contender fails, or an explicit Cause.combine. When the runtime itself combines a typed failure with a defect — a dying finalizer after a failure, or a dying sibling — it records the typed failure as a defect already, so the Cause reads [Die(error), Die(defect)] before any operator sees it.
Migration: In earlier 4.0 releases a handled Fail replaced the whole Cause, so catchTag, result, or retry on a [Fail, Die] cause succeeded and silently dropped the defect. Code that relied on that now sees the crash; recover it deliberately with catchDefect or a guarded catchCause.
Example status — Runnable: one typed failure plus a dying finalizer, handled four ways.
Self-contained source · Type-checked
ts
import { Cause, Effect, Exit, Schema } from "effect"class ExportFailed extends Schema.TaggedError<ExportFailed>()( "ExportFailed", { batchId: Schema.String }) {}// A typed failure whose finalizer then dies: the runtime records both as defects.const exportBatch = Effect.fail(new ExportFailed({ batchId: "b-7" })).pipe( Effect.ensuring(Effect.die(new Error("ledger handle already closed"))))// The same pair built explicitly keeps its Fail reason: [Fail, Die].const mixed = Effect.failCause( Cause.combine( Cause.fail(new ExportFailed({ batchId: "b-8" })), Cause.die(new Error("ledger handle already closed")) ))// 1. Typed recovery: the defect wins, the handler never runs, the error becomes a defect.const notRecovered = mixed.pipe( Effect.catchTag("ExportFailed", () => Effect.succeed("skipped")))// 2. mapError maps the typed error in place and keeps the defect.const mapped = mixed.pipe(Effect.mapError((error) => error.batchId))// 3. Guarded catchCause: recover only when nothing besides typed failures is present.const guarded = mixed.pipe( Effect.catchCause((cause) => Cause.hasDies(cause) || Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.succeed("skipped") ))// 4. catchDefect: an explicit decision to absorb the crash (and the typed failure beside it).const absorbed = mixed.pipe(Effect.catchDefect(() => Effect.succeed("absorbed")))const reasonTags = <A, E>(exit: Exit.Exit<A, E>) => Exit.isSuccess(exit) ? "Success" : exit.cause.reasons.map((reason) => reason._tag).join("+")console.log(reasonTags(await Effect.runPromiseExit(exportBatch))) // Die+Dieconsole.log(reasonTags(await Effect.runPromiseExit(mixed))) // Fail+Dieconsole.log(reasonTags(await Effect.runPromiseExit(notRecovered))) // Die+Dieconsole.log(reasonTags(await Effect.runPromiseExit(mapped))) // Fail+Dieconsole.log(reasonTags(await Effect.runPromiseExit(guarded))) // Fail+Dieconsole.log(reasonTags(await Effect.runPromiseExit(absorbed))) // Success
Practical rules:
Typed handlers cannot swallow a crash, so do not reach for catchCause to "fix" a mixed cause. Use catchDefect or a guarded catchCause (or sandbox) only where absorbing a defect is genuinely the owner's decision, and re-fail with the unchanged cause otherwise. Around plain domain logic, ordinary catchTag is still the right tool.
tapError, tapCause, and tapDefect lose nothing: they re-raise the original Cause after a successful observer.
Never use orDie as union cleanup: it turns expected failures into defects, and on a mixed cause it only adds more defects beside the one you would most want to see.
Effect.sandbox has no unsandbox counterpart (a stale doc comment still names one); restore the ordinary error model with Effect.catch((cause) => Effect.failCause(cause)).
Multiple domain errors are better modeled as data — Effect.validate or Effect.partition — than as several Fail reasons, because typed handlers see only the first.
Roll back partial work with exit-aware finalizers
A release function receives the Exit its scope closed with. That turns a sequence of acquireRelease steps inside one Effect.scoped into an in-process compensating transaction: each step's release undoes its creation only when the scope closes with a failure, and the undo steps run in reverse order of acquisition, so a dependent record is removed before the thing it depends on.
Example status — Runnable: the third step fails, so the ledger entry and then the grant are undone; on success nothing is undone.
A finalizer cannot fail in E. The release of acquireRelease, Effect.ensuring, and Effect.addFinalizer has error type never, so a fallible undo forces a decision up front: log and ignore (Effect.ignore({ log: true })), bound it with a timeout and ignore, or orDie when a failed undo is a bug. Effect.acquireUseRelease and Effect.onExit are the forms whose cleanup may fail in E. Whatever you choose, the original failure is not overwritten: a failing use and a failing release both appear in the resulting Cause, so tests should assert through Effect.exit.
It does not survive process death. This is rung zero of the durability ladder; when the crash boundary crosses systems, use an outbox, an idempotent remote operation, or a durable Workflow with compensation.
Retry repeats the same Effect under the same service graph. Fallback often means trying the same logical operation with a different region, model, replica, or credential set. ExecutionPlan expresses that distinction: each ordered step supplies a Context or Layer and may define attempts, a Schedule, and a predicate.
Example status — Runnable: the primary endpoint is attempted twice, then the same operation succeeds under the backup service.
attempts is per step. onEvent receives ordered start/success/failure events and cannot change the operation's result if the observer itself fails. A Stream execution plan may restart the stream after it already emitted elements; set preventFallbackOnPartialStream: true when mixing elements from two providers would violate the protocol.
Use ordinary catchTag when the fallback is a different value or business path. Use ExecutionPlan when the computation stays the same and the provided implementation changes. Between the two sit the value-level fallbacks: Effect.firstSuccessOf([a, b, c]) tries different effects in order and fails with the last error, Effect.retryOrElse degrades after a policy is exhausted, and Effect.orElseSucceed replaces every typed failure with a value computed from the error — narrow with catchTag first if only one variant should default. All of them act on typed failures only; see Fallback values and ignoring failures.
Retries and fallbacks multiply attempts, so telemetry needs two levels:
One span for the logical operation (Effect.fn("Payroll.recordRaise")).
Attempt events from Schedule.tap or the onEvent option of Effect.withExecutionPlan, tagged with attempt/step metadata.
One terminal log or metric at the boundary that owns the operation.
Avoid logging the same failure in repository, service, handler, and process code. Lower levels should enrich typed errors or spans; the owner decides whether an outcome is noteworthy. Never put secrets or rejected personal data into annotations merely because structured logging makes it convenient.
Pick the narrowest tap for the job: Effect.tapErrorTag("HrisUnavailable", f) observes one member of a tagged union (it also accepts an array of tags), Effect.tapDefect(f) fires only for defects — the natural "report a bug" hook that leaves typed failures alone — and Effect.tapCause(f) sees everything, interruption included. When the observer succeeds, the original Cause is re-raised unchanged. When the observer itself fails, its failure replaces the original one (the signature shows this as E | E2), so keep observers infallible: log, or wrap a fallible metric or audit call in Effect.ignore({ log: true }).
Example status — Contextual: targeted observation that cannot change the outcome.
Fragment · Type-checked
ts
import { Effect, Schema } from "effect"class EmployeeNotFound extends Schema.TaggedError<EmployeeNotFound>()( "EmployeeNotFound", { employeeId: Schema.String }) {}class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { operation: Schema.String, retryable: Schema.Boolean }) {}declare const loadEmployee: ( id: string) => Effect.Effect<{ readonly id: string }, EmployeeNotFound | HrisUnavailable>declare const recordOutage: (operation: string) => Effect.Effect<void, "MetricsDown">const observed = (id: string) => loadEmployee(id).pipe( Effect.tapErrorTag("HrisUnavailable", (error) => // A failing metrics backend must not turn HrisUnavailable into "MetricsDown". recordOutage(error.operation).pipe(Effect.ignore({ log: true })) ), Effect.tapDefect((defect) => Effect.logError("bug in employee lookup", defect)) ) // E is still EmployeeNotFound | HrisUnavailable
The capstone makes the policy order explicit: validate first, run an idempotent remote operation, retry only transient failures, and recover only the expected domain case. A permanent remote failure stays typed for the caller.
Example status — Runnable: the simulated gateway fails twice and succeeds on the third attempt without wall-clock delay.
Validation sits outside write, so invalid input does not consume retry attempts. The stable operation id is part of the simulated remote contract; a real receiver must enforce its uniqueness.
Tests should assert the semantic promise: attempt count, delay progression, cancellation, cleanup, and final error—not merely that “eventually it worked.” @effect/vitest supplies TestClock; fork sleeping work before advancing virtual time.
Example status — Runnable in Vitest: it validates two scheduled retries without waiting two seconds.
Also test a permanent error stops immediately, an exhausted policy returns the last typed failure, interrupting a blocked attempt releases its resources, and an idempotency key stays identical across attempts. Assert each outcome with the matching tool — tag and fields through Exit.findErrorOption for a typed failure, Exit.hasDies for a defect, Exit.hasInterrupts plus the observed cleanup for interruption — as laid out in The three failure buckets.
Keep expected failures in E; reserve defects for bugs and impossible invariants; return a correct negative answer as a success value.
Give error variants decision-relevant fields rather than parseable message strings.
Decide each variant at the layer responsible for its policy, and classify a whole union with Match.exhaustive / Match.tagsExhaustive so a new variant fails compilation there.
Handle an error at the narrowest layer that owns a meaningful recovery; fold with Effect.match only at the terminal boundary.
Use tapError/tapCause for observation and catchTag(s) for recovery; keep observers infallible.
Accept orDie only through the three-condition gate, never to shrink a union.
Remember that typed recovery does not run when a defect sits beside the typed failure: the error becomes a defect and the whole Cause propagates. Absorb a crash only deliberately, with catchDefect or a guarded catchCause.
Retry only classified transient failures, with both attempt and time/delay bounds, and decide whether each timeout is per attempt or for the whole operation.
Prove the whole retried Effect is repeatable or supply enforced idempotency.
Remember that timeout/interruption does not prove a remote write was rolled back.
Keep uninterruptible regions small; place slow waits inside restored interruptibility.
Let scoped acquisition own cleanup and test that interruption runs finalizers.
Decide what a failing cleanup means — finalizers cannot fail in E, so choose log-and-ignore, time-bound-and-ignore, or orDie — and assert through Effect.exit, because a failing use and a failing release both stay in the Cause.
Use exit-aware finalizers for in-process rollback, and a durable mechanism once the crash boundary crosses systems.
Use ExecutionPlan when fallback changes provided implementations.
Preserve every Cause reason internally; squash only at exception-shaped edges.
Emit one logical-operation span, explicit attempt telemetry, and one terminal outcome.
Drive Schedule and timeout tests with TestClock, never real sleeps.
The reliable sequence is: classify the failure, decide whether the operation is repeatable, bound retries, preserve cancellation and cleanup, then choose recovery or a different implementation explicitly.
A worker pool is not merely “start N promises.” It has ownership, capacity, failure, completion, cancellation, and cleanup semantics. This guide builds those semantics from Effect's structured fibers, bounded Queue, Stream, Semaphore, and test services.
Official guides: the Fibers, Queue, and Error Accumulation guides are linked from the sections they illustrate. These track Effect's main branch rather than a specific tagged release, so where they differ, this page and the edition's tagged source win.
Before choosing a combinator, answer these questions in a comment, a design note, or the pull request description. Every later section of this guide is one of these answers turned into code.
Question
What a complete answer looks like
Who owns each fiber, and for how long?
"The batch Effect owns the producer and the workers; all end when it returns or is interrupted."
How much runs at once?
Sequential, a number, or deliberately unbounded — and the number is tied to a scarce dependency ("8 workers; 3 HRIS permits because the vendor allows 3 concurrent calls per tenant")
What is the capacity of every buffer, and what happens when it is full?
"128 jobs; the producer suspends" — or a named loss policy with a metric
Which order is contractual?
Usually only one of input, start, completion, output, or committed order (see below)
Does one failure fail the batch?
Fail fast, or collect per-job outcomes
What do producers, consumers, siblings, and buffers observe on failure, interruption, early completion, and shutdown?
"A producer failure fails the queue; shutdown drains for 30 s, then interrupts"
Is the input finite? Is there one consumer or many?
Decides between forEach, Stream, Queue, and PubSub
If a question has no answer yet, the code will answer it by accident — typically with an unbounded buffer, a detached fiber, or a worker that waits forever.
Start with the shape of the work, not a favorite primitive.
Problem
Default primitive
A finite collection is already in memory
Effect.forEach(items, work, { concurrency })
A source emits over time and one pipeline owns consumption
Stream.mapEffect(work, { concurrency })
Producers and consumers have independent lifetimes
bounded Queue
Every subscriber must see every message
PubSub
One shared external limit surrounds several code paths
Semaphore
One shared limit, but tenants/keys must take fair turns at it
PartitionedSemaphore
Each tenant/key needs its own independent limit
one Semaphore per key
Dynamic tasks must be tracked as a group
FiberSet or FiberMap
Several state changes must commit atomically or wait for change
STM (TxRef, TxQueue, and friends)
Do not build a queue when Effect.forEach already owns the finite list. A queue earns its complexity when enqueueing and processing must be decoupled, when capacity must push back on producers, or when multiple producers share workers.
"Ordered" is five different promises, and most designs need only one of them:
Order
Meaning
Who provides it
Input
The sequence in which work was submitted
The source; a Queue is FIFO
Start
The sequence in which jobs begin executing
A single worker, or concurrency: 1
Completion
The sequence in which jobs finish
Nothing, once concurrency exceeds one
Output
The sequence of results handed to the caller
Effect.forEach and Stream.mapEffect preserve input order in their results even while running concurrently; Stream.mapEffect(…, { unordered: true }) trades that for throughput
Committed
The sequence in which an external system observes writes
Only a serialized writer, a per-key partition, or the external system's own ordering
Ordered output does not require serialized work, so serialize only the boundary whose order is contractual. If raises for one employee must be applied in submission order, partition by employeeId and keep each partition sequential; do not reduce the whole pool to one worker. Test the promise by forcing the opposite: make the first job finish last and assert only the order you actually guarantee.
Effect.forkChild(effect) creates a supervised child fiber. If its parent ends, the child is interrupted; keep and join the Fiber when its result matters. forkScoped ties a fiber to an explicit surrounding Scope. forkDetach moves a fiber to the global scope and is therefore an exceptional choice for work that intentionally outlives its requester.
Name the owner before you pick the fork. Work that must not outlive the current fiber uses forkChild. Work owned by the surrounding Scope — a Layer, a request, a test — uses forkScoped. Work owned by a Scope you were handed uses Effect.forkIn(effect, scope). Work owned by the process uses forkDetach, and only with a documented stop path: if nobody can say who interrupts a detached fiber, it is a leak. A long-lived loop in library code should be returned as an Effect and forked by the caller that owns its lifetime, not started on a root fiber behind the caller's back. The full table is under Fiber.
A fork returns a handle, not a result. Fiber.join re-enters the child's success or failure into the joiner, Fiber.await yields its Exit for supervision and tests, and Fiber.interrupt waits until the child's finalizers have run.
Higher-level concurrency operators already own their children:
Effect.all and forEach start bounded or unbounded children and collect results.
Stream.mapEffect owns per-element Effects and interrupts them when the pipeline stops.
race interrupts the losing branch after the first success; raceFirst uses first completion.
Closing a Scope interrupts fibers forked into it and runs registered finalizers.
Structured ownership means failure and cancellation travel in both directions. If a worker fails the pipeline, sibling work is interrupted unless you deliberately turn each job's failure into a value.
Example status — Runnable: for a known finite batch, this is the whole worker pool.
A bounded Queue suspends an offer when capacity is full. That suspension is backpressure: the producer cannot outrun the memory budget chosen by the application.
Queue.bounded(capacity) suspends producers when full.
A dropping queue rejects new offers with false when full.
A sliding queue accepts new offers and evicts the oldest buffered value.
An unbounded queue never pushes back and can grow with the producer/consumer gap.
For work that must be processed, use bounded. Dropping and sliding are loss policies suitable for telemetry samples or latest-state updates, not hidden performance switches. Suspension also needs a producer that can wait: a synchronous callback calling Queue.offerUnsafe on a full bounded queue gets false, not backpressure. Concurrency & Coordination has the full overflow table and shows how to count what a lossy queue sheds.
Structured does not mean bounded. A perfectly supervised Effect.forEach(employees, recalc, { concurrency: "unbounded" }) still starts one fiber, one HRIS request, and one result buffer per employee. State the active-work bound as a number and derive it from the scarce dependency it protects — pool size, vendor quota, CPU cores — never from what made a benchmark faster. Then estimate what the design can hold in memory at its worst moment:
text
peak retained memory ≈ Σ (capacity × largest item) over: queue storage + operator buffers (Stream.buffer, grouped batches) + per-subscriber PubSub lag + in-flight handlers (concurrency × working set) + sink and transport write buffers
One unbounded seam — an unbounded queue, a Stream.callback without bufferSize, concurrency: "unbounded" over external input — makes the whole sum unbounded. Streaming Ingestion Without Accidental Buffering applies the same equation to a file-ingestion pipeline.
Example status — Runnable: the producer cannot finish its second offer until the consumer frees capacity.
offerAll returns values that were not accepted. For a bounded queue it waits until values can be accepted; dropping queues return rejected values instead.
A job should contain enough stable identity to make processing observable and, if it crosses a durability boundary, idempotent. Keep the queue's in-memory message distinct from a remote or persisted delivery guarantee: an ordinary Queue is lost when the process stops.
Example status — Runnable: Schema makes the job and its expected failure explicit.
If jobs must survive a crash, replace the ingress with PersistedQueue, an SQL outbox, or a durable Workflow. The in-process concurrency pattern can remain similar, but delivery, acknowledgment, and idempotency become durable protocol concerns.
Stream.fromQueue(queue) consumes values with backpressure. Stream.mapEffect(work, { concurrency: n }) owns at most n in-flight jobs. This composition is usually simpler than writing N manual infinite loops, and Stream correctly carries queue completion, failure, and cancellation.
Example status — Contextual:sourceJobs may come from pagination, a file, or another service. The queue bridges its lifetime to processing.
Queue.end stops further offers but preserves buffered values. Stream.fromQueue drains them and ends normally when it observes Cause.Done. Joining the producer surfaces its completion before runWorkers returns.
If processJob fails, Stream.runDrain fails and interrupts remaining in-flight work. Because the producer is a child, it is also interrupted as the parent unwinds; it cannot remain blocked forever trying to offer into an abandoned queue.
As the pipeline grows beyond one function, put the queue's roles in the signatures: producers accept Queue.Enqueue, consumers accept Queue.Dequeue, and only the wiring code holds the full Queue.Queue.offer requires an Enqueue and Queue.take a Dequeue, so the compiler rejects a worker that re-enqueues follow-up jobs behind the scheduler's back or a producer that takes work away from the workers. A Queue is assignable to both roles, so the wiring passes the same value twice.
The reverse direction of failure needs a decision too. A consumer blocked in take learns nothing from a producer fiber that failed. Queue.into(queue) closes that gap: it ends the queue when the producer succeeds and fails the queue with the producer's cause otherwise, so the workers' stream ends with the same typed error.
Example status — Runnable: the job source fails after two jobs; both are processed, then the failure reaches the consumer side.
Self-contained source · Type-checked
ts
import { Cause, Effect, Queue, Schema, Stream } from "effect"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()( "HrisUnavailable", { status: Schema.Int }) {}interface RecalculationJob { readonly employeeId: string}// Write-only role. Success ends the queue; HrisUnavailable fails it.const produce = ( outbox: Queue.Enqueue<RecalculationJob, HrisUnavailable | Cause.Done>) => Effect.gen(function*() { yield* Queue.offerAll(outbox, [{ employeeId: "e-1" }, { employeeId: "e-2" }]) return yield* new HrisUnavailable({ status: 503 }) // the next page of jobs failed to load }).pipe(Queue.into(outbox))// Read-only role. The stream carries the queue's terminal outcome.const work = ( inbox: Queue.Dequeue<RecalculationJob, HrisUnavailable | Cause.Done>, processed: Array<string>) => Stream.fromQueue(inbox).pipe( Stream.mapEffect( (job) => Effect.sync(() => { processed.push(job.employeeId) }), { concurrency: 2 } ), Stream.runDrain )// Only the wiring sees both halves.const program = Effect.gen(function*() { const queue = yield* Queue.bounded<RecalculationJob, HrisUnavailable | Cause.Done>(16) const processed: Array<string> = [] yield* Effect.forkChild(produce(queue)) const outcome = yield* Effect.result(work(queue, processed)) return { processed, outcome: outcome._tag }})console.log(await Effect.runPromise(program))// { processed: [ 'e-1', 'e-2' ], outcome: 'Failure' }
When a worker needs a hand-written loop instead of a Stream, take in a while (true) and end it with Effect.catchIf(Cause.isDone, () => Effect.void); Concurrency & Coordination shows the complete pattern.
Fail fast: let JobFailed stay in the Stream error channel. The first failure ends the pipeline and interrupts sibling work.
Collect outcomes: apply Effect.result per element. Each failure becomes Result.Failure, so the Stream itself can continue.
Do not catch all causes per job. Expected job failures may become values; defects and interruption should still terminate ownership unless the protocol explicitly says otherwise.
Example status — Contextual: this changes only typed job failures into values.
Apply retry inside processJob only when the complete job operation is repeatable. A stable jobId does not create idempotency by itself; the external writer must enforce it. See Failure, Retry, Fallback, and Interruption.
Official guide: Error Accumulation — Effect.validate and Effect.partition are the collection-level counterparts of the per-element Effect.result policy shown here.
Worker count and external-resource capacity are different limits. Eight workers may perform CPU work but share only three outbound HRIS permits. A Semaphore around the HTTP call lets unrelated call sites obey the same limit.
Example status — Contextual: the permit is released on success, typed failure, defect, or interruption.
Use one semaphore value shared by all callers that participate in the limit. Constructing a semaphore inside every job gives each job its own permits and enforces nothing. Hold the permit around the scarce call only — callHris, not the parsing and mapping around it — so that work which does not consume the quota never waits for it. Waiters are served in order: a later take does not overtake an eligible queued request, though a smaller request may still go ahead of a larger one that cannot be satisfied yet.
Use PartitionedSemaphore when tenants or keys share one permit pool but must take fair turns at it: released permits go round-robin to the waiting partitions, completing one waiter before rotating to the next, so one busy department cannot starve the rest and multi-permit waiters in different partitions cannot deadlock each other. It does not give each key its own ceiling; for independent per-tenant limits keep one Semaphore per key.
Use a Ref for one atomic counter or snapshot. Use SynchronizedRef when computing the new value itself is effectful and must be serialized. Use STM when a decision reads and updates multiple pieces of transactional state, or must wait until a state predicate changes.
For example, “take one job, reserve its department budget, and decrement capacity atomically” is not safely expressed as three independent Ref updates. A TxQueue and TxRef can participate in one Effect.tx. Keep network and logging effects outside the transaction because STM may rerun its body before commit.
Queue termination APIs encode different operational policies:
Operation
New offers
Buffered values
Terminal outcome
Queue.end
rejected
drained
normal Cause.Done completion
Queue.fail(error)
rejected
drained
typed failure after drain
Queue.interrupt
rejected
drained
interruption after drain
Queue.shutdown
rejected
discarded immediately
interruption immediately if open; preserves an existing closing cause
Queue.end signals that no more work will arrive; it does not wait for buffered work to finish. Consumers drain it, and Queue.await waits until the queue reaches its final Done state. Use shutdown for emergency cancellation where abandoning buffered work is intentional.
Treat termination as a protocol with named roles, decided when the queue is created:
One owner creates the queue and the worker fibers, and the same owner's scope ends them. A queue created in one Layer and drained by fibers forked somewhere else has no one responsible for its last message.
One party signals the end — normally the producer, through Queue.end, Queue.fail, or Queue.into. A producer that can fail without telling the queue leaves consumers blocked in take until something interrupts them.
Shutdown distinguishes producers from consumers. On an open queue, Queue.shutdown interrupts pending take and Queue.await callers. Their andThen steps do not run, and joining them re-raises interruption; use Effect.onExit and Fiber.await to observe it. Pending single offers instead succeed with false; batch offers return their unaccepted suffix. A queue already closing via end/fail retains that terminal cause.
Example status — Runnable: the watcher's follow-up step is skipped, its onExit hook runs, and Fiber.await reports the interruption as data.
Official guide: Queue — its shutdown and await sections show the same interruption from the waiting fiber's side (the guide predates Queue.end / Queue.fail and the Cause.Done protocol in the table above).
For process shutdown, stop ingress first, end or interrupt the queue according to policy, wait for the pipeline within a deadline, then let outer Scope closure interrupt anything still running. If abandoning an in-memory job would violate the product contract, the job needed durable storage before shutdown began.
Track dynamic work only when it is truly dynamic
FiberSet owns an open-ended group of fibers and removes them as they complete. It is useful when tasks arrive from callbacks or subscriptions and cannot be represented as one forEach call. Closing its Scope interrupts remaining members. awaitEmpty waits until no tasks remain but does not report their failures; join reports the first non-interruption failure but does not mean “all succeeded.” Race the two when either successful completion or failure must finish the group.
Example status — Contextual: every submitted notification is supervised by the surrounding Scope.
Prefer a Queue when tasks need admission capacity or ordering. A FiberSet supervises work already admitted; it is not itself a backpressure mechanism.
When dynamic tasks are keyed — at most one recalculation per employee — use FiberMap. By default FiberMap.run(map, key, effect) interrupts the fiber already registered under that key and replaces it ("latest request wins"). Pass { onlyIfMissing: true } to keep the running fiber and ignore the new request instead ("first request wins"). See FiberMap.
Runnable capstone: bounded admission and bounded execution
The capstone has an independently forked producer, a two-item queue, two concurrent workers, per-job typed outcomes, and counters proving that execution never exceeds the worker limit.
Example status — Runnable: copy it into a TypeScript file and run with Node 26+.
Effect.result catches only the typed JobError channel. A defect or interruption still terminates the pipeline. The finalizer decrements inFlight on every exit, so the operational counter does not leak when processing fails or is canceled.
Do not test concurrency with wall-clock sleeps. Use a bounded queue, Deferred/Latch, and TestClock to put fibers in known states, then assert admission, in-flight limits, interruption, and finalization.
Example status — Runnable in Vitest: the first assertion proves admission backpressure; the second proves queue shutdown unblocks the producer.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Exit, Fiber, Queue } from "effect"it.effect("backpressures a producer and cancels it on shutdown", () => Effect.gen(function*() { const queue = yield* Queue.bounded<number>(1) const producer = yield* Queue.offerAll(queue, [1, 2, 3]).pipe( Effect.forkChild ) yield* Effect.yieldNow assert.isUndefined(producer.pollUnsafe()) assert.strictEqual(yield* Queue.size(queue), 1) assert.strictEqual(yield* Queue.take(queue), 1) yield* Effect.yieldNow assert.isUndefined(producer.pollUnsafe()) // 2 buffered; 3 still blocked yield* Queue.shutdown(queue) const exit = yield* Fiber.await(producer) assert.isTrue(Exit.isSuccess(exit)) if (Exit.isSuccess(exit)) { assert.deepStrictEqual(exit.value, [3]) // the unaccepted remainder } }))
Also test fail-fast versus collect-outcomes policy, the exact maximum concurrent count, normal end draining every accepted job, and Scope closure running each job's cleanup. For retrying workers, use TestClock and assert the attempt timeline and stable idempotency key, as in Recipe: Typed Retry with TestClock.
Three techniques make these tests deterministic rather than lucky:
startImmediately instead of a yieldNow guess.Effect.forkChild(effect, { startImmediately: true }) runs the child synchronously up to its first suspension before the fork returns, so "is the producer already blocked on offer?" has a definite answer. With the default options the child has not run at all when forkChild returns.
A rendezvous for racy interleavings. To prove a lost-update bug (or its fix), make every fiber announce its arrival, open a Deferred when the last one arrives, and have all of them wait on a gate the test opens. The contested step then happens on every run, not one run in a thousand. Deferred and Latch are the building blocks.
Capacity 1 on purpose. Large buffers hide deadlocks and ordering assumptions; a one-slot queue exposes them on the first run.
Example status — Runnable in Vitest: interrupting a blocked consumer must not leave a stale waiter that swallows the next job.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Fiber, Option, Queue } from "effect"it.effect("an interrupted taker does not steal a later job", () => Effect.gen(function*() { const queue = yield* Queue.bounded<string>(1) // Parked in take before forkChild returns — no yieldNow needed. const abandoned = yield* Queue.take(queue).pipe( Effect.forkChild({ startImmediately: true }) ) assert.isUndefined(abandoned.pollUnsafe()) yield* Fiber.interrupt(abandoned) yield* Queue.offer(queue, "cycle-2026:e-42") // The job is still there for a live consumer, exactly once. assert.strictEqual(yield* Queue.take(queue), "cycle-2026:e-42") assert.isTrue(Option.isNone(yield* Queue.poll(queue))) }))
For peak-in-flight assertions, decrement the counter in Effect.ensuring, as the capstone does; a counter decremented only on the success path reports a false maximum as soon as one job fails. Grow a concurrent component in stages — interruption plus finalizer, then bounded fan-out with counters, then the queue drain — so that a red test points at one idea.
Write the execution policy — owners, bounds, overflow, order, failure, shutdown — before choosing combinators.
Use forEach for an owned finite batch; introduce Queue only for independent lifetimes or admission control.
Bound both buffered capacity and in-flight execution; they solve different problems.
Derive every bound from the scarce dependency it protects, and use "unbounded" only where the collection itself is the bound.
Choose dropping/sliding only when losing work is an explicit domain policy, and export a metric for what is shed.
Promise only the order the contract needs; serialize that boundary, not the whole pool.
Put Queue.Enqueue and Queue.Dequeue in signatures; keep the full Queue in the wiring.
Make producer failure a terminal queue signal (Queue.fail, Queue.into) so consumers never wait forever.
Keep producer fibers supervised and join them when their outcome matters.
Let Stream own concurrent worker Effects and propagate cancellation.
Decide explicitly whether one typed job failure fails the batch or becomes a Result value.
Let defects and interruption escape per-job recovery unless the protocol explicitly owns them.
Share one Semaphore around the actual constrained resource.
Use Ref for one atomic value and STM for multi-value atomic decisions.
End to drain normally; interrupt to drain then cancel; shut down only to discard immediately.
Stop ingress before draining during process shutdown.
Persist jobs before admission when losing accepted work across restart is unacceptable.
Track open-ended work with FiberSet only after admission has been controlled.
Test fiber states with coordination primitives and virtual time, never timing guesses.
The governing rule is: every fiber has an owner, every buffer has a capacity, every failure has a policy, and every shutdown says whether accepted work drains or is abandoned.
This guide uses @effect/vitest, Vitest 5, TypeScript 7 strict mode, and the test services shipped by the same Effect release.
An Effect test should exercise the same program description as production while replacing only its boundary Layers. That means testing values, typed failures, required services, time, interruption, and resource lifetime without putting runPromise, global mocks, or real sleeps inside application code.
Examples are labelled Runnable when they form a complete test or Node program, Contextual when a local module is intentionally imported, and Illustrative when the code shows architecture rather than a copy-ready file.
A test is an argument, and an argument has a conclusion and a scope. Before writing one, state what it will establish and what it deliberately leaves open. Seven lines are enough:
Question
Example answer for "a conflict stops the notification"
Claim — which observable invariant?
when save fails with ApprovalConflict, send is never called
Boundary — a pure function, a service, a real adapter, or the packaged build?
service: ApprovalService.layer over two replaced boundaries
Channels — which of success, typed failure, defect, interruption, cleanup matter?
typed failure only; a defect must fail this test, not satisfy it
Replaced vs live — which requirements are fakes?
ApprovalRepo and ApprovalNotifier are fakes; nothing is live
Owners — who owns scopes, fibers, ports?
the per-test Scope from it.effect; no fibers, no ports
Coordination — which event proves each phase was reached?
none needed: the program is sequential
Oracle — what is inspected, including after close?
the Exit and the notifier's call counter
The eighth line is the one most often skipped: what this test does not prove. Here: that the real repository raises ApprovalConflict on a duplicate key, or that the real notifier is reachable. Writing that line is what stops a green service test from being quoted as evidence about a database.
Each step on the fidelity ladder yields a different kind of evidence, and a lower step never verifies a higher boundary:
Step
Evidence it gives
It does not prove
Type check plus Effect diagnostics
the contract is coherent: E, R, and laziness mistakes are absent
that anything behaves correctly when run
Pure test
a transformation or constructor is right for the inputs tried
how it composes with effects, time, or failure
Service test with replacement Layers
orchestration, typed failures, interruption, and cleanup of your code
that an adapter speaks its dependency's real protocol
Real-adapter test against a real fixture
the adapter's queries, codecs, error mapping, and cancellation
that the whole graph wires together
Application-graph test with the production Layers
the graph builds, acquires once, and releases
that the packaged entry point starts, reports readiness, and exits cleanly
Built-artifact test
the thing you ship starts, serves, and shuts down
production load, data, and network conditions
Classify a test by the boundary it crosses, not by the technology it names: an in-memory filesystem service makes a service test, and calling a router in memory does not show that a server binds or releases a port. "It type-checks", "the tests pass", and "the behavior was verified" are three different claims; report the one you actually have.
When the unit under test already exists — a Promise-based service you are about to migrate — the first test pins what it does today, including behavior you intend to change. Characterization tests record operational facts that a signature cannot: whether the caller is acknowledged before a follow-up settles, whether assembling the module already starts I/O, whether cleanup runs, how many downstream calls one request fans out to.
Illustrative — a characterization test for a legacy Promise function:
Fragment · Type-checked
ts
import { assert, it } from "@effect/vitest"// The legacy unit, exactly as it is today. Characterization never edits it.declare const submitRaise: ( raise: { readonly employeeId: string; readonly amount: number }, deps: { readonly writeAudit: (employeeId: string) => Promise<void> }) => Promise<"accepted">it("characterization: the caller is acknowledged before the audit write settles", async () => { let releaseAudit = (): void => {} const auditGate = new Promise<void>((resolve) => { releaseAudit = resolve }) let auditStarted = 0 let auditSettled = false const result = await submitRaise({ employeeId: "emp-42", amount: 4_200 }, { writeAudit: () => { auditStarted++ return auditGate.then(() => { auditSettled = true }) } }) assert.strictEqual(result, "accepted") assert.strictEqual(auditStarted, 1) // fan-out: exactly one audit write is started assert.isFalse(auditSettled) // ordering: acknowledged while the write is still in flight releaseAudit()})
Use latches and counters, never elapsed milliseconds. The manually resolved auditGate makes "before" and "after" exact; a setTimeout-based inference turns the characterization itself into a flake.
Do not repair production code while characterizing. A surprising result — here, a fire-and-forget audit write — is a finding to record, not a bug to fix in the same change.
After the migration, edit these same assertions to the repaired contract. If the Effect version must finish the audit write before acknowledging, assert.isFalse(auditSettled) becomes the opposite claim, and that one-line diff is the documented behavior change.
This is only the testing half of the brownfield strategy. Adopting Effect in an Existing TypeScript Codebase covers the order of migration, keeping one place where Promise meets Effect, and what to leave alone.
Suppose an approval service must save a decision, notify the employee, and retry a transient notification. Its business program depends on two services; it does not know whether either service is live, in-memory, or deliberately failing.
The important testing boundary is the environment of ApprovalService.layer: provide ApprovalRepo and ApprovalNotifier, then test the public approve operation. Avoid mocking internal combinators such as Effect.retry or Layer.provide; doing so tests a different program.
Never mock the effect module itself. A module mock that makes production code compile or pass hides a wrong API call behind a stub that agrees with it. Replace capabilities instead, each through the seam Effect already provides:
To control
Replace
How
an application dependency
its Context.Service
a test Layer, or Effect.provideService for one call
time
Clock
TestClock, installed by it.effect
randomness
Random
Random.withSeed("…") for a repeatable sequence — see Random
configuration
ConfigProvider
ConfigProvider.layer(ConfigProvider.fromUnknown({ … })) — see ConfigProvider
console output
Console
TestConsole, installed by it.effect
log records and spans
Logger, Tracer
an in-memory logger or tracer, shown later in this guide
In a real test suite, expose a dedicated state service when assertions must inspect the fake. Do not reach into private implementation state or use an untyped object cast merely to satisfy a service tag.
A fake that returns canned data proves the workflow can succeed. Three more properties make it prove the seam is real and keep it honest under retry and virtual time:
Property
Rule
The mistake it catches
Spy
record what was received; assert exact forwarding and call count, and — when a live implementation is reachable in the test — that its counter stayed at zero
a workflow that ignores its injected dependency, or calls it twice
Lazy
choose and consume the next scripted answer when the returned Effect runs, not when the method is called
Effect.retry re-runs the same Effect value; an eager fake captured attempt one's answer and never serves the scripted recovery
Clock-driven
simulate latency with Effect.sleep, never setTimeout
TestClock.adjust cannot move a native timer, so timeouts become untestable and the fake ignores interruption
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Context, Effect, Fiber, Layer, Queue, Ref, Schedule, Schema } from "effect"import { TestClock } from "effect/testing"class HrisUnavailable extends Schema.TaggedError<HrisUnavailable>()("HrisUnavailable", {}) {}class HrisClient extends Context.Service<HrisClient, { readonly salaryOf: (employeeId: string) => Effect.Effect<number, HrisUnavailable>}>()("app/HrisClient") {}// A scripted spy. `received` records every call and doubles as a phase signal.const makeScriptedHris = (script: ReadonlyArray<"down" | number>) => Effect.gen(function*() { const received = yield* Queue.unbounded<string>() const remaining = yield* Ref.make(script) const layer = Layer.succeed(HrisClient, HrisClient.of({ salaryOf: (employeeId) => // Lazy: everything below happens when the returned Effect runs, // so every retry attempt consumes its own script entry. Effect.gen(function*() { yield* Queue.offer(received, employeeId) yield* Effect.sleep("200 millis") // latency lives on Effect's clock const next = yield* Ref.modify(remaining, (all) => [all[0], all.slice(1)] as const) if (next === undefined || next === "down") return yield* new HrisUnavailable() return next }) })) return { layer, received } as const })const salaryWithRetry = Effect.gen(function*() { const hris = yield* HrisClient return yield* hris.salaryOf("emp-42").pipe( Effect.retry(Schedule.spaced("1 second").pipe(Schedule.upTo({ times: 2 }))) )})it.effect("the retry observes the scripted recovery", () => Effect.gen(function*() { const hris = yield* makeScriptedHris(["down", 120_000]) const fiber = yield* salaryWithRetry.pipe(Effect.provide(hris.layer), Effect.forkChild) assert.strictEqual(yield* Queue.take(hris.received), "emp-42") // attempt 1 is in flight yield* TestClock.adjust("200 millis") // latency elapses: HrisUnavailable yield* TestClock.adjust("1 second") // retry spacing assert.strictEqual(yield* Queue.take(hris.received), "emp-42") // attempt 2 is in flight yield* TestClock.adjust("200 millis") assert.strictEqual(yield* Fiber.join(fiber), 120_000) assert.strictEqual(yield* Queue.size(hris.received), 0) // exactly two calls, no third }))
Rewrite salaryOf so that it picks script[i++] in the method body and returns Effect.fail(...) or Effect.succeed(...) directly, and the same test fails: the method is called once, the retried Effect fails every time, and the counter never passes 1. That eager version still passes every test that does not retry, which is why the property has to be designed in rather than discovered.
it.effect runs the returned Effect, supplies TestClock and TestConsole, opens a Scope, and closes it after the test. Return the Effect directly; do not call a runner inside the test.
The test proves ordering because that ordering is part of the behavior. A test that only asserts success would not detect a notification sent before persistence.
Expected failures belong in the E channel. Convert the result to data and inspect its tag; do not catch an arbitrary JavaScript exception around a runner.
Contextual — add to test/approval.test.ts:
Fragment · Type-checked with fixture
ts
import { assert, it } from "@effect/vitest"import { Effect, Layer, Result } from "effect"import { ApprovalConflict, ApprovalNotifier, ApprovalRepo, ApprovalService} from "../src/approval.ts"it.effect("does not notify when persistence rejects the approval", () => Effect.gen(function*() { let notified = false const boundaries = Layer.merge( Layer.succeed(ApprovalRepo, ApprovalRepo.of({ save: (approval) => Effect.fail(new ApprovalConflict({ employeeId: approval.employeeId, cycleId: approval.cycleId })) })), Layer.succeed(ApprovalNotifier, ApprovalNotifier.of({ send: () => Effect.sync(() => { notified = true }) })) ) const application = ApprovalService.layer.pipe( Layer.provide(boundaries) ) const result = yield* ApprovalService.pipe( Effect.flatMap((service) => service.approve({ employeeId: "emp-42", cycleId: "fy27", amount: 4_200 })), Effect.provide(application), Effect.result ) assert.isTrue(Result.isFailure(result)) if (Result.isFailure(result)) { assert.strictEqual(result.failure._tag, "ApprovalConflict") } assert.isFalse(notified) }))
Use Effect.exit instead when the assertion needs the full Cause, including defects and interruption. A typed failure assertion should not accidentally accept a defect.
Three operators bring a failure into an assertion, and they differ in what a wrong outcome does to the test:
Operator
Yields
If the Effect unexpectedly succeeds
Sees defects and interruption
Effect.flip
the error E as the success value
the flipped Effect fails, and so does the test
no — they still fail the test
Effect.result
Result<A, E>
you must assert Result.isFailure yourself
no — they still fail the test
Effect.exit
Exit<A, E> with the full Cause
you must assert the failure yourself
yes — use Exit.hasFails, Exit.hasDies, Exit.hasInterrupts
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Exit, Option, Schema } from "effect"class ApprovalConflict extends Schema.TaggedError<ApprovalConflict>()("ApprovalConflict", { employeeId: Schema.String, cycleId: Schema.String}) {}const approveDuplicate = Effect.fail( new ApprovalConflict({ employeeId: "emp-42", cycleId: "fy27" }))it.effect("flip: the failure is the value under test", () => Effect.gen(function*() { const error = yield* Effect.flip(approveDuplicate) assert.strictEqual(error._tag, "ApprovalConflict") assert.strictEqual(error.cycleId, "fy27") }))it.effect("exit: a typed failure, and nothing but a typed failure", () => Effect.gen(function*() { const exit = yield* Effect.exit(approveDuplicate) assert.isTrue(Exit.hasFails(exit)) assert.isFalse(Exit.hasDies(exit)) assert.isFalse(Exit.hasInterrupts(exit)) const error = Exit.findErrorOption(exit) assert.isTrue(Option.isSome(error) && error.value.employeeId === "emp-42") }))
Assert structure, never rendered text. Match on _tag and fields through Result, Exit, or Cause. Cause.pretty output, the message a runner prints for a failed fiber, and SchemaError.message are diagnostics whose wording changes between releases; a snapshot of a whole Cause or stack is the same mistake in bulk.
Prove the post-recovery type as well as the behavior. A handler that compiles is not proof that only the intended variant left E — a broad Effect.catch compiles too. Pin it with expectTypeOf on Effect.Error<typeof recovered>, as shown in Prove laziness and the static contract.
Anything built on Clock—sleep, timeout, retry delay, schedules—uses the virtual clock inside it.effect. Fork sleeping work, advance time, then join it.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Fiber, Ref, Schedule } from "effect"import { TestClock } from "effect/testing"it.effect("retries twice without wall-clock delay", () => Effect.gen(function*() { const attempts = yield* Ref.make(0) const notify = Effect.gen(function*() { const attempt = yield* Ref.updateAndGet(attempts, (n) => n + 1) if (attempt < 3) return yield* Effect.fail("transient" as const) return "sent" as const }).pipe( Effect.retry(Schedule.exponential("1 second")) ) const fiber = yield* Effect.forkChild(notify) yield* TestClock.adjust("1 second") yield* TestClock.adjust("2 seconds") assert.strictEqual(yield* Fiber.join(fiber), "sent") assert.strictEqual(yield* Ref.get(attempts), 3) }))
Use it.live only when real runtime services are the subject of a small integration smoke test. Wall-clock sleeps make ordinary tests slow and flaky.
The test above works because notify reaches its first retry delay within one scheduling turn. TestClock.adjust gives already-forked fibers exactly one turn before it moves time, so a fiber that needs more — an extra yieldNow, a queue hand-off, a second service call — registers its sleepafter the adjustment and the join never completes. Sprinkling Effect.yieldNow between the fork and the adjust is turn-counting: it passes until someone adds a step to the code under test.
The robust pattern is a handshake per sleep boundary. The operation announces each attempt; the test waits for the announcement before each adjustment; and every attempt records the virtual time at which it ran.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Clock, Effect, Fiber, Queue, Ref, Schedule } from "effect"import { TestClock } from "effect/testing"it.effect("notification attempts run at 0 s, 1 s, and 2 s — never early", () => Effect.gen(function*() { const count = yield* Ref.make(0) const attempts = yield* Queue.unbounded<{ readonly attempt: number; readonly at: number }>() const notify = Effect.gen(function*() { const attempt = yield* Ref.updateAndGet(count, (n) => n + 1) yield* Queue.offer(attempts, { attempt, at: yield* Clock.currentTimeMillis }) if (attempt < 3) return yield* Effect.fail("transient" as const) return "sent" as const }) const fiber = yield* notify.pipe( Effect.retry(Schedule.spaced("1 second").pipe(Schedule.upTo({ times: 5 }))), Effect.forkChild ) assert.deepStrictEqual(yield* Queue.take(attempts), { attempt: 1, at: 0 }) yield* TestClock.adjust("1 second") assert.deepStrictEqual(yield* Queue.take(attempts), { attempt: 2, at: 1_000 }) yield* TestClock.adjust("1 second") assert.deepStrictEqual(yield* Queue.take(attempts), { attempt: 3, at: 2_000 }) assert.strictEqual(yield* Fiber.join(fiber), "sent") assert.strictEqual(yield* Queue.size(attempts), 0) // and no fourth attempt }))
Each Queue.take is both a synchronization point and an assertion. It cannot return before the attempt happened, and the recorded at proves the attempt did not run early.
Advance by the full delay, including any jitter you injected; with a jittered schedule, control Random or assert a range.
A test timeout is a safety net, never synchronization. If a test only passes with a longer timeout or a retry: 3 in the runner config, the missing piece is a handshake.
Retry policy — which failures are retried, how the schedule is bounded, what the caller sees after exhaustion — is tested in Recipe: Typed Retry with TestClock and explained in Schedule.
Providing a Layer inside one it.effect builds and releases it for that test. The top-level layer(L) helper instead builds one Layer for the whole block and releases it in afterAll.
Shared mutable fixtures introduce order coupling. Use them for integration resources whose sharing is the point; otherwise provide a fresh Layer per test. Nested it.layer(...) can add a dependent Layer while retaining the outer context.
Isolation has a second axis: which clock the fixture lives on. layer(L) builds L with TestClock and TestConsole already provided, so the Layer itself is constructed in virtual time. That is what you want for an in-memory fake and a trap for a real fixture: a database driver's connect timeout, an HTTP server's readiness poll, or a container wait written with Effect.sleep parks on a clock nobody advances, and the block hangs until the hook timeout. Make the choice explicit:
The shared Layer contains
Build the block with
Why
in-memory fakes and Ref state
layer(L)
application delays stay drivable with TestClock.adjust
a real driver, server, or container
layer(L, { excludeTestServices: true, timeout })
construction, tests, and teardown all run on the live clock
mostly fakes, plus one wall-clock wait
layer(L) and TestClock.withLive(wait)
only that wait leaves virtual time
The it handed to a layer block has no live tester, so the block-level option is the switch. The option table is in Sharing a layer across tests.
For scoped services, test through the Layer that owns the resource. it.effect already supplies a test Scope; adding Effect.scoped around the whole test changes the lifecycle being tested and is normally unnecessary.
Two guarantees are worth a test of their own when a resource matters. A use callback that throws synchronously — before it returns an Effect — still triggers the release, and the exception stays a defect. And when the body fails and the finalizer fails, the resulting Cause keeps both reasons — for example a Fail and a Die — instead of letting the cleanup failure replace the original one, so assert on the reason you care about with Cause.hasFails or Exit.findErrorOption, not on "the" error.
Checking the returned value says nothing about cleanup: a suite can be green while every call leaks a handle. "The test returned" is not a leak oracle either, because the per-test Scope closes after your last assertion. To observe a lifetime, own the Scope yourself and assert twice — the live state while it is open and the terminal state after it closes.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Context, Effect, Exit, Layer, Ref, Scope } from "effect"class HrisConnection extends Context.Service<HrisConnection, { readonly query: (sql: string) => Effect.Effect<string>}>()("test/HrisConnection") {}// A counting Layer: the instrumentation wraps the real acquire/release shape.const countedConnection = (acquired: Ref.Ref<number>, released: Ref.Ref<number>) => Layer.effect( HrisConnection, Effect.gen(function*() { const id = yield* Effect.acquireRelease( Ref.updateAndGet(acquired, (n) => n + 1), () => Ref.update(released, (n) => n + 1) ) return HrisConnection.of({ query: (sql) => Effect.succeed(`${id}:${sql}`) }) }) )it.effect("acquires once, stays open while in use, releases exactly once", () => Effect.gen(function*() { const acquired = yield* Ref.make(0) const released = yield* Ref.make(0) const counts = Effect.all([Ref.get(acquired), Ref.get(released)]) const connectionLayer = countedConnection(acquired, released) assert.deepStrictEqual(yield* counts, [0, 0]) // describing the Layer acquires nothing const scope = yield* Scope.make() const context = yield* Layer.buildWithScope(connectionLayer, scope) const connection = Context.get(context, HrisConnection) yield* connection.query("select 1") yield* connection.query("select 2") assert.deepStrictEqual(yield* counts, [1, 0]) // live: two uses, one acquisition, not released early yield* Scope.close(scope, Exit.void) assert.deepStrictEqual(yield* counts, [1, 1]) // terminal: released yield* Scope.close(scope, Exit.void) assert.deepStrictEqual(yield* counts, [1, 1]) // closing again does not release twice }))
The four assertions reject four different wrong implementations: eager acquisition ([1, 0] before the build), per-call acquisition ([2, 0] while live), early release ([1, 1] while live), and missing or duplicate release after close. Extend the same shape to the exits that matter for the resource:
Exit
What to assert
success, typed failure, defect, interruption
release ran exactly once, and after the last use
partial acquisition — the second of three resources fails to open
the first is released; the failed one is not "released" as if it had been acquired
nested resources
inner releases before outer — assert order only where the order is contractual
repeated close
no second release
Prefer an external probe over a counter wherever one exists: rebind the port that was just closed (and show that binding it before close fails), delete the temporary directory once handles are closed, read the pool's checked-out count, inspect the listener registry. Open-handle detectors are supporting evidence, not proof. When a test claims that a Layer instance is shared rather than rebuilt, check that the test could tell the difference: count acquisitions as above and compare against a Layer.fresh copy, which must acquire again (Layer covers the sharing rules). The full ownership model is in Owning Lifetimes — Startup, Readiness, and Shutdown.
A concurrency bug that appears once in a thousand runs is not under test. Two techniques make the racy schedule happen on every run.
A rendezvous gate. Every fiber reports its arrival at the dangerous point; the last arrival opens allArrived; all of them then wait on a gate that the test opens. Placed between a read and a write, it guarantees that every fiber has read before any fiber writes.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Deferred, Effect, Fiber, Ref } from "effect"// Runs two spenders against one budget, holding both at `betweenReadAndWrite`.const spendConcurrently = ( spend: (budget: Ref.Ref<number>, betweenReadAndWrite: Effect.Effect<void>) => Effect.Effect<void>) => Effect.gen(function*() { const budget = yield* Ref.make(100) const arrived = yield* Ref.make(0) const allArrived = yield* Deferred.make<void>() const gate = yield* Deferred.make<void>() const rendezvous = Ref.updateAndGet(arrived, (n) => n + 1).pipe( Effect.flatMap((n) => n === 2 ? Deferred.succeed(allArrived, undefined) : Effect.void), Effect.andThen(Deferred.await(gate)) ) const fibers = yield* Effect.forEach([1, 2], () => Effect.forkChild(spend(budget, rendezvous))) yield* Deferred.await(allArrived) // both fibers are parked between read and write yield* Deferred.succeed(gate, undefined) yield* Fiber.joinAll(fibers) return yield* Ref.get(budget) })it.effect("a read-then-write spend loses an update; an atomic update does not", () => Effect.gen(function*() { const racy = yield* spendConcurrently((budget, pause) => Effect.gen(function*() { const current = yield* Ref.get(budget) yield* pause yield* Ref.set(budget, current - 10) }) ) const atomic = yield* spendConcurrently((budget, pause) => pause.pipe(Effect.andThen(Ref.update(budget, (n) => n - 10))) ) assert.strictEqual(racy, 90) // deterministic lost update: both read 100 assert.strictEqual(atomic, 80) }))
In application code the rendezvous usually lives inside a fake: the service call that sits between the read and the write is the natural place to park every fiber.
startImmediately.Effect.forkChild(effect) returns before the child has run a single step, so "has it started?" is a race unless you wait for a signal. Effect.forkChild(effect, { startImmediately: true }) runs the child up to its first suspension before returning — after it, a Ref the child sets on entry already reads true, with no yieldNow guess. The same option exists on forkIn, forkScoped, and forkDetach.
For peak-in-flight assertions, increment on entry and decrement in Effect.ensuring, never after the work on the success path, or one failure corrupts every later reading. Structured Concurrency Through a Bounded Worker applies these techniques to a queue-backed worker.
Integrate progressively. Grow a concurrent component in stages — interruption plus finalizer, then bounded fan-out with counters, then a queue worker that drains — and let each test introduce at most two primitives. A red test should point at one idea.
Use example-based tests for named cases and it.effect.prop when the claim applies to all valid values. Schemas can act directly as property arbitraries.
For detailed codec expectations, effect/testing/TestSchema adds decode, encode, construction, arbitrary-generation, and lossless-transformation assertions. Keep a few human-readable boundary cases even when property tests cover the larger domain.
A Schema-derived generator produces valid decoded values, so a green property says nothing about rejection. Keep named encoded fixtures for malformed input, omitted keys that take a decoding default, and representation bugs you have already fixed; put cross-field rules into the schema as a check so the generator can see them; and turn every shrunk counterexample into a permanent example test. What a derived generator cannot test has the table.
Calls through Effect's Console service are captured by TestConsole in it.effect. This does not capture arbitrary console.log calls—which is another reason application code should use Effect services.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Console, Effect } from "effect"import { TestConsole } from "effect/testing"it.effect("emits an auditable approval message", () => Effect.gen(function*() { yield* Console.log("approval saved", { employeeId: "emp-42" }) assert.deepStrictEqual(yield* TestConsole.logLines, [ "approval saved", { employeeId: "emp-42" } ]) }))
logLines is flat: every positional argument from every call becomes one array element.
TestConsole is the seam for Console.*. It is the wrong seam for Effect.logInfo and its siblings: the default logger prints through Console, so a log call does show up in logLines, but as rendered output — a prefix string carrying a time stamp in the machine's local zone and a fiber id, then the message parts, then the annotations object. Assert on log records instead, by installing an in-memory Logger around the Effect under test.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Logger, Redacted, References } from "effect"import type { LogLevel } from "effect"interface LogRecord { readonly level: LogLevel.LogLevel readonly message: unknown readonly annotations: Readonly<Record<string, unknown>>}// Replaces the current loggers for `effect` and returns what they were given.const captureLogs = <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.gen(function*() { const records: Array<LogRecord> = [] const logger = Logger.make<unknown, void>((options) => { records.push({ level: options.logLevel, message: options.message, annotations: { ...options.fiber.getRef(References.CurrentLogAnnotations) } }) }) const value = yield* effect.pipe(Effect.provide(Logger.layer([logger]))) return { value, records } as const })const hrisToken = Redacted.make("hris-token-123")const approveRaise = Effect.gen(function*() { yield* Effect.logDebug("band lookup", { band: "L5" }) yield* Effect.logInfo("raise approved", { token: hrisToken })}).pipe(Effect.annotateLogs({ employeeId: "emp-42" }))it.effect("emits one auditable record, gated by level, without the secret", () => Effect.gen(function*() { const { records } = yield* captureLogs(approveRaise) assert.strictEqual(records.length, 1) // Debug is below the default minimum level assert.strictEqual(records[0]?.level, "Info") assert.deepStrictEqual(records[0]?.annotations, { employeeId: "emp-42" }) assert.notInclude(JSON.stringify(records), "hris-token-123") }))
options.message is the array of arguments passed to the log call. Logger.layer([logger]) replaces the current loggers, so nothing is printed; pass { mergeWithExisting: true } to keep them. To assert on a lower level, provide References.MinimumLogLevel (for example "Debug") around the Effect. Logger documents the production side.
Spans are part of the operational contract — they are how an incident is traced to one approval. Test them with an in-memory Tracer that records every span it creates, and assert structure only: names, parent links, that each span ended, and whether it ended in failure. Never assert ids, timestamps, or durations.
Runnable test:
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Exit, Option, Schema, Tracer } from "effect"class BandViolation extends Schema.TaggedError<BandViolation>()("BandViolation", { employeeId: Schema.String}) {}// A named Effect.fn opens a span with that name around every call.const loadBudget = Effect.fn("MeritCycle.loadBudget")(function*(cycleId: string) { yield* Effect.annotateCurrentSpan("cycleId", cycleId) return 500_000})const applyRaise = Effect.fn("MeritCycle.applyRaise")(function*(employeeId: string) { yield* Effect.annotateCurrentSpan("employeeId", employeeId) return yield* new BandViolation({ employeeId })})const runMeritCycle = Effect.fn("MeritCycle.run")(function*(cycleId: string) { yield* loadBudget(cycleId) return yield* applyRaise("emp-42")})it.effect("a failing child span marks its parent failed, and every span ends", () => Effect.gen(function*() { const spans: Array<Tracer.Span> = [] const tracer = Tracer.make({ span: (options) => { const span = new Tracer.NativeSpan(options) spans.push(span) return span } }) yield* Effect.exit(runMeritCycle("fy27")).pipe(Effect.provideService(Tracer.Tracer, tracer)) const summary = spans.map((span) => ({ name: span.name, parent: Option.isSome(span.parent) && span.parent.value._tag === "Span" ? span.parent.value.name : undefined, failed: span.status._tag === "Ended" ? Exit.isFailure(span.status.exit) : undefined })) assert.deepStrictEqual(summary, [ { name: "MeritCycle.run", parent: undefined, failed: true }, { name: "MeritCycle.loadBudget", parent: "MeritCycle.run", failed: false }, { name: "MeritCycle.applyRaise", parent: "MeritCycle.run", failed: true } ]) assert.strictEqual(spans[2]?.attributes.get("employeeId"), "emp-42") }))
A failed: undefined entry would mean a span that never ended — a leaked span, which is a lifetime bug like any other. Attribute assertions double as a disclosure test: check that the identifying field is present and that nothing secret is. Tracer covers span creation and export.
A passing test is only interesting if a believable wrong implementation would fail it. For each behavior, name the mistakes your team actually makes, then check that at least one assertion turns red for each. This converts "the test passes" into "the test would have caught it".
Plausible wrong implementation
The assertion that rejects it
hard-coded success (Effect.succeed(expected))
a second case with a different expected value; a spy call count of 1
the injected fake is ignored and a live default is used
exact forwarded arguments on the spy, and a live-side counter that stays 0
a step is skipped — input is parsed but never sent
the ordered event log (["saved", "notified"]), not just the result
catch-all recovery swallows a failure that should propagate
an Exit assertion on the variant that must still fail, plus expectTypeOf on E
a believable default is returned after a failed decode
a malformed-input case that must fail with a schema issue
cleanup runs on the success path only (tap plus tapError instead of ensuring)
the lifetime test under interruption, not just success and failure
early or duplicate release
live-state [1, 0] and terminal-state [1, 1] counters, plus a second close
sequential execution where a bound was intended — or unbounded where a bound was required
peak-in-flight counter asserted to equal the bound exactly
an update that is atomic per step but wrong as a whole (read, then write)
the rendezvous test that forces both reads before either write
retry of every failure, including permanent ones
a permanent failure with an attempt counter that must stay at 1
a runner inside the program, or one runtime built per request
the inertness counter (0 before run); one acquisition across many requests
collect everything, then slice
a pull counter on the source: a prefix of n must perform no later reads
rows paired to requests by position
shuffled rows with one id missing and one duplicated
the write happens outside the transaction, or recovery happens inside it
a forced failure after the first write, then a row count of 0
Counters (Ref), latches (Deferred), and recorded virtual time give deterministic evidence for every row; "it returned the right value" distinguishes almost none of them.
Pure tests for data transformations and constructors.
it.effect with small fake Layers for orchestration, errors, time, and cancellation.
Tests with real codecs and in-memory Effect runtimes such as WorkflowEngine.layerMemory, TestRunner.layer, or an MCP server driven through McpTest.makeClient (see McpTest).
A narrow adapter integration test for SQL, HTTP, filesystem, or a provider sandbox.
A small end-to-end smoke test with the production Layer graph.
A built-artifact test that launches what you actually ship.
The same service program should flow through levels two through five. Only its provided Layer graph changes. Level three keeps the real protocol machinery and removes one piece of infrastructure; In-memory test runtimes shipped with Effect lists what each harness keeps and what it cannot show.
Levels one through five import source modules. None of them shows that the package builds, that the entry point wires the graph, that the process reports readiness, or that it exits cleanly — and those are the failures that reach production on a green suite. One lane, kept small, runs the artifact itself:
Build and package exactly as the release pipeline does; test the output, not the source tree.
Launch the real entry point as a child process with temporary configuration: an OS-assigned port, a scratch directory, a throwaway database.
Wait for an explicit readiness event — a health endpoint that answers, or a line the process prints on purpose. Never a fixed delay.
Exercise one success and one failure through the public interface, asserting the external contract: status, body, exit code.
Request graceful shutdown the way the platform will (SIGTERM on POSIX hosts) and enforce an outer deadline. Forced termination is the failure path, never the happy path.
Assert the terminal state: the exit status, and that the port can be rebound, the lock file is gone, and no child process survives.
Add two startup-failure cases: invalid configuration must exit non-zero with an actionable message before anything is acquired, and an occupied port must roll back whatever had already started. Mark signal-based tests as platform-specific and give other hosts an equivalent trigger rather than skipping the lane.
This lane proves
It does not prove
the shipped artifact starts, becomes ready, serves, and releases its resources on shutdown
behavior under production load, real data volume, or real network partitions
An adapter test is only evidence if its fixture is real, isolated, and honest about availability. Hold every real fixture — database, broker, HTTP server, temporary directory — to the same contract:
Rule
Reason
Acquire it through a scoped Layer.
Acquisition, readiness, and teardown get one owner, and the same interruption guarantees as production code.
Name it uniquely per worker: schema, database, directory, and an OS-assigned port.
Parallel workers and a developer's leftover state cannot collide.
Migrate during acquisition and report ready only after a real probe — a query, a request, a bind.
A delay is not readiness; it is a slower race.
Close the Scope before removing the external fixture.
Dropping a database under open connections turns teardown errors into noise that hides real ones.
Never swallow a cleanup failure.
A fixture that cannot be removed is tomorrow's flake; fail loudly now.
Keep logs and diagnostics when a test fails.
The container log is usually the only explanation for a readiness timeout.
Give every test its own disposable database and credentials.
A suite that can reach someone's working database or a production account is not safe to run on any machine, repeatedly.
Required infrastructure that is unavailable fails the lane or marks it visibly incomplete.
import { Context, Effect, Layer, Schema } from "effect"class FixtureError extends Schema.TaggedError<FixtureError>()("FixtureError", { step: Schema.String}) {}class PayrollDb extends Context.Service<PayrollDb, { readonly url: string}>()("test/PayrollDb") {}declare const workerId: string // for example Vitest's pool iddeclare const createDatabase: (name: string) => Effect.Effect<{ readonly url: string }, FixtureError>declare const dropDatabase: (name: string) => Effect.Effect<void, FixtureError>declare const migrate: (url: string) => Effect.Effect<void, FixtureError>declare const probe: (url: string) => Effect.Effect<void, FixtureError>export const PayrollDbFixture = Layer.effect( PayrollDb, Effect.gen(function*() { const name = `payroll_test_${workerId}` const database = yield* Effect.acquireRelease( createDatabase(name), // A failed drop becomes a defect: loud, never swallowed. () => dropDatabase(name).pipe(Effect.orDie) ) yield* migrate(database.url) yield* probe(database.url) // ready means "answered a real query", not "waited a while" return PayrollDb.of({ url: database.url }) }))
Finalizers run in reverse order of acquisition, so a repository Layer built on top of PayrollDb closes its pool before this Layer drops the database; that ordering is what satisfies "close before removing the fixture". Use the block form layer(PayrollDbFixture, { excludeTestServices: true, timeout: "60 seconds" }) so that the acquisition above runs on the live clock.
A suite can be entirely green and entirely uninformative. Audit for these before trusting a result:
False green
How to detect it
an Effect returned from plain it(...) — Vitest never runs it
the floatingEffectInVitest diagnostic; grep for it( callbacks that return Effect.
assertion-free tests, or "does not throw" as the only claim
every test names the invariant it checks; count assertions in review
success-only coverage
for each operation, at least one typed-failure case and, for resourceful code, one interruption case
a fake is declared but never provided, so a live default still answers
a live-side counter that must stay 0, and a spy call count that must not
a broad mock presented as adapter evidence
the adapter has at least one test against a real fixture
a typed client that cannot express malformed wire input
raw-request tests below the typed client for decode failures
an integration suite that skips itself when a dependency is missing
required lanes fail when the dependency is absent; skipped counts are reported and reviewed
every test imports source files, and nothing ever starts the packaged build
the built-artifact lane above
shared mutable Layer state under concurrent tests
per-test Layers, or state designed for interleaving
real sleeps, polling loops, oversized timeouts, blanket retries
TestClock, handshakes, and the flake protocol below
snapshots of whole Causes, stacks, or rendered messages
structural assertions on _tag and fields
A green command that collected zero relevant tests is a failure. Check the script, workspace filters, include and exclude globs, the CI working directory, and environment-gated skips. Run the exact file, then the package command, then the CI-equivalent command, and compare the collected counts — they should differ only in ways you can explain.
On the first failure, keep the evidence: seed, worker id, ports, versions, a fiber dump if you have one, fixture logs, and the phase timeline from your handshakes. Then classify the cause before touching the test:
Cause
Fix
shared state between tests
isolate the Layer, or make the state order-independent
missing readiness signal
add a probe or a handshake
arbitrary timing — real sleeps, turn-counting
TestClock plus a phase handshake
leaked ownership — a fiber or handle from an earlier test
fix the lifetime; add the lifetime test that would have caught it
resource collision — ports, names, directories
unique per-worker names and OS-assigned ports
true external eventual consistency
the only case that may justify a bounded retry, with artifacts kept from every attempt
Quarantine only with a named owner and an expiry date. Build one deterministic reproducer before adding stress repetitions: a thousand reruns of a test that cannot fail deterministically only measure luck.
interruption: an in-flight adapter closes its resource;
schema boundaries: valid payloads round-trip and malformed input fails;
idempotency: repeating the same employee/cycle does not duplicate the durable write;
integration: the real repository Layer honors its transaction and uniqueness contract;
observability: the expected log/span fields identify the operation without exposing secrets.
That plan validates behavior rather than implementation structure. It remains stable when internal combinators are refactored.
Boundary placement is itself testable. Where a check, a bound, or a commit happens is a behavior, and a counter on the far side of the boundary observes it:
Placement claim
Evidence
invalid input is rejected at ingress
the repository fake's call counter stays 0 for a malformed payload
a prefix of a large source reads no more than it needs
a pull counter on the source after take(n)
many requests share one expensive resource
one acquisition across the whole run, from the counting Layer
the durable write commits before the external delivery
the ordered event log reads ["committed", "delivered"]
a cache entry expires when its TTL says so
a lookup counter, with TestClock.adjust to just before and just after the TTL
concurrent callers share one in-flight lookup
the lookup signals "started", the test asserts a count of 1 while callers are parked, then releases it
a batched resolver settles every request
rows returned shuffled, with one id missing and one duplicated: one backend call, caller-order results, no request left hanging
Caching & Batching describes the cache and resolver semantics those last three rows exercise. Finish each item in the plan by writing its "does not prove" line; the gaps that remain are the integration and artifact lanes' job list.
Streaming Ingestion Without Accidental Buffering
Stable stream primitives come from effect; the NDJSON codec used here is the unstable effect/encoding surface and should be version-pinned.
A streaming import is not constant-memory merely because its type is Stream. Constant-memory behavior comes from the whole pipeline: a pull-based source, incremental framing, bounded records, bounded concurrency, bounded batches, and a terminal consumer that does not collect the complete input.
Examples are labelled Runnable, Contextual, or Illustrative. Each code block includes its external imports; contextual files also name their local imports. Use Streaming & Channels for the operator catalog, Schema for boundary decoding, and Platform & Runtime Hosts for filesystem and stdin sources.
For an ingestion pipeline, approximate live memory as:
text
source chunks in flight+ incomplete frame or line+ decoded records in flight+ current database batch+ retries and observability payloads retained by your code
Pull-based back-pressure prevents the source from running arbitrarily far ahead, but operators can weaken that guarantee:
Stream.runCollect retains every output until completion.
Stream.buffer({ capacity: "unbounded" }) explicitly removes a memory bound.
Stream.callback and Stream.fromEventListener buffer without bound by default; nothing in the pipeline's types shows it. Pass bufferSize.
Stream.mapEffect(..., { concurrency: "unbounded" }) permits unbounded in-flight effects. A finite concurrency: n is itself a buffer of n inputs and results.
Stream.grouped(n) retains up to n decoded elements per batch; choose n deliberately.
Stream.buffer and concurrent stages run ahead of demand: a take placed after them does not stop the reads that already started.
a framing decoder must retain an incomplete final record, so an unbounded record is still an unbounded allocation.
retrying a materialized batch keeps that batch alive and may repeat its external effects.
The goal is bounded memory relative to documented maximum chunk, record, batch, and concurrency sizes—not a magical zero-buffer pipeline. Audit a pipeline stage by stage against the Where buffering hides inventory: every row has a default, and several defaults are unbounded or larger than you would choose (groupByKey buffers up to 4096 elements per key and never retires a key unless idleTimeToLive is set).
Network and file chunks do not line up with UTF-8 code points or newlines. Ndjson.decodeSchema consumes byte chunks, carries incomplete text and lines across pulls, parses each completed line, and decodes it through a Schema.
Runnable — Node 26+:
Self-contained source · Type-checked
ts
import { Effect, Schema, Stream } from "effect"import { Ndjson } from "effect/encoding"class EmployeeRow extends Schema.Class<EmployeeRow>("EmployeeRow")({ employeeId: Schema.String, salary: Schema.Finite}) {}const encoder = new TextEncoder()const bytes = encoder.encode( '{"employeeId":"e-1","salary":95000}\n' + '{"employeeId":"e-2","salary":105000}\n')// Deliberately split in the middle of JSON tokens. The decoder, not the// source, owns framing.const source = Stream.make( bytes.slice(0, 11), bytes.slice(11, 43), bytes.slice(43))const program = source.pipe( Stream.pipeThroughChannel(Ndjson.decodeSchema(EmployeeRow)()), Stream.runCollect)console.log(await Effect.runPromise(program))
runCollect is appropriate in this tiny framing probe because the input is intentionally bounded. It is not the production sink.
Decode before business logic so downstream elements are domain values, not unknown. Refine numeric and textual domains in the Schema instead of checking them after persistence.
The NDJSON channel contributes NdjsonError for framing/JSON failures and SchemaError for values that parse as JSON but violate EmployeeRow. Keep that distinction if operations need separate malformed-file and bad-record reporting.
Batching is useful when the destination has a bulk API. Keep records as individual stream elements through decode and normalization, then group immediately before the bulk write.
Contextual — src/employee-import.ts:
Fragment · Type-checked with fixture
ts
import { Context, Effect, Stream } from "effect"import { Ndjson } from "effect/encoding"import { EmployeeRow, ImportStoreError} from "./import-domain.ts"export class EmployeeBatchStore extends Context.Service<EmployeeBatchStore, { readonly upsert: ( rows: ReadonlyArray<EmployeeRow> ) => Effect.Effect<void, ImportStoreError>}>()("app/EmployeeBatchStore") {}export interface ImportSummary { readonly batches: number readonly rows: number}export const ingestEmployees = <SourceError, SourceRequirements>( source: Stream.Stream<Uint8Array, SourceError, SourceRequirements>) => Effect.gen(function*() { const store = yield* EmployeeBatchStore return yield* source.pipe( Stream.pipeThroughChannel( Ndjson.decodeSchema(EmployeeRow)({ ignoreEmptyLines: true }) ), // At most 250 decoded records are retained for this batch. The final batch // may be smaller. Stream.grouped(250), // Default concurrency is sequential: one transaction and one retained // batch at this stage. Stream.mapEffect((batch) => store.upsert(batch).pipe( Effect.as({ batches: 1, rows: batch.length } as const) ) ), Stream.runFold( (): ImportSummary => ({ batches: 0, rows: 0 }), (total, next) => ({ batches: total.batches + next.batches, rows: total.rows + next.rows }) ) )})
The terminal fold retains only two counters. Stream.runDrain would be simpler if no summary were required; Stream.runForEach is appropriate for one-record writes. Do not collect merely to compute a count.
If bulk writes benefit from overlap, set an explicit finite concurrency and confirm that the database pool, transaction semantics, ordering requirements, and retained batch memory all support it.
Illustrative. This operator is incomplete until writeBatch is bound to an idempotent application adapter.
Stream.grouped(250) is right for a file: the stream ends, so the last partial batch flushes. On a queue-, socket-, or PubSub-backed source it is wrong: a partial batch waits for the 250th record indefinitely, holding its records in memory and making downstream latency unbounded. Stream.groupedWithin(n, duration) flushes on whichever limit is reached first.
Illustrative:
Fragment · Type-checked
ts
import { Stream } from "effect"declare const hrisChangeFeed: Stream.Stream<{ readonly employeeId: string }>// Write at most 250 rows per batch, and never hold a row longer than 2 seconds.const changeBatches = hrisChangeFeed.pipe(Stream.groupedWithin(250, "2 seconds"))
A buffer is not a batcher.Stream.buffer({ capacity: 250 }) and Sink.forEachArray look like batching and are not: a buffer sets flow-control depth, and forEachArray receives whatever chunk was pulled — single elements after any mapEffect stage. Only grouped, groupedWithin, rechunk, or a transduced Sink (for batches bounded by bytes instead of count) define the batch the destination sees.
FileSystem.stream is lazy and scoped by the stream run. The platform implementation closes its handle when the stream completes, fails, or is interrupted.
Do not call a full-body decoder such as arrayBuffer, text, json, or schemaBodyJson before constructing the stream. Those APIs intentionally materialize the body.
FileSystem.stream and response.stream already own their handles. A hand-written adapter — a vendor SDK cursor, a database export, a message subscription — must make the same promise: the handle is acquired inside the stream and released by the stream, on completion, failure, interruption, and early stop alike.
Illustrative — self-contained adapter.openVendorExport stands in for the vendor SDK; the error mirrors ImportSourceError from src/import-domain.ts.
Stream.unwrap removes the Scope requirement and keeps the scope open for as long as the returned stream is being pulled. Two ways to get this wrong: opening the export before building the stream and closing it "after the import" leaks on the first decode failure, and a reader that downloads the whole export and then calls Stream.fromIterable is an all-at-once read wearing a stream's type. The scope-placement pitfall of Stream.scoped is covered in Owning resources inside a stream.
Treat failure policy as part of the import contract
There are three common policies, and they are not interchangeable:
Fail fast. The first malformed record or failed batch fails the stream. This is the simplest choice for replace-all imports and transactional staging tables.
Record and continue. Convert a per-record validation failure into a typed dead-letter record, persist it, and continue. This requires framing JSON separately from Schema decoding so one bad decoded value can be handled without terminating the codec channel: decode each framed value inside Stream.mapEffect and turn its SchemaError into data there, or split the stream with Stream.partition and drain the rejected branch into the dead-letter store (both branches must be consumed concurrently inside one Effect.scoped).
Quarantine the file. Abort the import, preserve source identity and offset information, and move the entire object to a review path.
The capstone uses fail-fast semantics. Ndjson.decodeSchema fails the channel on the first invalid line; catching the error after the channel cannot recover the remaining lines because the decoder has terminated. If partial acceptance is a requirement, design it explicitly rather than adding a broad Stream.catch at the end.
This is the general rule for every stream recovery operator: a failure is terminal for the failed region, and Stream.catch, catchTag, or catchCause can only append a different stream after the elements already delivered — rows written before the failure stay written. The operator table, including Stream.timeout ending a stalled source silently rather than failing, is in Handling stream failures.
Official guide: Error handling in streams (its "timeoutFail"-style headings are stale names; the current API is Stream.timeoutOrElse).
A back-pressured stream provides flow control, not exactly-once persistence.
If a batch commits and the process dies before its completion is checkpointed, rerunning the import can write it again.
Stream.retry(schedule) takes an ordinary Schedule and recreates and reruns its upstream region, re-acquiring the source. Placing it around a database write can duplicate already committed effects. The schedule resets as soon as the restarted stream emits one element, so a long-lived feed gets a fresh backoff budget after each successful reconnect instead of exhausting upTo({ times: 5 }) over its lifetime.
Give each row or batch a stable source identity and use an upsert, unique constraint, idempotency key, or transactional staging table.
Keep checkpoint advancement in the same transaction as the destination write when both live in one database.
For a durable background job, move the file/import identity through PersistedQueue or a Workflow; streaming itself does not survive process restart.
Stream.fromQueue respects the Queue's capacity and strategy. A bounded Queue with the suspending strategy pushes back on Effect producers. Browser callbacks and third-party event emitters may not be able to suspend; the adapter must choose whether to buffer, drop, slide, pause the source, or fail.
Stream.callback(register, { bufferSize, strategy }) is where that choice is written down — and omitting the options chooses an unbounded buffer. A synchronous listener can only call Queue.offerUnsafe, which never waits: on a full buffer it returns false under "suspend" and "dropping" (the new value is lost) and evicts the oldest value under "sliding". So "suspend" protects nothing for a callback source; pick "dropping" or "sliding" as a stated loss policy and count the losses, or move the producer into an Effect that awaits Queue.offer on a bounded queue. The same queue ends the stream (Queue.endUnsafe) and fails it (Queue.failCauseUnsafe); an adapter that never does either leaves the import hanging when the socket closes. See Creating streams for the full adapter and Queue for overload semantics.
Stream.buffer({ capacity: n }) decouples producer and consumer by up to n elements. The default finite strategy is "suspend"; "dropping" and "sliding" intentionally lose values. Stream.bufferArray buffers pulled chunks instead of individual elements and preserves chunking. Neither is a free performance switch: measure throughput and memory with realistic record sizes. A buffer also reads ahead of demand — behind Stream.buffer({ capacity: 64 }) a consumer that takes one element has already caused dozens of source reads — so put take and other demand limits upstream of buffers.
The test above proves framing and batching. It does not prove that the pipeline is incremental, and it would still pass if the source were read completely before the first write. Three cheap, deterministic proofs close that gap, and each rejects one plausible wrong implementation:
Proof
Assertion
Wrong implementation it rejects
Laziness
building the pipeline performs zero reads
a source that starts reading when it is constructed
Prefix-sensitivity
requesting n elements performs exactly n reads
collect-then-slice, or a buffer placed before the demand limit
Cleanup
the release counter is exactly 1 after early stop, after a mid-stream failure, and after interruption
a demand-correct pipeline that lost its finalizer
Use a probe source that emits one element per read (Stream.unfold), because demand is satisfied per chunk: over Stream.fromIterable or a 64 KiB file chunk, take(2) legitimately reads a whole chunk, and the assertion has to be "at most one chunk past the prefix". Acquire the probe's resource inside the stream so the release counter observes every exit path. Assert the counters, not just the values — the values are identical in the correct and the leaking implementation.
import { assert, it } from "@effect/vitest"import { Data, Deferred, Effect, Exit, Fiber, Ref, Stream } from "effect"class CursorFailed extends Data.TaggedError("CursorFailed")<{ readonly row: number}> {}// One read yields one row, so `reads` is an exact demand meter. The cursor is// acquired inside the stream, so `releases` observes every exit path.const makeProbeSource = (options?: { readonly failAt?: number }) => Effect.gen(function*() { const reads = yield* Ref.make(0) const releases = yield* Ref.make(0) const rows = Stream.unwrap( Effect.acquireRelease( Effect.void, () => Ref.update(releases, (n) => n + 1) ).pipe( Effect.as(Stream.unfold( 0, Effect.fnUntraced(function*(row: number) { yield* Ref.update(reads, (n) => n + 1) if (row === options?.failAt) { return yield* new CursorFailed({ row }) } return [`emp_${row}`, row + 1] as const }) )) ) ) return { rows, reads, releases } })it.effect("is lazy, prefix-sensitive, and releases on early stop", () => Effect.gen(function*() { const source = yield* makeProbeSource() const firstThree = source.rows.pipe( Stream.map((id) => id.toUpperCase()), Stream.take(3) ) // Building the pipeline performs no reads: nothing runs until a runner pulls. assert.strictEqual(yield* Ref.get(source.reads), 0) const out = yield* Stream.runCollect(firstThree) assert.deepStrictEqual(out, ["EMP_0", "EMP_1", "EMP_2"]) // Collect-then-slice over this infinite source would never get here. assert.strictEqual(yield* Ref.get(source.reads), 3) assert.strictEqual(yield* Ref.get(source.releases), 1) }))it.effect("releases the source when a row fails", () => Effect.gen(function*() { const source = yield* makeProbeSource({ failAt: 2 }) const exit = yield* Effect.exit(Stream.runDrain(source.rows)) assert.isTrue(Exit.isFailure(exit)) assert.strictEqual(yield* Ref.get(source.reads), 3) assert.strictEqual(yield* Ref.get(source.releases), 1) }))it.effect("releases the source when the consumer is interrupted", () => Effect.gen(function*() { const source = yield* makeProbeSource() const writing = yield* Deferred.make<void>() const fiber = yield* source.rows.pipe( // The first write signals, then never finishes. Stream.mapEffect(() => Deferred.succeed(writing, undefined).pipe(Effect.andThen(Effect.never)) ), Stream.runDrain, Effect.forkChild ) yield* Deferred.await(writing) // handshake, not a sleep yield* Fiber.interrupt(fiber) assert.strictEqual(yield* Ref.get(source.releases), 1) }))
The interruption test synchronizes on a Deferred handshake instead of a sleep: the fiber is interrupted only after the first write has provably started. When the stage under test is an ordered mapEffect, assert the exact output order; with unordered: true, compare as a set, because completion order is not part of the contract.
For load tests, track peak resident memory, destination latency, queue depth, batch duration, retry count, and records per second. A fast happy-path benchmark can hide a catastrophic retry or oversized-record path.
A production ingestion feature should have these explicit pieces:
a source adapter that acquires its handle inside the stream and closes it on completion, failure, interruption, and early stop;
a wire codec that handles arbitrary chunk boundaries;
a Schema that turns unknown into domain values;
a documented maximum input and record size;
a finite batch size (plus a time bound when the source is live) and finite concurrency;
an explicit bufferSize and loss policy on every callback or event-listener source;
a destination method with idempotent or transactional semantics;
a typed decision for malformed records: fail, dead-letter, or quarantine;
incremental counters and telemetry rather than collected records;
a durable outer job identity if the import must resume after restart;
tests that split input at hostile byte positions, count reads for a requested prefix, and assert the release counter after early stop, failure, and interruption.
An Effect application does not become durable by moving a fiber to another machine. It also does not become distributed merely because a value is in a database. Durability and distribution are separate axes:
durability decides which facts, results, messages, and waits survive a crash;
distribution decides where work runs, who owns a key, and how callers reach it.
This guide follows one business operation—applying an approved compensation change—up the ladder. Each rung adds a specific guarantee and a specific operational cost. Stop at the lowest rung that meets the failure model.
All workflow, persistence, event-log, and cluster APIs in this guide are tagged @stability unstable. Pin the version and re-audit before upgrading — event-log payloads and cluster runner traffic are SchemaBinary-encoded on the wire and in storage, so a future change to that encoding makes an upgrade a deployment event rather than a dependency bump.
Climb only as far as the guarantee requires: each rung keeps more across restarts and nodes, and costs more to operate.
Suppose applyApprovedRaise must validate an approval, update payroll, and publish a notification. Before choosing an API, write down what must remain true after each failure:
Failure
Question that chooses the primitive
The current request is interrupted
May the caller retry the whole operation?
The process restarts
Must queued work, cached results, or a wait survive?
A worker crashes after payroll accepted the write
Can the write safely be delivered again?
A deployment changes the workflow code
Can an older execution still replay deterministically?
A cluster node disappears
Which node should own employee-42 next?
A projection is lost
Can authoritative history rebuild it?
“Exactly once” is usually not an end-to-end guarantee. Effect can durably record messages or completed activity results, but an external API and the Effect store do not share a transaction. A crash can occur after the external commit and before the acknowledgement is stored. Design external writes for at-least-once delivery with a stable idempotency key, a uniqueness constraint, or a transactional outbox.
Start from an invariant and mark the crash windows
State the property first — "every accepted raise reaches applied or dead-lettered", "no stale owner commits after a handoff" — and then walk the path every unit of work takes:
text
input -> durable state -> claim -> external effect -> result persisted -> acknowledged ^ ^ ^ ^ ^ a crash in any of these gaps must leave the invariant intact
If domain state and delivery state live in different stores, assume there is no atomic commit between them unless a verified protocol closes the gap: an outbox/inbox, a uniqueness constraint, a compare-and-set, or a fencing token checked by the sink.
An attempt at an external write ends in one of three ways, and only two of them are safe to act on automatically.
Outcome
How you know
What to do
Failed before dispatch
The request was never sent (validation, authorization, connection refused).
Retry under a bounded schedule, or fail the job.
Failed with a known answer after dispatch
The sink replied with a definite rejection.
Record it; retry only if the rejection is transient.
Unknown after dispatch
Timeout, interruption, a dropped connection, or a process death after the request left.
Never replay blindly. Re-send only with the same idempotency key, or query the sink's status API; otherwise park it for an operator.
Two more rules fall out of the table. Acknowledge only after the effect and its result are both persisted, which is what makes delivery at-least-once rather than at-most-once. Count attempts durably and persist exhaustion (a dead-letter state), and keep defects and interruption out of ordinary business retry: a defect is a bug to surface, and an interrupt is cancellation, not a failure to try again.
When you write down what the system promises, tag every line: library-proved (the engine journals a completed Exit), adapter-dependent (the SQL backend commits the activity result with your row in one transaction), deployment-dependent (only one replica consumes this queue), unsupported (the library does not fence stale owners), or design guidance (we pass an idempotency key). Only the first kind survives a change of backend or topology unexamined.
Rung zero: ordinary Effects and scoped resources
Start with normal services, Effect, Layer, Ref, Queue, fibers, schedules, and scopes. They provide typed composition, concurrency, cancellation, and resource safety inside one running process. They do not survive process loss.
Runnable. This is the correct baseline when an HTTP caller can retry and the destination deduplicates the command.
If the process dies, an in-memory Queue, Ref, cache, scheduled fiber, or retry state disappears. Do not describe those as durable because they are wrapped in a Layer.
Rung zero still has a rollback tool: a release function receives the closing Exit, so a sequence of Effect.acquireRelease steps inside one Effect.scoped can undo partial work in reverse order when — and only when — the scope closes with a failure. That is an in-process compensating transaction; see Failure, Retry, Fallback, and Interruption. It does not survive process death, because a kill runs no finalizers. The durable counterpart is Workflow.withCompensation on rung three.
Use the persistence family when the unit that must survive is a value or a completed typed result:
KeyValueStore stores raw strings or bytes behind interchangeable backends.
Persistence stores schema-encoded Exit values in named stores.
PersistedCache adds an in-memory cache in front of persisted results.
RequestResolver.persisted adds cross-restart result reuse to persistable requests.
This rung avoids recomputation. It does not orchestrate a multi-step process and it does not create a worker queue. Memory layers are test implementations, not durability tests; use a filesystem, SQL, Redis, or browser-backed layer appropriate to the module.
Choose cache keys as durable domain identities, and include every input that changes the answer. Version a key or namespace when the encoded schema or computation semantics change.
Know what this rung is not. A persisted cache stores Exit values, so it can replay a cached failure until its TTL expires; it is not a fleet-wide single-flight (two nodes may compute the same miss concurrently) and it is not a transactional source of truth. A memory-backed RateLimiter store limits one process only; the Redis store adds atomic scripts across nodes, not availability, fairness, or persistence guarantees. The Persistence page covers each store's layers and time-to-live rules.
Use PersistedQueue when the durable unit is an independent FIFO job. Producers can supply an id to suppress duplicate enqueueing. Consumers take work, acknowledge it on success, and retry failures up to the configured attempt limit.
Contextual. This snippet is complete at the Effect boundary; production wiring must provide a durable queue store and the application-specific payroll layer.
The custom offer id makes producer retries idempotent: de-duplication survives completion until PersistedQueue.layerCleanup removes the finished element (30 days by default). That is the default deduplicate: "untilRemoved" mode; offer(value, { id, deduplicate: "untilExecuted" }) instead reserves the id only while the element is pending or retrying, which coalesces repeated triggers but is not an idempotency key (see PersistedQueue). An element that exhausts maxAttempts — or no longer decodes with the queue schema — is dead-lettered and kept until you drain it or set failedTimeToLive. None of this makes the external payroll operation atomic. Pass a stable domain key to payroll as well.
take processes one claim, not an infinite worker loop. It returns the handler's value or propagates the handler error after the scoped store records the outcome; retrying the item is storage scheduling, not an automatic rerun inside that same call. Repeat take under an explicit worker lifetime and failure policy. Attempts are counted at claim time and the handler sees a 1-based count; process death consumes an attempt too. Undecodable entries are marked failed and skipped internally, so schema decode failures do not surface from take.
offer(value, { id, delay: "30 seconds" }) postpones only the first delivery; retries still use the queue's retrySchedule. A duplicate id does not change its existing delay. SQL uses the database clock and rounds delays up to seconds; Redis relies on agreement between producer and polling-worker clocks. Zero, negative, or omitted delays enqueue immediately. An infinite delay returns the id without storing anything, including no deduplication record: it is not a parked job. With delayed and retried work, FIFO is not a promise of global completion order.
Migration: the Redis PersistedQueue lock format changed with per-acquisition fencing and is incompatible with older workers on the same prefix. Stop every old worker and let its locks expire before starting upgraded workers; do not run a mixed fleet. See PersistedQueue.
Use this rung for email delivery, document rendering, imports, and other retryable jobs whose lifecycle is essentially “pending, processing, done, or exhausted and awaiting operator recovery.” When the process must pause, branch, compensate, and remember multiple completed steps, move up one rung.
Every durable consumer on this ladder — a queue taker, a workflow owner, a shard-holding runner — holds a lease: a claim that expires. A lease alone cannot stop a paused former owner (a long GC pause, a frozen VM, a partitioned node) from waking up and committing after a new owner took over. Inside their own stores the libraries do fence: the SQL and Redis PersistedQueue stores tie each settlement and lock refresh to one acquisition, so a handler whose lock lapsed cannot complete, fail, retry, or release a row that has since been re-claimed, and a cluster runner re-checks its shard lock before storing a persisted reply. But Effect's persistence, workflow, and cluster modules do not hand you a fencing token for your external sink, so the application protocol has to supply the protection:
give every protected write a monotonic token or version that the sink checks (compare-and-set, WHERE version = $expected, a uniqueness constraint on the idempotency key), and create, persist, propagate, and test that token yourself;
or make duplicate ownership harmless, so that both owners converging on the same idempotent write is acceptable;
size lease durations for the pauses you actually observe, not for the happy path.
Process death skips that process's finalizers.Effect.acquireRelease and Layer teardown cannot clean up after a killed owner. Workflow.addFinalizer instead belongs to terminal execution: an abandoned attempt skips it, but replay can register it on a new owner and run it when the workflow eventually completes. It is neither a crash hook nor an exactly-once cleanup guarantee. Restart behavior must never depend on old-owner cleanup having run, and graceful shutdown should acknowledge only work whose outcome is already committed.
Rung three: orchestrate a durable business process
Discarding a child result does not detach the child: { discard: true } still links completion wakes and parent interruption. Use { discard: true, detached: true } only when the child must outlive parent cancellation, and never later wait on that detached execution from a workflow. Its completion will not wake that waiter. Failure suspension is a different policy: an execution's own SuspendOnFailure waits for explicit resume or interrupt rather than retrying the failed activity in the background. See detached children and recovery.
Workflow describes deterministic orchestration. Activity contains every side effect and source of nondeterminism. The workflow engine journals completed activity Exit values; replay returns a recorded result instead of deliberately executing that activity again.
The activity can still run more than once if the worker is interrupted after the external side effect commits but before its Exit is durably recorded. Its name is a stable journal key, and Activity.idempotencyKey(name) produces a stable token for the external system.
Contextual. The contract and implementation compile as one module; writePayroll is the application adapter that the deployment supplies.
The workflow body will run again during replay. Never read the ordinary clock, generate random values, call an external service, or mutate process state directly in it. Put that work in a named Activity or use a durable primitive:
DurableClock for a sleep that survives restarts;
DurableDeferred for an out-of-band approval or webhook;
DurableQueue to hand a step to separately deployed workers;
compensation or finalizers when the process needs explicit cleanup semantics.
The in-memory workflow engine proves contracts and control flow only. A production engine needs durable storage, and workflow changes need compatibility discipline: retain stable workflow, activity, sleep, and deferred names for in-flight executions.
Three behaviors of the cluster-backed engine shape how you write the body:
An owner can abandon an attempt. If the runner that owns an execution shuts down or loses the shard, the interrupt it delivers is treated as an abandoned run attempt: nothing is persisted, compensations and Workflow.addFinalizer callbacks do not run, a parent workflow is not resumed, and the next owner replays the journal. An in-flight activity may therefore execute again — the same exposure as a crash, handled by the same idempotency token.
Durable finalizers and owner-local finalizers are different things.Workflow.addFinalizer and withCompensation fire when the execution reaches a terminal state, possibly on another machine; scope finalizers registered under Workflow.provideScope fire when this owner's scope closes, including on abandonment. Release sockets, locks, and temp files through the second kind only.
Compensation is a saga action, not an undo. It runs after a prior success, it can fail, be interrupted, or run more than once, and a body that replays registers it again. Give it its own idempotency key and record its outcome.
Workflow entities also passivate after a fixed ten seconds of idleness under ClusterWorkflowEngine, so a suspended execution holds no runner slot and no process-local state; everything it needs on resume must come from the journal. The workflow chapter has the full table, including the five cancellation events to test.
Use effect/eventlog when the durable unit is a domain fact and current state must be reproducible from history. An event log is not merely a queue with long retention. Events are immutable business facts, handlers update projections, and replay or replication can rebuild those projections.
Effect's EventLog is handler-first: it runs the matching handler and only commits the journal entry if the handler succeeds. With SqlEventJournal, SQL-backed handler work using the supplied SqlClient can share the journal transaction. IndexedDB cannot make arbitrary handler work and its later journal write one transaction, so backend choice changes the atomicity boundary.
Illustrative. This is the portable event contract; see the event-log chapter for handler, journal, identity, and sync layers.
Choose the event log when audit, offline replication, rebuildable projections, or event-sourced domain decisions are product requirements. Do not add it only to obtain background retries; PersistedQueue is smaller for that job. Keep event tags, primary keys, and payload schemas compatible with stored history.
Journal entries and remote sync messages are SchemaBinary-encoded, and no compatibility reader ships for a different wire format. "Authoritative history" is only as durable as your ability to decode it: the event payload Schema is the persisted contract from the moment you write it, so changing its wire representation later needs a one-off re-encode (or a new store id with the old journal kept read-only), with clients and servers moved together.
Replication is at-least-once. The sync loop retries a failed remote write indefinitely on a capped backoff, re-authenticates and retries when the server answers Forbidden, and skips the remote call entirely when nothing is uncommitted; the server acknowledges writes rather than echoing them back, and the receiving side de-duplicates by entry id. A replayed remote batch that fails to decode or whose handler fails is retried rather than committed unapplied. The remote protocol and the encrypted batch format change across releases — upgrade clients and servers together (see Event Log). Design projections so that seeing an entry twice is harmless.
Cluster entities are addressable actors whose ids are mapped to shards and owned by runners. They solve placement, routing, per-key serialization, passivation, and failover. By default, entity RPC messages are volatile. Annotate an RPC with ClusterSchema.Persisted when that message requires durable at-least-once delivery.
Illustrative. The entity contract shows the durability choice at the individual RPC boundary.
Entity handlers run sequentially per live instance unless a handler opts into concurrent execution. In-memory state held by an entity disappears when it is passivated or moved. Persist authoritative state elsewhere, reconstruct it on activation, or derive it from an event log. Persisted messages make delivery durable; they do not automatically make a handler's arbitrary external effects exactly once. For a volatile RPC sent with discard: true, success acknowledges delivery to the owning runner rather than an entity reply; delivery failures still propagate and may be retried. A persisted discard is recoverable from storage and is not coupled to the immediate notification transport result.
Persisted delivery also changes what a caller sees during a rebalance. If the entity moves or is shut down before replying, the caller simply keeps waiting and receives the reply from message storage once the next owner has processed the request; if the caller's own runner is shutting down, the call is interrupted rather than failed with EntityNotAssignedToRunner, because the request is already durable. Do not translate that interrupt into a domain error or a retry. A volatile send has no storage behind it and still fails fast — including with MailboxFull when the target runner is at its maxResidentEntities cap (10,000 by default), a limit that delays persisted work instead of rejecting it. An interruptible volatile request is also tied to its caller's connection: if the calling runner disconnects, the remote handler is interrupted and its mailbox slot freed, so a lost volatile call may have stopped partway. Work that must finish regardless of the caller belongs in a persisted request.
Runner wire format is a cluster-wide contract. Runner-to-runner traffic is serialized with SchemaBinary by default (serialization: "binary" on NodeClusterSocket.layer / NodeClusterHttp.layer and the Bun and Deno equivalents); serialization: "ndjson" is the text-based alternative both generations of a rolling upgrade can share. A cluster cannot mix runners on different serialization settings, and a change to the RPC envelope itself (such as the optional discard field added to requests) changes the binary fingerprint, so runners on either side of such a release must be upgraded together. Likewise, a rollout that changes the default must pin every node to the same serialization option throughout the rollout and rehearse a mixed-version pair in staging first. See Cluster & Sharding.
Persisted messages and their replies stay in MessageStorage so duplicates are recognised; for an entity type that handles an unbounded stream of distinct requests, bound that storage with MessageRetention, choosing a retention longer than any caller's retry window (a primary key re-sent after deletion runs again). Never apply it to workflow or ClusterCron entities. The same entity and workflow definitions can also run on Cloudflare Durable Objects through the experimental @effect/platform-cloudflare, where each entity id is its own object with SQLite storage and there are no runners or shard locks (Running on Cloudflare Durable Objects).
Use entities when many keys need single-owner logic spread across machines. Use a singleton for one cluster-wide process. Distribution may sit below a workflow engine, host workers for a persisted queue, or expose an event-sourced aggregate, but those are compositions—not substitutes for one another.
Compose rungs by assigning one owner to each truth
A production raise application might use only a workflow and an idempotent payroll adapter. A larger system might use this composition:
An HTTP command starts ApplyApprovedRaise with approvalId as its workflow idempotency key.
A named activity writes payroll with an activity-derived idempotency token.
After payroll confirms, another activity appends RaiseApplied to the authoritative event log.
Projections serve reads; cluster entities are introduced only if per-employee distributed ownership is required.
Do not let a queue row, workflow journal, event, and entity Ref all claim to be the authoritative status. Name one source of truth and treat the others as delivery state, orchestration state, projections, or caches. Record a durable handoff before acknowledging its predecessor, or use a transaction/outbox when both records share a database.
Preserve immutable domain history and rebuild projections
EventLog
Route typed commands to one owner per key across nodes
Cluster Entity
Make selected entity messages survive failover
ClusterSchema.Persisted plus durable MessageStorage
Keep persisted entity storage bounded
MessageRetention (not for workflow or ClusterCron entities)
Treat persisted bytes as input, and their names as a contract
Everything above rung zero writes bytes that a later version of your program will read. Two rules follow.
Stored records are untrusted input. Persist an explicit envelope — protocol version, tenant, a stable operation id, a state tag, attempt metadata, a bounded payload, timestamps from a declared clock, and the fencing token if the sink needs one — and validate version, identity, and size before any business interpretation. A record you cannot decode is not a retryable failure: quarantine it durably where an operator can see it. PersistedQueue does this for you (an undecodable element is dead-lettered instead of being retried); for your own tables, do the equivalent.
Names are identities. A store id, queue name, workflow tag, activity name, deferred name, event tag, entity type, RPC tag, and the output of every idempotencyKey / primaryKey function are all keys into live data. Renaming one orphans that data; renaming the TypeScript import does not migrate it. Build composite keys with a canonical, versioned encoder rather than by concatenating user- or model-supplied strings, where "a:b" + "c" and "a" + "b:c" collide.
Rollout strategy
Use it when
Drain, then deploy
In-flight work is short and you can pause intake.
Read-old / write-new
The new schema can still decode old records; keep old readers and handlers until the backlog is gone.
Route by version
Old and new code must coexist for long-lived executions; the version is part of the identity.
Verified migration
Records must be rewritten; test the migrator on production-shaped fixtures and keep a rollback copy.
New identity
Semantics changed; start …V2 and let the old name finish.
Before any of them, inventory what is in flight — suspended workflows and their longest wait, queue depth and dead letters, unacknowledged persisted messages — and test old fixtures against new code, plus old and new workers against one store. Do not read mutable ambient configuration during a replay; capture it once in a journaled step.
Validate the chosen guarantee, not only the happy-path return value:
Unit-test the domain services and idempotency-key derivation with ordinary test layers.
Redeliver the same queue item, activity, or persisted RPC and prove the external state changes once.
Kill the worker after the external commit but before acknowledgement; restart it and verify recovery.
For workflows, suspend and resume with the production storage backend and test replay of an older execution against the new deployment.
For event sourcing, rebuild a fresh projection from journal history and compare it with the live projection.
For cluster entities, passivate an instance and fail over a runner; prove state reconstruction and persisted-message behavior.
Test poison messages and permanent failures so retries terminate, surface diagnostics, and reach an operator-controlled recovery path.
Pause an owner past its lease (freeze the process, let another take over, then thaw it) and prove the stale owner's write is rejected by the sink.
Run old and new code against one store, and replay fixtures of old stored bytes on the new build; include a corrupt record and check it is quarantined, not retried.
Take storage away mid-operation and verify nothing is acknowledged that was not persisted; then restore from a backup and resume in-flight work.
For a cluster upgrade, rehearse the serialization pin with one old and one new runner before touching production.
Keep three lanes separate, because each proves something different: a deterministic lane (memory layers, TestClock) proves the state machine and compensation order; an adapter lane on the production backend with real kill-and-restart proves durability and redelivery; an artifact lane runs the built deployable with its real configuration and shutdown signals. A green deterministic lane says nothing about crash durability.
Bound retries and distinguish transient failures from permanent typed failures.
Verify the real production backend; memory layers cannot demonstrate crash durability.
Document which record is authoritative and which records are delivery or projection state.
Rehearse deployment compatibility while durable work is still in flight, including stored-format changes (event-log payloads) and wire-format changes (cluster serialization).
Classify every external write outcome as before-dispatch, known, or unknown; never auto-replay an unknown.
Protect sinks against stale owners with a version or fencing check; a lease alone is not enough.
Never rely on finalizers for restart correctness; a kill skips them.
Alert on cluster residency approaching maxResidentEntities and on persisted-message backlog age.
Authenticate, authorize, and audit operator actions (inspect, interrupt, resume, redrive, quarantine release), and run restore drills rather than trusting that backups exist.
A production AI feature is not a prompt wrapped in an HTTP handler. It is a normal application capability with a typed input boundary, an injectable model, narrowly authorized tools, validated output, explicit limits, observable cost, and a deterministic test seam.
This guide builds a policy assistant that answers an HR partner's question from an authorized policy catalog. It keeps the model behind a service so the rest of the application never depends on a provider SDK.
The AI APIs are tagged @stability unstable. Pin Effect and the matching provider packages together, and re-audit before upgrading.
Decide what the caller receives and what failure means. Free-form text is appropriate for drafting. If another program will act on the answer, use LanguageModel.generateObject with a Schema and treat schema failure as a typed AI failure—not as a partially trustworthy result.
Runnable. These schemas are the stable application boundary; provider response shapes remain inside the adapter.
The Schema validates shape and constraints. It does not prove that the answer is true, that a citation supports the claim, or that policy permits an action. Those require grounded tools, application checks, and human review appropriate to the risk. The local decode is also the only authority on shape: a provider's "strict JSON" mode narrows what the model emits, but generateObject still decodes the reply through your Schema, and a reply that fails must stay a typed StructuredOutputError rather than being rescued by parsing prose. An empty reply fails the same way; pass allowEmpty: true only when "nothing to report" is a valid product answer, and handle the resulting Option explicitly (see LanguageModel).
Write down which values the capability may believe. Everything a model can influence is input to be validated; nothing a model can influence may grant authority.
Value
Source
Treat as
Actor, tenant, roles, session
Authenticated request context, bound into services before the model runs
Untrusted content: it can carry instructions aimed at the model
Model text, tool names and arguments, citations, confidence
The model
Untrusted output: validate the shape, then re-check authority in code
Three consequences follow. Fail closed when identity, authorization, approval, a required price or usage figure, or a safety bound cannot be established — an absent limit is an error, not "unlimited". Keep egress deliberate: know which provider receives which data, under which retention terms, and strip what the task does not need. Separate guidance from enforcement: prompts steer, Schemas validate representation, and only handler code proves authorization, freshness, or safety.
Tools are typed calls from the model into your application. Tool.make defines the name, description, parameter Schema, and success Schema. Toolkit.make groups tools, and toolkit.toLayer supplies their handlers.
Do not let a tool accept an arbitrary database predicate, URL, file path, or tenant id. Define the smallest domain operation the model needs. The handler—not the model—must enforce tenant scope, authorization, row-level policy, rate limits, and audit recording.
Contextual.PolicyCatalog is the authorized application port. Its live layer is expected to bind the current actor and tenant before returning search results.
Self-contained source · Type-checked
ts
import { Context, Effect, Schema } from "effect"import { AiError, Tool, Toolkit } from "effect/ai"const PolicyExcerpt = Schema.Struct({ policyId: Schema.String, title: Schema.String, section: Schema.String, excerpt: Schema.String})type PolicyExcerpt = Schema.Schema.Type<typeof PolicyExcerpt>class PolicyCatalog extends Context.Service<PolicyCatalog, { readonly searchAuthorized: ( query: string, limit: number ) => Effect.Effect<ReadonlyArray<PolicyExcerpt>, AiError.AiError>}>()("app/PolicyCatalog") {}const SearchPolicies = Tool.make("SearchPolicies", { description: "Search policy text the current user is authorized to read", parameters: Schema.Struct({ query: Schema.String.annotate({ description: "A concise policy question, without employee personal data" }), limit: Schema.Int.check( Schema.isBetween({ minimum: 1, maximum: 8 }) ) }), success: Schema.Array(PolicyExcerpt), failureMode: "error"})export const PolicyToolkit = Toolkit.make(SearchPolicies)export const PolicyToolkitLive = PolicyToolkit.toLayer( Effect.gen(function*() { const catalog = yield* PolicyCatalog return PolicyToolkit.of({ SearchPolicies: Effect.fn("SearchPolicies")(function*({ query, limit }) { return yield* catalog.searchAuthorized(query, limit) }) }) }))
Tool parameter decoding rejects malformed calls before the handler runs, and tool success values are encoded through their Schema. Both use the schema's JSON codec, so arguments arrive as JSON (a date as an ISO string) and results leave as JSON. What happens to the rejection follows the tool's failureMode, exactly as a handler failure does: under "error" (the default, used here) the generation fails with an AiError whose reason is ToolParameterValidationError; under "return" the same error is handed back to the model as a failed tool result so it can repair the call. Use "return" only when exposing the failure to the model is an intentional recovery strategy and the error content is safe to reveal — authentication, authorization, and approval failures are never "recoverable tool text".
Tool calls requested in one model turn are resolved with unbounded concurrency unless you pass concurrency. A search tool that fans out to a rate-limited index, or any tool holding a connection, needs an explicit number on every generateText / generateObject / streamText call that carries the toolkit.
Descriptions influence model behavior; they are not a security boundary. Keep authorization in the handler even if the system prompt says the same thing.
Business code should depend on LanguageModel.LanguageModel, not OpenAiClient or another vendor client. A provider model is a Layer; select and configure it at the application edge. Config.Redacted prevents the API key's value from appearing in ordinary logs and inspection.
Contextual. This is a complete Effect adapter. The deployment still supplies PolicyCatalog; OPENAI_API_KEY is read through the configured ConfigProvider.
The relative imports point to the preceding contract module. In a single-file prototype, place those declarations above the service instead.
Retry only failures known to be transient. Authentication, quota exhaustion, invalid requests, content-policy rejection, and invalid structured output need different handling. AI errors carry no request headers or query parameters; a NetworkError records method and url, but its optional cause is the original HttpClientError, unredacted — keep it out of user-facing messages and log it as carefully as the request itself. Bound both retries and total request duration at the application boundary.
If you need provider or model fallback, an ExecutionPlan can provide successive model layers. A fallback is still a semantic change: models differ in tool support, output quality, safety behavior, price, and context limits. Exercise every planned model in contract tests.
A read-only retrieval tool can often execute automatically. A tool that changes payroll, sends a message, creates a ticket, or reveals sensitive data needs a stronger boundary.
Illustrative. Marking a tool as approval-gated tells the AI framework to produce an approval request instead of silently executing it. The surrounding application must authenticate the approver, show the exact decoded arguments, persist the decision when required, and provide the matching approval response.
Illustrative · Pseudocode — not executable
ts
import { Schema } from "effect"import { Tool } from "effect/ai"export const SubmitPolicyException = Tool.make("SubmitPolicyException", { description: "Submit a policy exception after an authorized human approves it", parameters: Schema.Struct({ employeeId: Schema.String, policyId: Schema.String, rationale: Schema.String }), success: Schema.Struct({ requestId: Schema.String })}).setNeedsApproval(true)
Approval does not replace authorization or idempotency. Recheck both inside the eventual handler, bind the approval to the actor and exact arguments, and pass a stable request id to the destination so a retried tool result cannot create two actions.
Once a human decision exists, the application appends a tool-approval-response part (approvalId, approved, optional reason) to the conversation and calls the model again with the same handler-equipped toolkit. The framework then runs an approved call before contacting the provider, or records a denied one as a failed result of type "execution-denied". Completed approval results are retained in the response, so a Chat records them and a later turn does not execute the approved tool a second time.
Keep the framework from executing a mutation before your gates run
setNeedsApproval covers "a human must say yes". It does not cover "authenticate, authorize at execution time, claim an idempotency record, and only then invoke". For that, stop the framework from resolving tool calls at all: pass disableToolCallResolution: true, inspect the proposed calls, run your own protocol, and dispatch through the toolkit's handle.
The default is still strict tool-call validation: disabled resolution leaves user-tool parameters in their JSON encoding, typed as Schema.Json. Decode that JSON with Schema.toCodecJson(tool.parametersSchema) before applying typed policy gates, and pass the original JSON to handle. If the application must receive malformed arguments or undeclared names to run its own repair loop, also set toolCallValidation: "deferred". Those model-generated calls have unknown parameters, including when no toolkit is supplied; allow-list the name and decode/normalize parameters before applying the gates below. Provider-executed calls remain validated. Do not add deferred mode to the example below without adding that explicit validation boundary.
Contextual.ActionLedger is the application's tenant-scoped idempotency store and Authorizer its policy port; both are bound to the authenticated actor before this code runs.
Self-contained source · Type-checked
ts
import { Context, Effect, Schema, Stream } from "effect"import { LanguageModel, Tool, Toolkit } from "effect/ai"class ActionRefused extends Schema.TaggedError<ActionRefused>()("ActionRefused", { toolCallId: Schema.String, reason: Schema.Literals(["unauthorized", "not-approved", "duplicate"])}) {}class ActionOutcomeUnknown extends Schema.TaggedError<ActionOutcomeUnknown>()( "ActionOutcomeUnknown", { operationId: Schema.String }) {}const SubmitPolicyException = Tool.make("SubmitPolicyException", { description: "Submit a policy exception for an employee", parameters: Schema.Struct({ employeeId: Schema.String, policyId: Schema.String, rationale: Schema.String }), success: Schema.Struct({ requestId: Schema.String })})const ActionToolkit = Toolkit.make(SubmitPolicyException)type ExceptionArgs = typeof SubmitPolicyException.parametersSchema.Typeclass Authorizer extends Context.Service<Authorizer, { // Resolves actor and tenant from trusted context, never from `args`. readonly authorize: (toolCallId: string, args: ExceptionArgs) => Effect.Effect<void, ActionRefused>}>()("app/Authorizer") {}class ActionLedger extends Context.Service<ActionLedger, { // Atomically claims a server-issued operation id for this intent and // persists "dispatched" before returning it. readonly claim: (toolCallId: string, args: ExceptionArgs) => Effect.Effect<string, ActionRefused> readonly settle: ( operationId: string, outcome: "succeeded" | "failed-known" | "unknown" ) => Effect.Effect<void>}>()("app/ActionLedger") {}export const proposeThenSubmit = Effect.fn("proposeThenSubmit")(function*(question: string) { const toolkit = yield* ActionToolkit const authorizer = yield* Authorizer const ledger = yield* ActionLedger const response = yield* LanguageModel.generateText({ prompt: question, toolkit, disableToolCallResolution: true // propose only; nothing has executed }) const submitted: Array<string> = [] for (const call of response.toolCalls) { const params = yield* Schema.decodeUnknownEffect( Schema.toCodecJson(SubmitPolicyException.parametersSchema) )(call.params) yield* authorizer.authorize(call.id, params) const operationId = yield* ledger.claim(call.id, params) // `handle` and the full consumption of its stream stay in one Effect, so // interrupting this request also interrupts the handler fiber. const outcome = yield* toolkit.handle(call.name, call.params, call.id).pipe( Effect.flatMap(Stream.runLast), // A typed handler failure is a known outcome. Effect.tapError(() => ledger.settle(operationId, "failed-known")), Effect.timeout("20 seconds"), // A timeout or interruption AFTER dispatch is not a known failure. Effect.catchTag("TimeoutError", () => ledger.settle(operationId, "unknown").pipe( Effect.andThen(Effect.fail(new ActionOutcomeUnknown({ operationId }))) )), Effect.onInterrupt(() => ledger.settle(operationId, "unknown")) ) if (outcome._tag === "Some" && "requestId" in outcome.value.result) { yield* ledger.settle(operationId, "succeeded") submitted.push(outcome.value.result.requestId) } } return submitted})
The mutation is a protocol with a ledger, not a function call:
Decode and normalize the arguments before authorization (the example decodes the tool's JSON codec; handle separately decodes the original JSON before invoking the handler).
Resolve actor and tenant from trusted context, authorize at execution time, and verify any approval against the call id, an argument digest, the actor, the tenant, its expiry, and the policy version you expected.
Derive the idempotency key from a server-issued operation id, the tenant, the operation kind, and the normalized intent — not from the tool-call id, which changes when the model retries.
Claim the ledger entry atomically and persist dispatched before invoking. A duplicate claim converges on the first outcome instead of dispatching again.
Record succeeded, failed-known, or unknown. A timeout or interruption after dispatch is unknown: never replay it blindly; reconcile through the destination's idempotency or status API.
Hand the model small, sanitized tool results. Ledger state, policy reasons, and stack traces stay server-side.
McpServer is the external protocol boundary for exposing selected tools and resources to other agents. It is not the in-process agent loop: keep ordinary application tool calls on Toolkit, and add MCP only when another process needs discovery and invocation over stdio or Streamable HTTP.
Every server layer must declare the protocol versions it accepts, for example protocols: [McpProtocol.v2025_06_18]; do not silently accept an unspecified or future wire contract. A stdio layer owns the process stream lifecycle. An HTTP layer owns an HTTP server route and must be deployed with its origin and media checks intact: requests carrying Origin are rejected unless the exact origin is allowlisted, POST requires Content-Type: application/json, and Accept must allow both JSON and event-stream responses. Put authentication, tenant binding, tool authorization, rate limits, audit logging, and request-size limits outside or inside the handlers as appropriate—protocol negotiation does not supply product authorization.
Treat MCP handlers like any other externally reachable Effect service. Decode arguments through Schema, expose the smallest safe capability, provide their Layers once for the server lifetime, and make consequential operations idempotent. Pass tool, resource, and prompt registration layers through the transport layer's registrations option; per-request services such as the authenticated principal reach handlers through MCP middleware (or HttpRouter.middleware under layerHttp), and McpServer.visibility hides capabilities a caller may not use — see Request-level dependencies, middleware, and visibility. Every failed call reaches the client as an isError: true result. A declared failure is part of the tool's contract and is sent as written: its message for an Error under failureMode: "error", otherwise its schema-encoded payload (always the payload under "return"), so keep internal detail out of declared failures. Undeclared failures, AiErrors, defects, and results that fail their own schema reach the client only as a fixed internal-error text, and are logged and handed to the configured ErrorReporters, so wire a reporter if tool faults should page someone. Arguments that fail the parameter schema become a JSON-RPC InvalidParams error on protocols up to 2025-06-18 and an isError result on 2025-11-25 and later. Mark a tool Tool.Strict when unexpected arguments should be rejected rather than dropped. See the concise MCP server reference for the full outcome table, layer configuration, and transport details. For the full server architecture — protocol eras, OAuth resource-server middleware, human-in-the-loop round trips, idempotency, and in-process tests — read Exposing an Effect Application over MCP.
Chat owns conversation history and appends resolved tool calls and results between turns. It is useful when a task genuinely needs multiple model/tool rounds. It is not a reason to use an unbounded while (true) loop in production.
Contextual. The toolkit and model are Context requirements. This loop terminates with a typed failure after maxTurns model calls.
chat.streamText({ ..., maxSteps }) runs the same bounded loop inside one stream: it keeps calling the model while every tool call of a round was answered, for at most maxSteps rounds, and emits one finish part per round, so account usage per round. It stops early at a call it cannot answer, such as an approval request or a client-executed tool. The turn limit is still yours to choose; never pass an unbounded value.
Also bound tool concurrency, provider retries, per-tool timeouts, accumulated history, response tokens, and total wall-clock time. Persist chat only when the product needs continuity; define retention and deletion rules because prompts, tool results, and exported history may contain sensitive data.
Validate the budget, reserve before dispatch, account per turn
A turn limit bounds iterations; it does not bound cost. Treat the budget as data with its own invariants, and enforce it before each model call.
Contextual. The reservation uses a Tokenizer estimate; the provider's reported usage reconciles it afterwards.
Self-contained source · Type-checked
ts
import { Effect, Ref, Schema } from "effect"import { Chat, Tokenizer, Tool, Toolkit } from "effect/ai"class BudgetRejected extends Schema.TaggedError<BudgetRejected>()("BudgetRejected", { limit: Schema.Literals(["policy", "turns", "tokens"]), detail: Schema.String}) {}interface AgentBudget { readonly maxTurns: number readonly maxTotalTokens: number readonly maxOutputTokensPerTurn: number}// Fixed ceilings the caller cannot raise. NaN, Infinity, negatives, and// fractions are rejected instead of being read as "no limit".const ceiling: AgentBudget = { maxTurns: 8, maxTotalTokens: 60_000, maxOutputTokensPerTurn: 4_000 }const validateBudget = (budget: AgentBudget) => Effect.gen(function*() { for (const key of ["maxTurns", "maxTotalTokens", "maxOutputTokensPerTurn"] as const) { const value = budget[key] if (!Number.isSafeInteger(value) || value <= 0 || value > ceiling[key]) { return yield* new BudgetRejected({ limit: "policy", detail: `${key}=${String(value)}` }) } } return budget })export const runBudgetedAgent = <Tools extends Record<string, Tool.Any>>( question: string, toolkit: Toolkit.Toolkit<Tools>, requested: AgentBudget) => Effect.gen(function*() { const budget = yield* validateBudget(requested) const tokenizer = yield* Tokenizer.Tokenizer const spent = yield* Ref.make(0) const chat = yield* Chat.fromPrompt([ { role: "system", content: "Use the available tools for evidence." }, { role: "user", content: question } ]) for (let turn = 1; turn <= budget.maxTurns; turn++) { // Reserve BEFORE dispatch: estimated context + worst-case output. const history = yield* Ref.get(chat.history) const estimate = (yield* tokenizer.tokenize(history)).length const reserved = estimate + budget.maxOutputTokensPerTurn if ((yield* Ref.get(spent)) + reserved > budget.maxTotalTokens) { return yield* new BudgetRejected({ limit: "tokens", detail: `turn ${turn}` }) } const response = yield* chat.generateText({ prompt: [], toolkit, toolChoice: "auto", concurrency: 2 }) // Reconcile with what the provider billed; ADD per turn, never max(). const billed = (response.usage.inputTokens.total ?? estimate) + (response.usage.outputTokens.total ?? budget.maxOutputTokensPerTurn) yield* Ref.update(spent, (total) => total + billed) if (response.toolCalls.length === 0) return response.text } return yield* new BudgetRejected({ limit: "turns", detail: String(budget.maxTurns) }) }).pipe( // One absolute deadline for the whole run; the timeout interrupts the // in-flight provider request and any running tool handlers. Effect.timeout("90 seconds") )
Rules the example encodes, and the ones it leaves to the surrounding service:
A missing or malformed limit fails closed.Infinity, NaN, a negative number, or a caller-supplied limit above the fixed ceiling is a rejected policy, not an unlimited one.
Returned usage is reconciliation, not first enforcement. By the time usage arrives the money is spent. If a provider omits usage, charge the reservation.
Bound each outgoing context separately from the billed total. Every turn re-sends history; truncate or summarize before the context limit rather than after a provider error.
Retries draw from the same budgets, and a retry is only legal before any streamed output reached the caller and before any mutating tool was dispatched.
An abort signal is not a timeout. Race a timeout that interrupts, and bound stream consumption as well as stream creation — a stream that is never drained holds its connection.
Share limiters at the service boundary. A Semaphore created per invocation limits nothing across requests; build it once in the service's Layer.
Accept a turn as complete only when it ends in exactly one well-formed finish part, and deny by default any unrecognized part type that would trigger an action.
LanguageModel.streamText returns a Stream of tagged response parts. Forward text deltas incrementally, but also observe the terminal finish part for usage and reason. Cancellation should interrupt the model request through the stream scope.
Contextual. This projection intentionally exposes only text deltas. A production transport should separately record the terminal finish part and translate stream errors.
Self-contained source · Type-checked
ts
import { Stream } from "effect"import { LanguageModel, type Response } from "effect/ai"export const streamPolicyDraft = (question: string) => LanguageModel.streamText({ prompt: [ { role: "system", content: "Draft policy guidance; do not make decisions." }, { role: "user", content: question } ] }).pipe( Stream.filter( (part): part is Response.TextDeltaPart => part.type === "text-delta" ), Stream.map((part) => part.delta) )
A streamed turn can end four ways: a terminal finish part, a typed failure, a timeout, or interruption when the client disconnects. Only the first produced a turn that is safe to show the model again.
Record the turn as incomplete before consuming the stream, keyed by a server-issued turn id.
Append bounded semantic events (text accumulated so far, tool calls, tool results) — not raw provider frames, and never unbounded.
Mark it complete only after a valid terminal finish part and reconciled usage. Use Stream.onExit (or a scoped finalizer) to write failed or interrupted for every other ending.
Rebuild later prompts only from complete, compatible turns. Store the tool-definition and schema versions with each turn; a half-written assistant message or a tool call without its result makes the next provider request malformed.
Chat itself is in-process mutable state with no tenant, version, or concurrency control. When completeness or shared ownership matters, keep the authoritative transcript in your own store and hydrate a Chat from it per request with Chat.fromPrompt or Chat.fromExport. If you use Chat.layerPersisted instead, its histories live under the persistence store's key layout: histories written on a KeyValueStore backing under the older <storeId><key> layout are not read back after the store-isolation change, so copy them to <storeId>:<key> before upgrading (see Persistence and Chat).
Do not collect the stream into an array or one string before sending it to the client; that preserves the type but discards streaming's latency and memory benefits. See Streaming Ingestion Without Accidental Buffering for the same principle at data-ingestion scale.
Make prompt assembly, authorization, retrieval, citation verification, and output policy ordinary pure or Effect code. Those tests should not depend on a network model. At the AI boundary, provide a deterministic LanguageModel made from encoded response parts.
Runnable. This fake is the same test seam used by Effect's own AI tests. LanguageModel.make also stamps the service's [TypeId] brand, which a hand-written object literal would have to add itself.
Self-contained source · Type-checked
ts
import { Effect, Layer, Stream } from "effect"import { LanguageModel } from "effect/ai"export const FakeLanguageModel = Layer.effect( LanguageModel.LanguageModel, LanguageModel.make({ generateText: () => Effect.succeed([ { type: "text", text: "The policy requires manager and HR approval." } ]), streamText: () => Stream.empty }))export const example = LanguageModel.generateText({ prompt: "What approvals are required?"}).pipe( Effect.map((response) => response.text), Effect.provide(FakeLanguageModel))
A single canned answer proves little about an agent. A scripted model replays one list of encoded parts per turn and records exactly what it was sent, so a test can assert on prompts, turn counts, and tool dispatch.
Runnable. Each inner array is one model turn; the second turn only happens if the first tool call was resolved.
Give every other capability boundary a fake with the same discipline: a toolkit handler with a Deferred barrier before and after its commit point (to interrupt at each), tenant-aware stores that enforce compound keys, an approval fake whose bound fields can each be varied independently, a TestClock and fixed price table, and a telemetry collector that rejects attribute keys outside an allow-list.
Use provider integration tests for the smaller set of behaviors the fake cannot prove: provider request translation, structured-output compatibility, tool-call encoding, streaming event order, safety responses, and fallback behavior. Do not make assertions on stylistic wording; assert schemas, invariants, cited evidence, tool authorization, limits, and failure classification.
A permitted user retrieves only authorized policy excerpts; a cross-tenant query returns none even when the model asks for it.
Malformed tool parameters never reach the handler.
A valid structured response decodes to PolicyAnswer; malformed JSON, a missing citation, and an invalid confidence value fail through the AI error channel.
A rate-limit error retries within the bound; authentication and invalid-output errors do not loop indefinitely.
A mutating tool cannot execute before a correctly bound approval, and redelivery creates one external action.
The agent stops at the configured turn limit and interrupts outstanding tools when the request is cancelled.
Streaming emits early deltas without collecting the full result, reports terminal usage, and closes on client cancellation.
Logs and traces contain request ids, model identity, latency, finish reason, token usage, and tool names—but no API keys, full sensitive prompts, or hidden reasoning.
Each approval mismatch — wrong call id, changed arguments, another actor or tenant, expired, stale policy version — produces zero dispatches.
Concurrent and sequential duplicates of one intent dispatch once and return the same recorded outcome.
A timeout before dispatch is reported as a safe failure; a timeout after dispatch is recorded as unknown and is not retried automatically.
Every budget fails at its exact edge (turn maxTurns + 1, the first token over the total), and a non-finite or over-ceiling budget is rejected before any model call.
A partially consumed stream leaves a persisted incomplete/interrupted turn, runs its finalizers, and that turn is absent from the next prompt.
A canary string planted in a retrieved document never appears in tool arguments for another tenant, in logs, or in telemetry attributes.
State what each layer of the suite proves. Deterministic fakes prove policy. Recorded or mock HTTP transports prove adapter parsing, streaming order, and cancellation. A small, separately authorized live-provider lane proves only that the remote API still matches the recording today.
Embeddings. Persist provider, model, dimensions, normalization, and a schema version beside each vector. When any of them changes, build a new versioned index and re-embed; never compare vectors from different spaces.
Classification and scoring. When the answer is a label, a rating, or a probability — routing a raise request, flagging a policy exception — a DecisionModel returns validated distributions instead of free text. Treat its thresholds as versioned policy, record the input schema version and the provider model beside each stored decision, and test routing with a scripted DecisionModel.make layer.
Fallback models. A fallback is a separately configured capability. Re-validate its tool, structured-output, and media support in contract tests, and never route to it in order to get past a content-policy refusal.
Dynamic and MCP-sourced tools.McpClient.toolkit turns another server's tools into a Toolkit (see McpClient); it is a protocol bridge, not a trust decision. Authenticate the server, allow-list tool names, snapshot each tool's JSON Schema and validate arguments locally, map every tool to an application capability with its own policy, and reject a changed schema until a human has reviewed it. Its options support that discipline: bind only an approved descriptor snapshot with tools, gate writes with transformTool (for example setNeedsApproval(true)), bound each call with timeout, and leave trustAnnotations off unless the server is yours.
Browser-facing agents.AgUiServer (experimental) serves an agent to an AG-UI frontend. Everything in a run's input is client-controlled: AgUi.toPrompt drops client system/developer messages and context by default, frontend tools run in the browser as client-executed tools, and server tools still authorize from trusted context. Authenticate the route and bound maxSteps.
Media input. Before a file part leaves the process, validate its content signature and declared type, its size and pixel or time extent, how many parts the request carries, and which URI schemes it may reference; a prompt must never make the provider fetch a URL on its own.
Stored tool results. A result holds the JSON encoding of the success or the failure schema according to its isFailure flag, and failed results may be a Tool.ExecutionFailure. Treat exported Chat history as a versioned persisted format and review it when a tool's schemas change.
Keep provider selection and credentials in Layers and Config, outside business services; where the platform issues workload identity tokens, prefer workload identity federation over static API keys, and provide its layer only to the provider client.
Treat prompts, retrieved documents, model text, and tool arguments as untrusted input.
Validate machine-consumed output with Schema and apply domain invariants afterward.
Authorize every tool in its handler; expose narrow domain operations, not generic infrastructure access.
Require and audit human approval for consequential actions.
Use stable, server-issued idempotency keys for tools that write externally, and record unknown outcomes instead of replaying them.
Set concurrency on every call that carries a toolkit; use disableToolCallResolution when your own gates must run before a handler.
Bound agent turns, retries, tool concurrency, token budgets, history, and wall-clock duration — and reject any budget that is missing, non-finite, or above the fixed ceiling.
Keep failed, timed-out, and interrupted turns out of later prompts.
Record model/provider, latency, finish reason, token usage, tool calls, failures, and fallback selection; tool spans carry gen_ai.tool.name by default, and arguments only if you enable Toolkit.RecordToolArguments.
Redact secrets and minimize personal or confidential content sent to providers.
Define retention, regional processing, deletion, incident-response, and provider-data-use policy.
Maintain deterministic fakes plus a small live-provider contract suite.
Pin unstable Effect/provider package versions and review changelogs together.
McpServer, McpProtocol, McpSchema, McpTest, Tool, and Toolkit are all tagged @stability unstable, and McpClient is @stability experimental: pin Effect, and re-check this guide when you upgrade.
The Model Context Protocol (MCP) lets an agent host discover what your application can do and call it: tools to act, resources to read, prompts to start a task. effect/ai/McpServer turns a Toolkit and a few Layers into a server. It handles JSON-RPC framing, protocol negotiation, JSON Schema generation, argument decoding, and result encoding. Everything that makes the server safe to expose is still yours: who the caller is, which tenant they act for, what they are allowed to change, and what happens when a call arrives twice.
This guide builds that server for a compensation platform. It assumes you already know Effect services and Layers, HttpRouter, and Tool/Toolkit. For API inventories it links to the concise AI & Language Models reference instead of repeating them.
What you will build. An acme-comp MCP server that:
exposes salary bands, eligible employees, and draft merit proposals as curated tools, a band resource template, and a review prompt;
runs over stdio for desktop clients and over Streamable HTTP for remote agents, serving the stateless 2026-07-28 revision and the session-based 2025-11-25 revision from one endpoint;
acts as an OAuth resource server: a public metadata route, a bearer-token middleware that provides a Principal, and scope checks inside handlers;
asks the user to confirm a submission, by elicitation on session clients and by a sealed InputRequired round trip on stateless clients;
reads the caller through request-level dependencies that the compiler will not let you forget;
collapses retried writes with idempotency keys, reports internal faults, and is tested in-process without opening a socket.
An MCP server is an external interface, like an HTTP API. It is not how your own application talks to a model. Inside the process, a model call takes a Toolkit directly: LanguageModel.generateText({ toolkit, ... }) decodes the model's tool calls and runs your handlers (see Building a Production AI Capability). Add MCP when another process — a desktop assistant, an IDE, a third-party agent — needs to discover and invoke those capabilities.
The same Toolkit value serves both surfaces. Define each tool once with Tool.make, implement handlers once with toolkit.toLayer, then pass the toolkit to LanguageModel in-process and register it with McpServer.toolkit for external clients. The handlers do not know which surface called them, which is the point: authorization and tenancy live in the handlers, so both surfaces enforce the same rules.
What the server owns. Protocol negotiation per client, tools/list / resources/list / prompts/list, JSON Schema for each tool's parameters and output, decoding arguments through your Schema, encoding results, mapping handler outcomes to wire results, list-changed notifications, and completions for resource and prompt parameters.
What you own. Authentication, tenant binding, per-tool authorization, confirmation of consequential actions, idempotency, rate limits, request-size limits, and audit records. Protocol negotiation is not authorization.
What Effect does not ship. Say this plainly in design reviews so nobody waits for it:
Only a minimal MCP client.McpClient (experimental) discovers and calls a remote server's tools, prompts, resources, and Agent Skills on 2025-11-25 or 2026-07-28, and McpClient.toolkit hands the remote tools (or an approved snapshot of them) to a model. It has no OAuth, retries, sampling, elicitation, or subscriptions, and remote tools still follow the rules for dynamic and MCP-sourced tools.
No OAuth helpers. Nothing verifies tokens, serves protected-resource metadata, or issues challenges. You write a middleware and a route; this guide shows both.
No Tasks extension helpers. Long-running work has no built-in task handle. Return a job id from a tool and expose its status as a tool or resource. The server's extensions option advertises extension capabilities, but implementing an extension is your code.
No full legacy HTTP transport.layerHttp implements the single-endpoint Streamable HTTP topology only: no standalone GET event stream, no event resumption, and no session expiry. Client-initiated session termination is available as an opt-in: pass allowSessionTermination: true and DELETE on the session path interrupts active requests and returns 404 for subsequent ones.
stdio (McpServer.layerStdio) — the client starts your server as a subprocess and speaks newline-delimited JSON-RPC over stdin/stdout. Use it for desktop assistants and IDEs on the user's machine. The process runs as the user, so authentication is the operating system's job. Stdout carries protocol frames only: route logs to stderr, or the first log line corrupts the stream. When the client closes stdin, accepted requests finish, open subscriptions end, and the process exits with code 0.
Streamable HTTP (McpServer.layerHttp) — your server listens and remote clients POST JSON-RPC to one path. Use it for shared, multi-tenant deployments. You must authenticate every request.
layerHttp provides McpServer, can fail to build with Cause.IllegalArgumentError, and requires HttpRouter.HttpRouter plus whatever its registrations still need per request (next section): it registers a POST route at path on whatever router is in context, and answers GET, PUT, PATCH, and OPTIONS on that path with 405. DELETE also returns 405 unless session termination is explicitly enabled. Its boundary checks are strict:
a request that carries an Origin header gets 403 unless that exact origin is in allowedOrigins; requests without Origin (command-line agents, server-to-server calls) pass;
POST requires Content-Type: application/json (415 otherwise) and an Accept header listing both application/json and text/event-stream (406 otherwise);
a POST that carries only notifications is answered with 202.
Because OPTIONS returns 405, the endpoint does not answer browser CORS preflights. Most MCP clients are not browsers; if one is, make that decision deliberately in front of the route.
For a serverless host such as Cloudflare Workers, choose McpServer.layerHttpRequestScoped instead: every POST owns its server until its response body completes, so no server fiber, timer, or queue consumer survives the request. It only accepts stateless adapters (use [McpProtocol.v2026_07_28]), retains tools/resources/prompts/completions and sealed InputRequired round trips, and forwards request-local progress/logs. It has no sessions, legacy elicit, subscriptions, broadcast list changes, or DELETE termination. Discovery reports listChanged: false; subscriptions/listen is method-not-found. The dual-era example below deliberately stays on long-lived layerHttp; do not swap its transport while retaining the session adapter. A long-lived endpoint may independently opt out of stateless subscriptions with allowSubscriptions: false.
protocols is a non-empty list of adapters. Effect ships five: McpProtocol.v2024_11_05, v2025_03_26, v2025_06_18, and v2025_11_25, which are session-based (the client sends initialize, the server issues a session), and v2026_07_28, which is stateless. One endpoint can serve several eras at once, so old and new clients share a deployment. Two rules apply:
At most one stateless adapter. Listing two fails the server layer with IllegalArgumentError when it builds.
The list is the contract. A session client that offers an unlisted version on initialize is answered with the first session adapter in your list, and the client decides whether to continue. Do not list revisions you have not tested.
2026-07-28 removes initialize and protocol sessions. Every request carries its protocol version, client capabilities, and client identity in params._meta, and HTTP requests repeat the method (and, for calls, the tool name) in Mcp-Method / Mcp-Name headers. A client can call server/discover to read the server's identity, capabilities, and instructions, and receives list-changed notifications through subscriptions/listen when the transport can push. Design for these consequences:
Context is per request.McpSchema.McpRequestContext is rebuilt for every call. There is no session to stash state in, and no McpSchema.McpServerClient, so the server cannot send requests back to the client mid-call. Anything that must survive between two calls travels in the requestState string you hand to the client — see Human in the loop.
Any replica can answer. Session-era sessions live in an in-memory map in the process that issued them, so session clients need sticky routing; stateless requests do not.
Delivery is at most once per attempt. A client that loses a response retries with a new JSON-RPC id. The server cannot tell a retry from a new intent, so writes need idempotency keys derived from the intent, never from the request id.
Cancellation is a closed stream. On stateless HTTP, notifications/cancelled is accepted and ignored; the client cancels by closing the response stream, which interrupts your handler's fiber. Interruption can land anywhere before your commit, so make writes atomic and idempotent.
Logging and progress follow the request. A per-request log level in _meta sets References.CurrentLogLevel for the handler, and progress notifications reach the client only for the progressToken its request carried, and only until that request completes, is cancelled, or disconnects.
Traces follow the client. A W3C traceparent in params._meta parents the server's tools/call <name> span, so one trace spans the agent and your handlers (see Tracing).
Capabilities are registration Layers that require McpServer; hand them to the transport as its registrations option, so they are registered before the first request is read. Every service a handler reads is a request-level dependency: it stays in the Layer's type as McpServer.McpRequest<"Requires", S> until MCP middleware or the transport discharges it, and Layer.provide(Layer.succeed(S, ...)) does not. layerHttp turns the markers it cannot discharge into HttpRouter requirements, so the same bearer-token route middleware that answers 401 also supplies the caller to handlers; on stdio an MCP middleware has to. A composition that forgets either one does not compile.
Migration: 4.0 code provided the transport to the capabilities (CompCapabilities.pipe(Layer.provide(McpServer.layerHttp(...)))) and read the caller with Effect.serviceOption to keep it out of the toolkit Layer's requirements. Pass registrations instead, and declare the caller as a tool dependency.
Runnable. One set of capabilities, two transports. CompCapabilities is the Layer the next section builds; both transports share the same identity and protocol list.
Fragment · Type-checked
ts
import { NodeHttpServer, NodeRuntime, NodeStdio } from "@effect/platform-node"import { Context, Effect, Layer, Logger } from "effect"import { McpProtocol, McpServer } from "effect/ai"import { HttpRouter } from "effect/http"import { createServer } from "node:http"class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string readonly scopes: ReadonlySet<string>}>()("acme/Principal") {}// Toolkit, resources, and prompts — built in "Shape the catalog". Registrations need// the McpServer service, and their handlers read the caller per request.declare const CompCapabilities: Layer.Layer< never, never, McpServer.McpServer | McpServer.McpRequest<"Requires", Principal>>// Verifies the bearer token for HTTP requests (see "Authorize as an OAuth resource server").declare const BearerAuth: HttpRouter.Middleware<{ provides: Principal handles: never error: never requires: never layerError: never layerRequires: never}>// The OS user who launched the stdio process.declare const localPrincipal: Principal["Service"]const identity = { name: "acme-comp", version: "1.6.0", // Returned by `initialize` and `server/discover`: tell the client how to use the server. instructions: "Compensation planning for the caller's tenant. Read bands and employees freely. " + "Draft proposals with comp_draft_proposal; nothing is submitted until the user confirms " + "comp_submit_proposals.", // One stateless revision, one session revision. A session client offering an unlisted // version on `initialize` is answered with the first session adapter in this list. protocols: [McpProtocol.v2026_07_28, McpProtocol.v2025_11_25]} as const// Streamable HTTP: one POST endpoint on the router that `HttpRouter.serve` builds. The// per-request Principal becomes an HttpRouter requirement that BearerAuth satisfies.export const HttpMcp = McpServer.layerHttp({ ...identity, path: "/mcp", // Browser-originated requests must come from these exact origins, or get 403. allowedOrigins: ["https://comp.acme.example"], registrations: CompCapabilities}).pipe(Layer.provide(BearerAuth.layer))// stdio has no HTTP request, so an MCP middleware supplies the Principal for every request.const LocalUser = McpServer.middleware<{ provides: Principal }>()((effect) => Effect.provideService(effect, Principal, localPrincipal))// stdio: the client launches this process; stdout carries protocol frames only.export const StdioMcp = McpServer.layerStdio({ ...identity, registrations: CompCapabilities.pipe(Layer.provide(LocalUser.layerGlobal))}).pipe( Layer.provide(NodeStdio.layer), Layer.provide(Layer.succeed(Logger.LogToStderr)(true)))const HttpServerLive = HttpRouter.serve(HttpMcp).pipe( Layer.provide(NodeHttpServer.layer(createServer, { port: 8080 })))if (process.argv.includes("--stdio")) { Layer.launch(StdioMcp).pipe(NodeRuntime.runMain)} else { Layer.launch(HttpServerLive).pipe(NodeRuntime.runMain)}
HttpMcp goes straight into HttpRouter.serve. Every entrypoint builds its own router in a forked memo map, so a route provided with its own HttpRouter.layer inside the argument is never mounted, and a stateful service first built inside the argument is private to that entrypoint (see the HttpRouter warning). Provide shared services — database clients, repositories, the token verifier — outside serve, as the authorization section does.
A reusable task template that steers the model through your tools
review-merit-proposals
When in doubt, make it a tool: every client supports tools, and support for resources and prompts varies by host. Never make a write a resource or a prompt.
To teach agents a workflow across several tools — "read the band before drafting, never submit without confirmation" — publish an Agent Skill with McpServer.skill: a SKILL.md plus supporting files that hosts with the Skills extension discover and load. A skill is guidance, like a description; it never grants permissions, and handlers keep enforcing every rule it states.
The model reads names, descriptions, and parameter descriptions to decide what to call. Write them for that reader:
One verb per tool, a stable prefix.comp_search_employees, not employees or manage_comp. The prefix keeps names unique when a host loads several servers.
Say what it returns, what it does not do, and what to call next. "Does not return salary amounts", "nothing is submitted by this call".
Describe parameters, bound them, and give an example value.Schema.Int.check(Schema.isBetween(...)) both validates and appears in the JSON Schema.
Never accept the tenant, the actor, or a role as an argument. Those come from the verified token. If the parameter schema has no tenantId, the model cannot pass one.
Annotations become MCP tool hints: Tool.Title → title, Tool.Readonly → readOnlyHint, Tool.Destructive → destructiveHint, Tool.Idempotent → idempotentHint, Tool.OpenWorld → openWorldHint. The protocol defaults are pessimistic — a tool is assumed destructive and open-world unless you say otherwise — so annotate safe tools explicitly. Hints are advisory: a host may use them to decide when to ask the user, but clients are told not to trust them from untrusted servers, and your handler must enforce what the hint claims.
Tool.Strict changes validation, not just advertising. A strict tool advertises additionalProperties: false and the server rejects undeclared argument keys; a non-strict tool advertises additionalProperties: true and drops them. Use strict mode on writes, where a misspelled argument should fail rather than be ignored. Parameters must encode to an object-root JSON Schema (a Schema.Struct); use Tool.EmptyParams for a tool without parameters.
Contextual.CompData is the tenant-scoped application port and Principal is the service the authorization section's middleware provides; both are declared so the block compiles alone.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"// The verified caller of the current request (see "Authorize as an OAuth resource server").class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string readonly scopes: ReadonlySet<string>}>()("acme/Principal") {}class BandNotFound extends Schema.TaggedError<BandNotFound>()("BandNotFound", { message: Schema.String}) {}const SalaryBand = Schema.Struct({ jobFamily: Schema.String, level: Schema.String, currency: Schema.String, min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite})const EmployeeSummary = Schema.Struct({ employeeId: Schema.String, displayName: Schema.String, level: Schema.String, compaRatio: Schema.Finite.annotate({ description: "Current base pay divided by band midpoint" })})const DraftedProposal = Schema.Struct({ proposalId: Schema.String, withinBand: Schema.Boolean, warnings: Schema.Array(Schema.String)})// Every method takes the tenant first; no query runs without it.class CompData extends Context.Service<CompData, { readonly band: ( tenantId: string, jobFamily: string, level: string ) => Effect.Effect<typeof SalaryBand.Type, BandNotFound> readonly searchEmployees: ( tenantId: string, query: { readonly cycleId: string; readonly managerId?: string | undefined; readonly limit: number } ) => Effect.Effect<ReadonlyArray<typeof EmployeeSummary.Type>> readonly draftProposal: ( tenantId: string, author: string, input: { readonly cycleId: string; readonly employeeId: string; readonly increasePct: number } ) => Effect.Effect<typeof DraftedProposal.Type>}>()("acme/CompData") {}const GetSalaryBand = Tool.make("comp_get_salary_band", { description: "Return min, mid and max base pay for one job family and level in the caller's " + "current band table. Call before drafting a proposal to check the target salary.", parameters: Schema.Struct({ jobFamily: Schema.String.annotate({ description: 'Job family code, e.g. "ENG"' }), level: Schema.String.annotate({ description: 'Level code, e.g. "L5"' }) }), success: SalaryBand, failure: BandNotFound, // declared: the client sees its message as an isError result dependencies: [Principal] // request-level: supplied by middleware for every call}) .annotate(Tool.Title, "Get salary band") .annotate(Tool.Readonly, true) .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false)const SearchEmployees = Tool.make("comp_search_employees", { description: "List employees eligible in a compensation cycle, optionally for one manager. " + "Returns at most `limit` rows (default 25). Does not return salary amounts.", parameters: Schema.Struct({ cycleId: Schema.String.annotate({ description: 'Cycle id, e.g. "FY27-merit"' }), managerId: Schema.optional(Schema.String), limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))) }), success: Schema.Struct({ employees: Schema.Array(EmployeeSummary) }), dependencies: [Principal]}) .annotate(Tool.Readonly, true) .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false)const DraftProposal = Tool.make("comp_draft_proposal", { description: "Create or replace the caller's draft merit proposal for one employee in an open " + "cycle, validated against the band. Nothing is submitted or paid by this call; submission " + "happens in comp_submit_proposals after the user confirms.", parameters: Schema.Struct({ cycleId: Schema.String, employeeId: Schema.String, increasePct: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 25 })) }), success: DraftedProposal, dependencies: [Principal]}) .annotate(Tool.Destructive, false) // replaces only the caller's own draft .annotate(Tool.Idempotent, true) // same arguments, same draft .annotate(Tool.OpenWorld, false) .annotate(Tool.Strict, true) // reject undeclared argument keys // Drafting leads to a confirmation step; clients that cannot show a form never see it. .annotate(McpSchema.EnabledWhen, ({ capabilities }) => capabilities.elicitation !== undefined)// Declaration order is registration order, and `tools/list` preserves it.export const CompToolkit = Toolkit.make(GetSalaryBand, SearchEmployees, DraftProposal)export const CompToolkitHandlers = CompToolkit.toLayer(Effect.gen(function*() { const data = yield* CompData return CompToolkit.of({ comp_get_salary_band: Effect.fn("comp_get_salary_band")(function*({ jobFamily, level }) { const principal = yield* Principal return yield* data.band(principal.tenantId, jobFamily, level) }), comp_search_employees: Effect.fn("comp_search_employees")(function*({ cycleId, managerId, limit }) { const principal = yield* Principal const employees = yield* data.searchEmployees(principal.tenantId, { cycleId, managerId, limit: limit ?? 25 }) return { employees } }), comp_draft_proposal: Effect.fn("comp_draft_proposal")(function*(input) { const principal = yield* Principal return yield* data.draftProposal(principal.tenantId, principal.subject, input) }) })}))// The same CompToolkit can be passed to LanguageModel.generateText in-process, where// the caller provides Principal like any other service. Here it stays a request-level// requirement of CompTools until the transport's middleware supplies it.export const CompTools = McpServer.toolkit(CompToolkit).pipe(Layer.provide(CompToolkitHandlers))
What a client receives for each handler outcome — success, invalid arguments, declared failure, internal fault — differs by protocol era and is listed in the tool outcome table. The short version: declared failures are part of the contract and reach the client as written; everything else becomes a fixed internal-error message.
McpSchema.EnabledWhen is an annotation holding a predicate over { protocolVersion, capabilities, clientInfo }. The server evaluates it for each client: a tool whose predicate is false is left out of that client's tools/list, and a direct tools/call for it fails as "tool not found". Resources, resource templates, and prompts registered with annotations obey it too (McpServer.prompt takes an annotations option; for resources use McpServer.registerResource, since the resource Layer constructor has no annotations option).
Use it to keep the catalog honest per client: hide write tools from clients that cannot confirm, hide a tool that returns InputRequired from session-era clients, hide tools whose output only renders on a newer revision. Do not use it for authorization. protocolVersion, capabilities, and clientInfo are what the client says about itself; any caller can claim any client name. Scopes are checked in handlers.
A resource template turns typed URI parameters into a read; completions help the host fill them in. A prompt is a parameterized message the user picks from a menu. Both run with the same per-request context as tools, so they read the principal the same way.
Contextual. The store functions are declared; the API reference for resource and prompt options is in the McpServer section.
Fragment · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"import { McpSchema, McpServer } from "effect/ai"class Principal extends Context.Service<Principal, { readonly tenantId: string }>()("acme/Principal") {}declare const bandRowJson: (tenantId: string, jobFamily: string, level: string) => Effect.Effect<string>const jobFamily = McpSchema.param("jobFamily", Schema.String)const level = McpSchema.param("level", Schema.String)// Advertised as the template comp://bands/{jobFamily}/{level}; parameters arrive decoded.export const BandResource = McpServer.resource`comp://bands/${jobFamily}/${level}`({ name: "Salary band", description: "The caller's current band table row for one job family and level, as JSON.", mimeType: "application/json", completion: { level: (prefix) => Effect.succeed(["L3", "L4", "L5", "L6", "L7"].filter((l) => l.startsWith(prefix))) }, content: Effect.fn("BandResource")(function*(_uri, jobFamily, level) { // Reading a service in a resource handler makes it request-level, like a tool dependency. const principal = yield* Principal return yield* bandRowJson(principal.tenantId, jobFamily, level) })})export const ReviewPrompt = McpServer.prompt({ name: "review-merit-proposals", title: "Review a manager's merit proposals", description: "Walk through the draft proposals in one org unit and flag band and budget exceptions.", parameters: { cycleId: Schema.String, orgUnit: Schema.String.annotate({ description: 'Org unit code, e.g. "ENG-PLATFORM"' }) }, // A string becomes one user message; return PromptMessage values for multi-turn templates. content: ({ cycleId, orgUnit }) => Effect.succeed( `Review every draft merit proposal for ${orgUnit} in cycle ${cycleId}. Use ` + `comp_search_employees and comp_get_salary_band, list proposals above band in a table ` + `with a recommendation, and do not submit anything.` )})export const CompContent = Layer.mergeAll(BandResource, ReviewPrompt)
Resource and prompt content is data the model will read, so it is untrusted on the way back in: a manager's free-text justification inside a resource can carry instructions aimed at the model. Label such fields as user-authored text in descriptions and keep them out of anything your server interprets.
Serviceful schemas stay serviceful here: resource-template and prompt registration require their parameter decoding services, plus the encoding services of parameters with completions, as ordinary registration-time requirements. Supply these when composing capability Layers. What content and completion handlers read is request-level instead. Compilation catching a missing service is a real wiring failure, not a reason to cast away the Layer's requirements.
Merge all capabilities into one Layer — Layer.mergeAll(CompTools, CompContent, WriteTools, SubmitProposals), built in the sections below — and that is the CompCapabilities the bootstrap passes as registrations. Registration across separate capability Layers follows Layer build order, so if the order of tools/list matters to you, put the tools of one surface in one toolkit (Toolkit.merge combines toolkits).
There are three common ways to put an application API in front of an agent. They are not exclusive.
Curated tools. One schema-first tool per domain operation, as above. Behavior is predictable, each tool carries its own authorization and confirmation rules, and descriptions can teach the model the workflow. The cost is catalog size: every operation is a tool the host has to load.
Query tools. A small set of meta-tools — search the schema, validate a query, run a read-only query — over a typed query surface such as a GraphQL schema or a set of SQL views. Reads become flexible with three tools instead of thirty. The guards must live below the model: parse the query, allow exactly one read-only operation, cap depth, cost, and rows, enforce tenant filters and field-level scopes in the resolvers rather than in the query text, and treat user-authored fields in results as untrusted data.
Code mode. The host has the model write a short program against a typed client generated from your tool schemas and runs it in the host's own sandbox, chaining calls without a model turn between each. Nothing changes on your server, except that precise parameter and output schemas pay off more.
Recommendation. Curate every write, each with its own scope check, confirmation, and idempotency. Add one read-only query tool only when curated reads stop scaling, and guard it at the parser. Keep the catalog small — tens of tools, not hundreds — in a deterministic order, trim it per client with EnabledWhen, and let hosts that support progressive discovery or tool search handle a large catalog on their side. Treat tool names as part of the security model: hosts key allow-lists and remembered approvals on them, so a rename is a breaking, security-relevant change, and a generic name can collide with another server's tool.
A remote MCP server is an OAuth 2.1 protected resource. The authorization server — your identity provider — issues access tokens; your server only verifies them and enforces what they grant. layerHttp leaves authentication to the surrounding HTTP server, so you add three pieces:
Protected-resource metadata (RFC 9728) at /.well-known/oauth-protected-resource/mcp, public, naming the resource, its authorization servers, and supported scopes. Clients read it to find where to get a token.
A bearer-token middleware on the MCP route. No token or a bad token gets 401 with a WWW-Authenticate: Bearer challenge that points at the metadata URL; a token without the baseline scope gets 403 with error="insufficient_scope" and the needed scope. A valid token becomes a Principal service for the rest of the request.
Per-tool scope checks in handlers, because the HTTP layer sees one endpoint, not which tool the JSON-RPC body calls.
Token verification itself — signature against the issuer's keys, issuer, audience equal to your canonical resource URI, expiry, not-before — is not part of Effect 4. Use a JOSE library behind a service, so tests can substitute it.
Runnable shape.TokenVerifierLive and CompCapabilities are declared; everything else is the code you deploy.
Fragment · Type-checked
ts
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"import { Context, Effect, Layer, Option, Schema } from "effect"import { McpProtocol, McpServer } from "effect/ai"import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"import { createServer } from "node:http"const RESOURCE = "https://mcp.acme.example/mcp" // canonical resource URI = required token audienceconst METADATA_URL = "https://mcp.acme.example/.well-known/oauth-protected-resource/mcp"export class Unauthenticated extends Schema.TaggedError<Unauthenticated>()("Unauthenticated", { reason: Schema.String}) {}// Tenant, subject, client, and scopes come from verified token claims only.export class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string readonly clientId: string readonly scopes: ReadonlySet<string>}>()("acme/Principal") {}export class TokenVerifier extends Context.Service<TokenVerifier, { readonly verify: (token: string) => Effect.Effect<Principal["Service"], Unauthenticated>}>()("acme/TokenVerifier") {}declare const TokenVerifierLive: Layer.Layer<TokenVerifier> // JOSE library + the issuer's JWKSdeclare const CompCapabilities: Layer.Layer< never, never, McpServer.McpServer | McpServer.McpRequest<"Requires", Principal>>const challenge = (status: 401 | 403, error: "invalid_token" | "insufficient_scope", scope?: string) => HttpServerResponse.empty({ status, headers: { "www-authenticate": `Bearer realm="mcp", error="${error}"` + (scope === undefined ? "" : `, scope="${scope}"`) + `, resource_metadata="${METADATA_URL}"` } })export const ProtectedResourceMetadata = HttpRouter.add( "GET", "/.well-known/oauth-protected-resource/mcp", HttpServerResponse.jsonUnsafe({ resource: RESOURCE, authorization_servers: ["https://auth.acme.example"], scopes_supported: ["comp:read", "comp:write"], bearer_methods_supported: ["header"] }))export const BearerAuth = HttpRouter.middleware<{ provides: Principal }>()( Effect.gen(function*() { const verifier = yield* TokenVerifier return (httpEffect) => Effect.gen(function*() { const request = yield* HttpServerRequest.HttpServerRequest const header = request.headers["authorization"] if (header === undefined || !/^bearer /i.test(header)) return challenge(401, "invalid_token") const principal = yield* Effect.option(verifier.verify(header.slice(7))) if (Option.isNone(principal)) return challenge(401, "invalid_token") // Baseline scope at the edge; per-tool scopes are checked in handlers. if (!principal.value.scopes.has("comp:read")) return challenge(403, "insufficient_scope", "comp:read") return yield* Effect.provideService(httpEffect, Principal, principal.value) }) }))const McpRoutes = McpServer.layerHttp({ name: "acme-comp", version: "1.6.0", path: "/mcp", protocols: [McpProtocol.v2026_07_28, McpProtocol.v2025_11_25], allowedOrigins: ["https://comp.acme.example"], // Their request-level Principal becomes an HttpRouter requirement... registrations: CompCapabilities}).pipe( // ...which this route middleware satisfies. It wraps the routes registered while this // Layer builds: the MCP endpoint. The metadata route is merged beside it and stays public. Layer.provide(BearerAuth.layer))HttpRouter.serve(Layer.mergeAll(ProtectedResourceMetadata, McpRoutes)).pipe( // Shared services are provided outside the entrypoint, so they are built once. Layer.provide(TokenVerifierLive), Layer.provide(NodeHttpServer.layer(createServer, { port: 8080 })), Layer.launch, NodeRuntime.runMain)
The middleware applies to the MCP endpoint because router.add reads route middleware from the context in which the route is registered, and layerHttp registers its routes while it builds inside McpRoutes. Remove Layer.provide(BearerAuth.layer) and McpRoutes no longer compiles, because nothing provides the handlers' Principal.
The Principal provided by the middleware reaches tool, resource, and prompt handlers, which run with the HTTP request's services. Read it as an ordinary service:
Declare it as a tool dependency.Tool.make(..., { dependencies: [Principal] }) lets the handler yield* Principal, and makes it a request-level requirement of the McpServer.toolkit Layer rather than a startup one. Resource and prompt handlers declare it by reading it.
A Principal in the Layer graph is not a substitute. Providing one with Layer.provide does not discharge the request-level requirement, and if a registration did capture one, the request's own services take precedence on every call. Only middleware supplies the caller.
Low-level addTool handlers are the exception. They may require only McpRequestContext, so the dual-era gate below reads the principal with Effect.serviceOption and dies when it is missing: that means the server was mounted without the middleware, a deployment fault, so the call returns the fixed internal-error result and the cause is logged and reported.
Contextual.Proposals is the tenant-scoped port; the toolkit is merged into CompCapabilities like the read tools.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Schema } from "effect"import { McpServer, Tool, Toolkit } from "effect/ai"export class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string readonly clientId: string readonly scopes: ReadonlySet<string>}>()("acme/Principal") {}export class InsufficientScope extends Schema.TaggedError<InsufficientScope>()("InsufficientScope", { scope: Schema.String, message: Schema.String}) {}export const requireScope = (scope: string) => Effect.flatMap(Principal, (principal) => principal.scopes.has(scope) ? Effect.succeed(principal) : Effect.fail( new InsufficientScope({ scope, message: `This tool needs the ${scope} scope; ask the user to re-authorize.` }) ))class Proposals extends Context.Service<Proposals, { readonly withdraw: (tenantId: string, author: string, proposalId: string) => Effect.Effect<boolean>}>()("acme/Proposals") {}const WithdrawProposal = Tool.make("comp_withdraw_proposal", { description: "Withdraw one of the caller's draft proposals. Requires the comp:write scope.", parameters: Schema.Struct({ proposalId: Schema.String }), success: Schema.Struct({ withdrawn: Schema.Boolean }), failure: InsufficientScope, // declared, so the model reads the re-authorize hint dependencies: [Principal]}) .annotate(Tool.Destructive, true) .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false)const WriteToolkit = Toolkit.make(WithdrawProposal)export const WriteTools = McpServer.toolkit(WriteToolkit).pipe( Layer.provide(WriteToolkit.toLayer(Effect.gen(function*() { const proposals = yield* Proposals return WriteToolkit.of({ comp_withdraw_proposal: Effect.fn("comp_withdraw_proposal")(function*({ proposalId }) { const principal = yield* requireScope("comp:write") // Tenant and author come from the token, never from arguments. const withdrawn = yield* proposals.withdraw(principal.tenantId, principal.subject, proposalId) return { withdrawn } }) }) }))))
Tenant isolation is a data-layer rule. Repositories take the tenant as their first argument and filter every query by it; handlers pass principal.tenantId and nothing else. A test should show that a principal from tenant A asking for tenant B's employee gets nothing, whatever the arguments say.
Do not pass the client's token downstream. The access token's audience is your MCP server. Calling another API with it (token passthrough) is forbidden: that API cannot tell who it is really serving, and your server becomes a confused deputy. Exchange the token for one scoped to the downstream API, or call it with your own service credentials and pass the principal as data.
Audit with the token's identities. Record subject, clientId, tenant, tool name, and the idempotency key for every write. McpRequestContext.clientInfo is self-reported; use it for diagnostics only.
Some writes need a person to confirm what will happen: submitting a cycle's proposals notifies HR and locks them. The model must not be able to confirm on the user's behalf, so the confirmation has to come back through the client, from the user. The two protocol eras do this differently.
On session-based revisions (form elicitation needs 2025-06-18 or later), the server can send requests to the client in the middle of a call. McpServer.elicit({ message, schema }) sends elicitation/create with a JSON Schema derived from schema, waits, and decodes the accepted content with the same schema. It needs McpSchema.McpServerClient, which exists only for initialized session clients.
Accept returns the decoded value.
Decline fails with McpSchema.ElicitationDeclined. A client that did not advertise the elicitation capability, or a revision without elicitation, also ends in ElicitationDeclined, with the reason in its cause.
Cancel interrupts the handler: the user abandoned the whole operation.
On Streamable HTTP the elicitation request travels on the tool call's event stream and the client answers with a separate POST, so the call stays open while the user decides.
2026-07-28 has no server-to-client requests. Instead, a handler returns new McpSchema.InputRequired({ inputRequests, requestState }). The client shows the requests to the user (elicitation/create, sampling/createMessage, or roots/list), then calls the same tool again with the same arguments, the answers in inputResponses keyed as you named them, and your requestState string echoed back unchanged. The second call is a new request: it may land on another replica, minutes later. The handler reads inputResponses and requestState from McpSchema.McpRequestContext.
Rules the server enforces for you:
At least one of inputRequests or requestState is required.
If an input request needs a capability the client did not advertise, the call fails with protocol error -32021 and data.requiredCapabilities, and your handler's result is not sent. An empty elicitation: {} capability counts as form support.
A session-era client that receives InputRequired gets a protocol error, so hide such tools from session clients or branch on protocolVersion, as the gate below does.
If the handler fails with McpSchema.InvalidParams while continuation fields are present, the client receives JSON-RPC -32602; on a first-round call the same failure is reported as an isError result.
requestState is the only memory between rounds, and it comes back from the client. Treat it as attacker-controlled: a client can replay it, alter it, or hand it to someone else. Seal it.
Integrity. HMAC-SHA256 over the encoded payload with a server secret, compared in constant time. The block below uses node:crypto; on runtimes without it, effect/crypto/Mac (Mac.hmacSha256, Mac.timingSafeEqual) and SecureRandom provide the same primitives as services.
Expiry and freshness. An expiry timestamp and a random nonce inside the sealed payload.
Binding. The tenant, the subject, and a digest of the exact arguments, checked against the current principal and arguments in round 2.
Only what round 1 proved. Store the proposal ids and the total the user is shown, not a flag that says "approved".
Runnable. A self-contained service; provide RequestState.layer beside the other shared services, with the secret in Config and rotated like any other key.
The nonce makes every sealed state unique; it does not by itself stop a replay within the expiry window. Make round 2 idempotent — the next block keys the submission on the proposal ids — so a replayed state reproduces the same outcome instead of a second submission. Record consumed nonces as well if a replay must be rejected outright.
A toolkit handler must return the tool's success type, so it cannot return InputRequired. A tool that needs the stateless round trip is registered at the lower level, through the McpServer.McpServer service's addTool, with a hand-written McpSchema.Tool descriptor and a handler that returns CallToolResult | InputRequired, may fail only with InternalError | InvalidParams, and may require only McpRequestContext. In exchange you own everything the toolkit path does for you: decode the arguments, build the result, and map failures.
Contextual. The ports from the previous blocks are repeated as declarations so this block compiles alone. Merge SubmitProposals into CompCapabilities; it needs McpServer.McpServer, which the transport Layer provides.
Self-contained source · Type-checked
ts
import { Context, Effect, Layer, Option, Schema } from "effect"import { McpSchema, McpServer } from "effect/ai"import { createHash } from "node:crypto"class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string readonly scopes: ReadonlySet<string>}>()("acme/Principal") {}// A low-level handler may require only McpRequestContext, so read the caller optionally// and fail closed: a missing Principal means the route was mounted without its middleware.const currentPrincipal = Effect.serviceOption(Principal).pipe( Effect.flatMap(Option.match({ onNone: () => Effect.die("MCP handler ran without an authenticated Principal"), onSome: (principal) => Effect.succeed(principal) })))interface PendingSubmission { readonly tenantId: string readonly subject: string readonly argumentsDigest: string readonly proposalIds: ReadonlyArray<string> readonly totalIncrease: number}class InvalidRequestState extends Schema.TaggedError<InvalidRequestState>()("InvalidRequestState", { reason: Schema.String}) {}class RequestState extends Context.Service<RequestState, { readonly seal: (pending: PendingSubmission) => Effect.Effect<string> readonly open: (token: string) => Effect.Effect<PendingSubmission, InvalidRequestState>}>()("acme/RequestState") {}class TotalChanged extends Schema.TaggedError<TotalChanged>()("TotalChanged", {}) {}class Proposals extends Context.Service<Proposals, { readonly drafts: ( tenantId: string, author: string, cycleId: string ) => Effect.Effect<ReadonlyArray<{ readonly proposalId: string; readonly increase: number }>> // Atomic: re-checks the total and records the key in the same transaction. readonly submit: ( tenantId: string, proposalIds: ReadonlyArray<string>, options: { readonly submittedBy: string; readonly expectedTotal: number; readonly idempotencyKey: string } ) => Effect.Effect<{ readonly batchId: string }, TotalChanged>}>()("acme/Proposals") {}const SubmitArgs = Schema.Struct({ cycleId: Schema.String })const Confirmation = Schema.Struct({ confirm: Schema.Boolean })const isConfirmation = Schema.is(Confirmation)const confirmationJsonSchema = { type: "object", properties: { confirm: { type: "boolean", title: "Submit these proposals" } }, required: ["confirm"]}const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex")const textResult = (text: string, isError = false) => new McpSchema.CallToolResult({ content: [{ type: "text", text }], isError })const SubmitProposalsTool = new McpSchema.Tool({ name: "comp_submit_proposals", title: "Submit merit proposals", description: "Submit all of the caller's draft proposals in a cycle for HR approval. Shows the " + "user the count and total first and submits only after they confirm. Requires comp:write.", inputSchema: { type: "object", properties: { cycleId: { type: "string" } }, required: ["cycleId"], additionalProperties: false }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }})export const SubmitProposals = Layer.effectDiscard(Effect.gen(function*() { const server = yield* McpServer.McpServer const proposals = yield* Proposals const requestState = yield* RequestState const commit = (principal: Principal["Service"], pending: PendingSubmission) => proposals.submit(principal.tenantId, pending.proposalIds, { submittedBy: principal.subject, expectedTotal: pending.totalIncrease, // Same intent, same key: a retried round 2 or a duplicate call submits once. idempotencyKey: digest(["comp_submit_proposals", principal.tenantId, pending.proposalIds]) }).pipe( Effect.map(({ batchId }) => new McpSchema.CallToolResult({ content: [{ type: "text", text: `Submitted ${pending.proposalIds.length} proposals as ${batchId}.` }], structuredContent: { batchId, submitted: pending.proposalIds.length } }) ), Effect.catchTag("TotalChanged", () => Effect.succeed(textResult("Not submitted: the proposals changed after confirmation. Call again.", true))) ) yield* server.addTool({ tool: SubmitProposalsTool, // Clients without form elicitation cannot complete this tool, so they never see it. annotations: Context.make(McpSchema.EnabledWhen, ({ capabilities }) => capabilities.elicitation !== undefined), handle: Effect.fn("comp_submit_proposals")(function*(payload: unknown) { const args = yield* Schema.decodeUnknownEffect(SubmitArgs)(payload).pipe( Effect.mapError(() => new McpSchema.InvalidParams({ message: "Expected { cycleId: string }" })) ) const principal = yield* currentPrincipal if (!principal.scopes.has("comp:write")) { return textResult("This tool needs the comp:write scope; ask the user to re-authorize.", true) } const context = yield* McpSchema.McpRequestContext const argumentsDigest = digest(args) // Round 2 (stateless era): our sealed state and the user's answer came back. if (context.requestState !== undefined) { const pending = yield* requestState.open(context.requestState).pipe( Effect.mapError(() => new McpSchema.InvalidParams({ message: "requestState is invalid or expired" })) ) if ( pending.tenantId !== principal.tenantId || pending.subject !== principal.subject || pending.argumentsDigest !== argumentsDigest ) { return yield* new McpSchema.InvalidParams({ message: "requestState does not match this call" }) } const answer = context.inputResponses?.["confirm"] const content = answer?.content return answer?.action === "accept" && isConfirmation(content) && content.confirm ? yield* commit(principal, pending) : textResult("Not submitted: the user did not confirm.") } // Round 1 (both eras): compute exactly what the user is asked to confirm. const drafts = yield* proposals.drafts(principal.tenantId, principal.subject, args.cycleId) if (drafts.length === 0) return textResult(`No draft proposals in ${args.cycleId}.`) const pending: PendingSubmission = { tenantId: principal.tenantId, subject: principal.subject, argumentsDigest, proposalIds: drafts.map((draft) => draft.proposalId), totalIncrease: drafts.reduce((sum, draft) => sum + draft.increase, 0) } const message = `Submit ${drafts.length} merit proposals in ${args.cycleId} ` + `(total increase ${pending.totalIncrease}) for HR approval? This locks them.` if (context.protocolVersion === "2026-07-28") { return new McpSchema.InputRequired({ inputRequests: { confirm: { method: "elicitation/create", params: { mode: "form", message, requestedSchema: confirmationJsonSchema } } }, requestState: yield* requestState.seal(pending) }) } // Session era: ask over the open session and wait for the answer. const client = yield* Effect.serviceOption(McpSchema.McpServerClient) if (Option.isNone(client)) return textResult("This client cannot confirm submissions.", true) const confirmed = yield* McpServer.elicit({ message, schema: Confirmation }).pipe( Effect.provideService(McpSchema.McpServerClient, client.value), Effect.map(({ confirm }) => confirm), Effect.catchTag("ElicitationDeclined", () => Effect.succeed(false)) ) return confirmed ? yield* commit(principal, pending) : textResult("Not submitted: the user declined.") }) })}))
Read the gate as four guarantees. The user confirms the exact proposal ids and total computed in round 1. Round 2 accepts only a state this server sealed, for this principal and these arguments. The store re-checks the total inside the submit transaction, so a draft edited between rounds aborts instead of submitting an unconfirmed amount. The idempotency key turns a retried round 2 into the same batch.
Outcomes. The tool outcome table lists what a client receives for each toolkit handler outcome on each protocol era. Design to its two categories:
Declared failures (failure on Tool.make) are part of the contract. The client receives them as an isError: true result — the error's message under failureMode: "error" when it is an Error with a message, otherwise the payload's JSON encoding through the failure schema — and the server neither logs nor reports them. Use them for outcomes the model can act on: band not found, insufficient scope, a conflicting request id. They are visible to the client, so keep internal detail out.
Everything else — undeclared failures, defects, results that fail their own success schema — reaches the client only as a fixed internal-error message, and is logged at error level and handed to every configured ErrorReporter. Turn infrastructure failures into defects with Effect.orDie rather than widening the tool's contract with them.
In the low-level addTool path, the mapping is yours: a handler's InternalError message is sent to the client as an isError result on 2025-11-25 and later, so put only a fixed message in it, and log or report the cause yourself.
Retries and idempotency. Clients retry: a stateless client after a dropped stream, any client after a timeout, a model that did not see the first result. Every write tool needs a key that identifies the intent:
Natural keys when the operation has one. Drafting a proposal is "the caller's draft for this employee in this cycle"; doing it twice replaces the same draft, so the tool is idempotent by construction and annotated Tool.Idempotent.
Client request ids when two identical calls can be two real intents, such as two equal one-off bonuses. Ask for a requestId parameter, scope it by tenant and subject, and store a digest of the arguments with it, so reusing an id with different arguments is a declared conflict rather than a silent replay.
Never the JSON-RPC id. It changes on every retry.
Claim the key and perform the write in one transaction, store the first outcome, and return it for duplicates. If a call is interrupted after the write was dispatched, the outcome is unknown; the client's retry with the same key resolves it instead of writing twice.
Runnable shape.AdjustmentLedger, Principal, and the paging function are declared; the reporter Layer is provided with the capabilities.
Fragment · Type-checked
ts
import { Context, Effect, ErrorReporter, Layer, Schema } from "effect"import { McpServer, Tool, Toolkit } from "effect/ai"import { createHash } from "node:crypto"class Principal extends Context.Service<Principal, { readonly tenantId: string readonly subject: string}>()("acme/Principal") {}declare const pageOnCall: (error: Error, details: Readonly<Record<string, unknown>>) => voidclass LedgerUnavailable extends Schema.TaggedError<LedgerUnavailable>()("LedgerUnavailable", {}) {}class RequestIdReused extends Schema.TaggedError<RequestIdReused>()("RequestIdReused", { message: Schema.String}) {}// Insert-if-absent keyed by intent; a duplicate returns the first outcome.class AdjustmentLedger extends Context.Service<AdjustmentLedger, { readonly recordOnce: ( key: string, argumentsDigest: string, adjustment: { readonly tenantId: string; readonly employeeId: string; readonly amount: number } ) => Effect.Effect< { readonly adjustmentId: string; readonly replayed: boolean }, RequestIdReused | LedgerUnavailable >}>()("acme/AdjustmentLedger") {}const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex")const RecordSpotBonus = Tool.make("comp_record_spot_bonus", { description: "Record a one-off spot bonus for one employee. Generate a new requestId for each " + "intended bonus and reuse it when retrying; a retried requestId never records twice.", parameters: Schema.Struct({ requestId: Schema.String.check(Schema.isMinLength(8)), employeeId: Schema.String, amount: Schema.Finite.check(Schema.isBetween({ minimum: 1, maximum: 10_000 })) }), success: Schema.Struct({ adjustmentId: Schema.String, replayed: Schema.Boolean }), failure: RequestIdReused, dependencies: [Principal]}) .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false) .annotate(Tool.Strict, true)const BonusToolkit = Toolkit.make(RecordSpotBonus)export const BonusTools = McpServer.toolkit(BonusToolkit).pipe( Layer.provide(BonusToolkit.toLayer(Effect.gen(function*() { const ledger = yield* AdjustmentLedger return BonusToolkit.of({ comp_record_spot_bonus: Effect.fn("comp_record_spot_bonus")(function*({ requestId, employeeId, amount }) { const principal = yield* Principal const key = digest(["comp_record_spot_bonus", principal.tenantId, principal.subject, requestId]) return yield* ledger.recordOnce(key, digest({ employeeId, amount }), { tenantId: principal.tenantId, employeeId, amount }).pipe( // Infrastructure is not part of the tool contract: a defect is logged and // reported, and the client sees only the fixed internal-error message. Effect.catchTag("LedgerUnavailable", (error) => Effect.die(error)) ) }) }) }))))// Undeclared failures and defects in toolkit handlers reach every configured reporter.export const Reporting = ErrorReporter.layer([ ErrorReporter.make(({ error, attributes, severity }) => pageOnCall(error, { ...attributes, severity }))])export const ReportedBonusTools = BonusTools.pipe(Layer.provide(Reporting))
Reporters are read from the context in which the toolkit is registered, so provide the reporter Layer to the capability Layers (or above them), not inside a handler.
HttpRouter.toWebHandler builds the server Layer and returns { handler, dispose }, where handler turns a Web Request into a Response. A test can drive the real transport — origin, media-type, and header checks included — without a socket. The stateless era makes this especially simple: every request is self-describing, so there is no session to set up.
Runnable. A complete @effect/vitest test file.
Self-contained source · Type-checked
ts
import { assert, it } from "@effect/vitest"import { Effect, Layer, Schema } from "effect"import { McpProtocol, McpServer, Tool, Toolkit } from "effect/ai"import { HttpRouter } from "effect/http"const GetSalaryBand = Tool.make("comp_get_salary_band", { parameters: Schema.Struct({ jobFamily: Schema.String, level: Schema.String }), success: Schema.Struct({ min: Schema.Finite, mid: Schema.Finite, max: Schema.Finite })}).annotate(Tool.Readonly, true)const CompToolkit = Toolkit.make(GetSalaryBand)const ServerUnderTest = McpServer.layerHttp({ name: "acme-comp", version: "test", path: "/mcp", protocols: [McpProtocol.v2026_07_28], registrations: McpServer.toolkit(CompToolkit).pipe( Layer.provide(CompToolkit.toLayer({ comp_get_salary_band: () => Effect.succeed({ min: 150_000, mid: 185_000, max: 220_000 }) })) )})const ListToolsReply = Schema.Struct({ result: Schema.Struct({ tools: Schema.Array(Schema.Struct({ name: Schema.String })) })})const CallToolReply = Schema.Struct({ result: Schema.Struct({ isError: Schema.optional(Schema.Boolean), structuredContent: Schema.optional(Schema.Unknown) })})// A stateless request carries its version, capabilities, and client identity in `_meta`,// and repeats the method (and tool name) in routing headers.const post = ( handler: (request: Request) => Promise<Response>, body: { readonly id: number; readonly method: string; readonly params: Record<string, unknown> }, headers: Record<string, string> = {}) => Effect.promise(async () => { const response = await handler( new Request("http://localhost/mcp", { method: "POST", headers: { accept: "application/json, text/event-stream", "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": body.method, ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: body.id, method: body.method, params: { ...body.params, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": { name: "comp-tests", version: "1.0.0" } } } }) }) ) // A single reply is JSON; a reply that also carries notifications is an event stream. const text = await response.text() const json = response.headers.get("content-type")?.includes("text/event-stream") ? text.split("\n").filter((line) => line.startsWith("data: ")).at(-1)?.slice(6) : text return { status: response.status, body: json === undefined || json === "" ? null : JSON.parse(json) as unknown } })it.effect("serves the catalog and calls over stateless HTTP", () => Effect.gen(function*() { const { handler } = yield* Effect.acquireRelease( Effect.sync(() => HttpRouter.toWebHandler(ServerUnderTest, { disableLogger: true })), ({ dispose }) => Effect.promise(dispose) ) const listed = yield* post(handler, { id: 1, method: "tools/list", params: {} }) const tools = yield* Schema.decodeUnknownEffect(ListToolsReply)(listed.body) assert.deepStrictEqual(tools.result.tools.map((tool) => tool.name), ["comp_get_salary_band"]) const call = (id: number, args: Record<string, unknown>) => post(handler, { id, method: "tools/call", params: { name: "comp_get_salary_band", arguments: args } }, { "mcp-name": "comp_get_salary_band" }).pipe(Effect.flatMap(({ body }) => Schema.decodeUnknownEffect(CallToolReply)(body))) const ok = yield* call(2, { jobFamily: "ENG", level: "L5" }) assert.deepStrictEqual(ok.result.structuredContent, { min: 150_000, mid: 185_000, max: 220_000 }) // On 2026-07-28, arguments that fail the schema come back as an isError result. const invalid = yield* call(3, { jobFamily: "ENG" }) assert.strictEqual(invalid.result.isError, true) // A browser origin that is not allow-listed is refused before any JSON-RPC runs. const foreign = yield* post(handler, { id: 4, method: "tools/list", params: {} }, { origin: "https://elsewhere.example" }) assert.strictEqual(foreign.status, 403) }))
When the HTTP admission rules are not what is under test, McpTest.makeClient(registrations, { protocols }) is lighter: it runs the same registrations, middleware, visibility, and JSON-RPC encoding in memory, performs the handshake for you, and returns typed listTools / callTool / readResource methods. Request-level dependencies still have to be met by MCP middleware there, so a test supplies a fake Principal with a test McpServer.middleware, not with Layer.provide.
Build the rest of the suite on the same harness:
Authorization. Compose the real BearerAuth with a fake TokenVerifier Layer and assert 401 with a WWW-Authenticate header that names the metadata URL, 403 insufficient_scope for a token without comp:read, an isError result with the re-authorize hint for a missing per-tool scope, and that the metadata route answers without a token.
Tenancy. Two principals from different tenants; each call returns only its own tenant's rows, whatever the arguments say.
The round trip. Call comp_submit_proposals without answers and decode resultType: "input_required"; call again with the returned requestState and an accepted answer and assert exactly one submission; repeat the second call and assert the same batch; alter one character of the state, or send it under another principal, and assert JSON-RPC -32602; omit the elicitation capability and assert -32021.
Middleware coverage. With McpTest, assert that a test middleware which fails with an McpErrorBase code reaches the client as that JSON-RPC error, and that a McpServer.visibility check hides admin tools from tools/list and from direct calls.
Session era. For elicitation tests, initialize a 2025-11-25 session, keep the Mcp-Session-Id response header on later requests, read the elicitation/create request from the call's event stream, and answer it with a separate POST.
Catalog drift. Snapshot the tools/list result — names, descriptions, input and output schemas, hints — and review every diff. A changed tool is a changed contract for every host that remembered it.
Handler logic itself — scope checks, idempotency, tenant filters — is ordinary Effect code; test most of it below the transport with fake services, as in Testing an Effect Application.
Protocols. List only the adapters you test; at most one stateless adapter; session clients need sticky routing, stateless requests do not.
Transport boundary.allowedOrigins set to exact origins; logs on stderr for stdio; request-size limits and rate limits at the edge; no reliance on GET streams, resumption, or session expiry, which layerHttp does not implement.
Entrypoint. Capability and MCP Layers merged directly into HttpRouter.serve; shared services (database, repositories, token verifier, request-state secret) provided outside it.
Authentication. Public protected-resource metadata; 401 challenges that point at it; tokens verified for signature, issuer, audience equal to your resource URI, and expiry; the principal built from claims only.
Authorization. Baseline scope at the edge, per-tool scopes in handlers, declared InsufficientScope failures that tell the model to ask for re-authorization; Principal declared as a request-level dependency and supplied only by middleware; a low-level handler that finds none dies.
Tenancy. No tenant, actor, or role parameters; repositories take the tenant first; no token passthrough to downstream APIs.
Catalog. One verb per tool with a stable prefix; descriptions that state returns, limits, and next steps; bounded parameters; hints set explicitly; Tool.Strict on writes; EnabledWhen to trim per client, never to authorize; a snapshot test of tools/list.
Confirmation. Consequential writes confirmed through the client — elicit on session eras, InputRequired on the stateless era — with requestState sealed, expiring, bound to principal and arguments, and holding only what round 1 proved; the store re-validates at commit.
Idempotency. Every write keyed by intent (natural key or a scoped client request id), claimed atomically with the write, first outcome replayed; never keyed on the JSON-RPC id.
Failures. Domain outcomes declared; infrastructure failures turned into defects; an ErrorReporter provided to the capability Layers; fixed messages in low-level InternalErrors.
Audit. Subject, client id, tenant, tool, arguments digest, and idempotency key recorded for every write; clientInfo treated as self-reported.
Tracing. Dashboards keyed on the OpenTelemetry MCP span names (tools/call <name>) and mcp.* attributes; tool arguments recorded only where traces may hold user data (Toolkit.RecordToolArguments).
Upgrades. All MCP modules are unstable: pin Effect, rerun the in-process suite and the catalog snapshot on every upgrade.